Skip to content

Commit 8259840

Browse files
committed
fix: do not require indy or bbs to be installed
Signed-off-by: Timo Glastra <[email protected]>
1 parent cd4e4b0 commit 8259840

File tree

14 files changed

+152
-58
lines changed

14 files changed

+152
-58
lines changed

aries_cloudagent/config/default_context.py

+10-6
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
from ..resolver.did_resolver import DIDResolver
1414
from ..resolver.did_resolver_registry import DIDResolverRegistry
1515
from ..tails.base import BaseTailsServer
16-
from ..ledger.indy import IndySdkLedgerPool, IndySdkLedgerPoolProvider
1716

1817
from ..protocols.actionmenu.v1_0.base_service import BaseMenuService
1918
from ..protocols.actionmenu.v1_0.driver_service import DriverMenuService
@@ -22,6 +21,7 @@
2221
from ..protocols.introduction.v0_1.demo_service import DemoIntroductionService
2322
from ..transport.wire_format import BaseWireFormat
2423
from ..utils.stats import Collector
24+
from ..utils.dependencies import is_indy_sdk_module_installed
2525

2626

2727
class DefaultContextBuilder(ContextBuilder):
@@ -64,12 +64,16 @@ async def build_context(self) -> InjectionContext:
6464
async def bind_providers(self, context: InjectionContext):
6565
"""Bind various class providers."""
6666

67-
# MTODO: move to IndySdkProfileManager if possible
6867
# Bind global indy pool provider to be able to share pools between wallets
69-
context.injector.bind_provider(
70-
IndySdkLedgerPool,
71-
CachedProvider(IndySdkLedgerPoolProvider(), ("ledger.pool_name",)),
72-
)
68+
# It is important the ledger pool provider is available in the base context
69+
# so it can be shared by all wallet instances. If we set it in the indy sdk
70+
# profile provider it could mean other wallets won't have access to the provider
71+
if is_indy_sdk_module_installed():
72+
from ..ledger.indy import IndySdkLedgerPool, IndySdkLedgerPoolProvider
73+
context.injector.bind_provider(
74+
IndySdkLedgerPool,
75+
CachedProvider(IndySdkLedgerPoolProvider(), ("ledger.pool_name",)),
76+
)
7377

7478
context.injector.bind_provider(ProfileManager, ProfileManagerProvider())
7579

aries_cloudagent/ledger/routes.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
from .base import BaseLedger, Role as LedgerRole
2121
from .endpoint_type import EndpointType
2222
from .error import BadLedgerRequestError, LedgerError, LedgerTransactionError
23-
from .indy import Role
2423

2524

2625
class LedgerModulesResultSchema(OpenAPISchema):
@@ -93,7 +92,7 @@ class RegisterLedgerNymQueryStringSchema(OpenAPISchema):
9392
description="Role",
9493
required=False,
9594
validate=validate.OneOf(
96-
[r.name for r in Role if isinstance(r.value[0], int)] + ["reset"]
95+
[r.name for r in LedgerRole if isinstance(r.value[0], int)] + ["reset"]
9796
),
9897
)
9998

aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/handler.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -53,13 +53,15 @@
5353
CredentialIssuancePurpose.term,
5454
AuthenticationProofPurpose.term,
5555
}
56+
SUPPORTED_ISSUANCE_SUITES = {Ed25519Signature2018}
57+
SIGNATURE_SUITE_KEY_TYPE_MAPPING = {Ed25519Signature2018: KeyType.ED25519}
5658

57-
SUPPORTED_ISSUANCE_SUITES = {Ed25519Signature2018, BbsBlsSignature2020}
5859

59-
SIGNATURE_SUITE_KEY_TYPE_MAPPING = {
60-
Ed25519Signature2018: KeyType.ED25519,
61-
BbsBlsSignature2020: KeyType.BLS12381G2,
62-
}
60+
# We only want to add bbs suites to supported if the module is installed
61+
if BbsBlsSignature2020.BBS_SUPPORTED:
62+
SUPPORTED_ISSUANCE_SUITES.add(BbsBlsSignature2020)
63+
SIGNATURE_SUITE_KEY_TYPE_MAPPING[BbsBlsSignature2020] = KeyType.BLS12381G2
64+
6365

6466
PROOF_TYPE_SIGNATURE_SUITE_MAPPING = {
6567
suite.signature_type: suite

aries_cloudagent/protocols/present_proof/indy/pres_preview.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
from marshmallow import fields
88

9-
from ....ledger.indy import IndySdkLedger
9+
from ....ledger.base import BaseLedger
1010
from ....messaging.models.base import BaseModel, BaseModelSchema
1111
from ....messaging.util import canon
1212
from ....messaging.valid import INDY_CRED_DEF_ID, INDY_PREDICATE
@@ -292,7 +292,7 @@ async def indy_proof_request(
292292
name: str = None,
293293
version: str = None,
294294
nonce: str = None,
295-
ledger: IndySdkLedger = None,
295+
ledger: BaseLedger = None,
296296
non_revoc_intervals: Mapping[str, NonRevocationInterval] = None,
297297
) -> dict:
298298
"""
+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""Dependency related util methods."""
2+
3+
import sys
4+
5+
6+
def is_indy_sdk_module_installed():
7+
"""Check whether indy (indy-sdk) module is installed.
8+
9+
Returns:
10+
bool: Whether indy (indy-sdk) is installed.
11+
12+
"""
13+
try:
14+
# Check if already imported
15+
if "indy" in sys.modules:
16+
return True
17+
18+
# Try to import
19+
import indy # noqa: F401
20+
21+
return True
22+
except ModuleNotFoundError:
23+
# Not installed if import went wrong
24+
return False
25+
26+
27+
def is_ursa_bbs_signatures_module_installed():
28+
"""Check whether ursa_bbs_signatures module is installed.
29+
30+
Returns:
31+
bool: Whether ursa_bbs_signatures is installed.
32+
33+
"""
34+
try:
35+
# Check if already imported
36+
if "ursa_bbs_signatures" in sys.modules:
37+
return True
38+
39+
# Try to import
40+
import ursa_bbs_signatures # noqa: F401
41+
42+
return True
43+
except ModuleNotFoundError:
44+
# Not installed if import went wrong
45+
return False
46+
47+
48+
def assert_ursa_bbs_signatures_installed():
49+
"""Assert ursa_bbs_signatures module is installed."""
50+
if not is_ursa_bbs_signatures_module_installed():
51+
raise Exception("ursa_bbs_signatures module not installed")

aries_cloudagent/vc/ld_proofs/suites/BbsBlsSignature2020Base.py

+3
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,16 @@
55
from typing import List
66

77
from ..error import LinkedDataProofException
8+
from ....utils.dependencies import is_ursa_bbs_signatures_module_installed
89
from ..document_loader import DocumentLoaderMethod
910
from .LinkedDataProof import LinkedDataProof
1011

1112

1213
class BbsBlsSignature2020Base(LinkedDataProof, metaclass=ABCMeta):
1314
"""Base class for BbsBlsSignature suites."""
1415

16+
BBS_SUPPORTED = is_ursa_bbs_signatures_module_installed()
17+
1518
def _create_verify_proof_data(
1619
self, *, proof: dict, document: dict, document_loader: DocumentLoaderMethod
1720
) -> List[str]:

aries_cloudagent/vc/ld_proofs/suites/BbsBlsSignatureProof2020.py

+16-12
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,27 @@
33
from os import urandom
44
from pyld import jsonld
55
from typing import List
6+
from .BbsBlsSignature2020Base import BbsBlsSignature2020Base
67

7-
from ursa_bbs_signatures import (
8-
create_proof as bls_create_proof,
9-
verify_proof as bls_verify_proof,
10-
CreateProofRequest,
11-
VerifyProofRequest,
12-
get_total_message_count,
13-
ProofMessage,
14-
BlsKeyPair,
15-
ProofMessageType,
16-
)
17-
8+
if BbsBlsSignature2020Base.BBS_SUPPORTED:
9+
from ursa_bbs_signatures import (
10+
create_proof as bls_create_proof,
11+
verify_proof as bls_verify_proof,
12+
CreateProofRequest,
13+
VerifyProofRequest,
14+
get_total_message_count,
15+
ProofMessage,
16+
BlsKeyPair,
17+
ProofMessageType,
18+
)
19+
20+
from ....utils.dependencies import assert_ursa_bbs_signatures_installed
1821
from ....wallet.util import b64_to_bytes, bytes_to_b64
1922
from ..crypto import KeyPair
2023
from ..error import LinkedDataProofException
2124
from ..validation_result import ProofResult
2225
from ..document_loader import DocumentLoaderMethod
2326
from ..purposes import ProofPurpose
24-
from .BbsBlsSignature2020Base import BbsBlsSignature2020Base
2527
from .BbsBlsSignature2020 import BbsBlsSignature2020
2628
from .LinkedDataProof import DeriveProofResult
2729

@@ -61,6 +63,7 @@ async def derive_proof(
6163
nonce: bytes = None,
6264
):
6365
"""Derive proof for document, return dict with derived document and proof."""
66+
assert_ursa_bbs_signatures_installed()
6467

6568
# Validate that the input proof document has a proof compatible with this suite
6669
if proof.get("type") not in self.supported_derive_proof_types:
@@ -222,6 +225,7 @@ async def verify_proof(
222225
document_loader: DocumentLoaderMethod,
223226
) -> ProofResult:
224227
"""Verify proof against document and proof purpose."""
228+
assert_ursa_bbs_signatures_installed()
225229
try:
226230
proof["type"] = self.mapped_derived_proof_type
227231

aries_cloudagent/vc/ld_proofs/suites/tests/test_BbsBlsSignature2020.py

+2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from asynctest import TestCase, mock as async_mock
2+
import pytest
23

34

45
from .....did.did_key import DIDKey
@@ -21,6 +22,7 @@
2122
from ..BbsBlsSignature2020 import BbsBlsSignature2020
2223

2324

25+
@pytest.mark.ursa_bbs_signatures
2426
class TestBbsBlsSignature2020(TestCase):
2527
test_seed = "testseed000000000000000000000001"
2628

aries_cloudagent/vc/ld_proofs/suites/tests/test_BbsBlsSignatureProof2020.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from asynctest import TestCase, mock as async_mock
2-
2+
import pytest
33

44
from .....did.did_key import DIDKey
55
from .....wallet.key_pair import KeyType
@@ -30,6 +30,7 @@
3030
from ..BbsBlsSignatureProof2020 import BbsBlsSignatureProof2020
3131

3232

33+
@pytest.mark.ursa_bbs_signatures
3334
class TestBbsBlsSignatureProof2020(TestCase):
3435
test_seed = "testseed000000000000000000000001"
3536

aries_cloudagent/wallet/bbs.py

+20-10
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,25 @@
11
"""BBS+ crypto."""
22

33
from typing import List, Tuple
4-
from ursa_bbs_signatures import (
5-
SignRequest,
6-
VerifyRequest,
7-
BlsKeyPair,
8-
sign as bbs_sign,
9-
verify as bbs_verify,
10-
BbsException as NativeBbsException,
11-
)
12-
from ursa_bbs_signatures._ffi.FfiException import FfiException
134

5+
from ..utils.dependencies import (
6+
assert_ursa_bbs_signatures_installed,
7+
is_ursa_bbs_signatures_module_installed,
8+
)
149
from ..core.error import BaseError
15-
1610
from ..wallet.util import random_seed
1711

12+
if is_ursa_bbs_signatures_module_installed():
13+
from ursa_bbs_signatures import (
14+
SignRequest,
15+
VerifyRequest,
16+
BlsKeyPair,
17+
sign as bbs_sign,
18+
verify as bbs_verify,
19+
BbsException as NativeBbsException,
20+
)
21+
from ursa_bbs_signatures._ffi.FfiException import FfiException
22+
1823

1924
class BbsException(BaseError):
2025
"""Base BBS exception."""
@@ -31,6 +36,7 @@ def sign_messages_bls12381g2(messages: List[bytes], secret: bytes):
3136
bytes: The signature
3237
3338
"""
39+
assert_ursa_bbs_signatures_installed()
3440

3541
messages = [message.decode("utf-8") for message in messages]
3642
try:
@@ -59,6 +65,8 @@ def verify_signed_messages_bls12381g2(
5965
True if verified, else False
6066
6167
"""
68+
assert_ursa_bbs_signatures_installed()
69+
6270
key_pair = BlsKeyPair(public_key=public_key)
6371
messages = [message.decode("utf-8") for message in messages]
6472

@@ -86,6 +94,8 @@ def create_bls12381g2_keypair(seed: bytes = None) -> Tuple[bytes, bytes]:
8694
A tuple of (public key, secret key)
8795
8896
"""
97+
assert_ursa_bbs_signatures_installed()
98+
8999
if not seed:
90100
seed = random_seed()
91101

aries_cloudagent/wallet/crypto.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@
1313
from .error import WalletError
1414
from .util import bytes_to_b58, b64_to_bytes, b58_to_bytes, random_seed
1515
from .key_type import KeyType
16+
from .bbs import (
17+
create_bls12381g2_keypair,
18+
verify_signed_messages_bls12381g2,
19+
BbsException,
20+
sign_messages_bls12381g2,
21+
)
1622

1723

1824
def create_keypair(key_type: KeyType, seed: bytes = None) -> Tuple[bytes, bytes]:
@@ -34,7 +40,6 @@ def create_keypair(key_type: KeyType, seed: bytes = None) -> Tuple[bytes, bytes]
3440
return create_ed25519_keypair(seed)
3541
elif key_type == KeyType.BLS12381G2:
3642
# This ensures python won't crash if bbs is not installed and not used
37-
from .bbs import create_bls12381g2_keypair
3843

3944
return create_bls12381g2_keypair(seed)
4045
else:
@@ -133,8 +138,6 @@ def sign_message(
133138
secret=secret,
134139
)
135140
elif key_type == KeyType.BLS12381G2:
136-
from .bbs import sign_messages_bls12381g2
137-
138141
return sign_messages_bls12381g2(messages=messages, secret=secret)
139142
else:
140143
raise WalletError(f"Unsupported key type: {key_type.key_type}")
@@ -186,8 +189,6 @@ def verify_signed_message(
186189
message=messages[0], signature=signature, verkey=verkey
187190
)
188191
elif key_type == KeyType.BLS12381G2:
189-
from .bbs import verify_signed_messages_bls12381g2, BbsException
190-
191192
try:
192193
return verify_signed_messages_bls12381g2(
193194
messages=messages, signature=signature, public_key=verkey

aries_cloudagent/wallet/tests/test_bbs.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from unittest import TestCase
2-
2+
import pytest
33

44
from ..bbs import (
55
sign_messages_bls12381g2,
@@ -15,6 +15,7 @@
1515
SEED = "seed000000000001"
1616

1717

18+
@pytest.mark.ursa_bbs_signatures
1819
class TestBBS(TestCase):
1920
def test_create_keypair_seed(self):
2021
(pk, sk) = create_bls12381g2_keypair(SEED)

0 commit comments

Comments
 (0)