Ejemplo n.º 1
0
async def run():
    # В данном примере участвуют два агента, один из которых является Steward (т.е. имеет право записи в реестр),
    steward_agent_params = await get_agent_params("agent1")
    # Второго агента назовем клиент
    client_agent_params = await get_agent_params("agent2")

    # Работаем от имени клиента
    async with sirius_sdk.context(**client_agent_params):
        # Клиентский агент создает новый DID и записывает его в свой кошелек
        agent_did, agent_verkey = await sirius_sdk.DID.create_and_store_my_did(
        )
        print(agent_did)

    # Клиент по независимому каналу связи передает свой новый DID и verkey (публичный ключ, ассоциированый с DID) Steward-у,
    # чтобы он зарегистрировал его в реестре

    # Работаем от имени Steward-а
    async with sirius_sdk.context(**steward_agent_params):
        # Получаем DID первого агента, под которым он известен как Steward
        steward_did, _ = await sirius_sdk.DID.create_and_store_my_did(
            seed='000000000000000000000000Steward1')
        # работаем с реестром под именем default
        dkms = await sirius_sdk.ledger('default')
        # записываем DID клинета в реестр
        ok, resp = await dkms.write_nym(submitter_did=steward_did,
                                        target_did=agent_did,
                                        ver_key=agent_verkey)
        print(ok)
Ejemplo n.º 2
0
async def test_sane(test_suite: ServerTestSuite):
    params = test_suite.get_agent_params('agent1')
    async with sirius_sdk.context(params['server_address'],
                                  params['credentials'], params['p2p']):
        inst1 = _current_hub()
        inst2 = _current_hub()
    assert id(inst1) == id(inst2)

    params1 = test_suite.get_agent_params('agent1')
    params2 = test_suite.get_agent_params('agent2')

    async with sirius_sdk.context(params1['server_address'],
                                  params1['credentials'], params1['p2p']):
        ping1 = await sirius_sdk.ping()
        endpoints1 = await sirius_sdk.endpoints()
        my_did_list1 = await sirius_sdk.DID.list_my_dids_with_meta()

    async with sirius_sdk.context(params2['server_address'],
                                  params2['credentials'], params2['p2p']):
        ping2 = await sirius_sdk.ping()
        endpoints2 = await sirius_sdk.endpoints()
        my_did_list2 = await sirius_sdk.DID.list_my_dids_with_meta()

    endpoints1 = [e.address for e in endpoints1]
    endpoints2 = [e.address for e in endpoints2]
    my_did_list1 = [d['did'] for d in my_did_list1]
    my_did_list2 = [d['did'] for d in my_did_list2]
    assert ping1 is True
    assert ping2 is True
    assert set(endpoints1) != set(endpoints2)
    assert set(my_did_list1) != set(my_did_list2)
Ejemplo n.º 3
0
async def test_invitee_back_compatibility(indy_agent: IndyAgent, test_suite: ServerTestSuite):
    their_invitaton = await indy_agent.create_invitation(label='Test Invitee')
    invitation = Invitation.from_url(their_invitaton['url'])
    invitee = test_suite.get_agent_params('agent1')

    # Init invitee
    async with sirius_sdk.context(invitee['server_address'], invitee['credentials'], invitee['p2p']):
        did, verkey = await sirius_sdk.DID.create_and_store_my_did()
        invitee_side = sirius_sdk.Pairwise.Me(did, verkey)

    await run_coroutines(
        run_invitee(
            invitee['server_address'], invitee['credentials'], invitee['p2p'], invitation, 'Invitee', invitee_side, True
        ),
        read_events(
            invitee['server_address'], invitee['credentials'], invitee['p2p']
        )
    )
    invitation_pairwise = None
    async with sirius_sdk.context(invitee['server_address'], invitee['credentials'], invitee['p2p']):
        async for i, pairwise in sirius_sdk.PairwiseList.enumerate():
            if pairwise.me.did == invitee_side.did:
                invitation_pairwise = pairwise
                break
    assert invitation_pairwise is not None
Ejemplo n.º 4
0
async def test_inviter_back_compatibility(indy_agent: IndyAgent, test_suite: ServerTestSuite, agent1: sirius_sdk.Agent):
    inviter = test_suite.get_agent_params('agent1')
    # Init inviter
    async with sirius_sdk.context(inviter['server_address'], inviter['credentials'], inviter['p2p']):
        inviter_endpoint_address = [e for e in await sirius_sdk.endpoints() if e.routing_keys == []][0].address
        connection_key = await sirius_sdk.Crypto.create_key()
        inviter_endpoint_address = replace_url_components(inviter_endpoint_address, pytest.test_suite_overlay_address)
        invitation = Invitation(label='Inviter', endpoint=inviter_endpoint_address, recipient_keys=[connection_key])
        invitation_url = invitation.invitation_url
        did, verkey = await sirius_sdk.DID.create_and_store_my_did()
        inviter_side = sirius_sdk.Pairwise.Me(did, verkey)

    await run_coroutines(
        run_inviter(
            inviter['server_address'], inviter['credentials'], inviter['p2p'], connection_key, inviter_side, True
        ),
        indy_agent.invite(invitation_url=invitation_url),
    )

    invitated_pairwise = None
    async with sirius_sdk.context(inviter['server_address'], inviter['credentials'], inviter['p2p']):
        async for i, p in sirius_sdk.PairwiseList.enumerate():
            assert isinstance(p, sirius_sdk.Pairwise)
            if p.me.did == inviter_side.did:
                invitated_pairwise = p
                break
    assert invitated_pairwise is not None
Ejemplo n.º 5
0
 async def init_creds():
     global med_cred_def, med_schema, boarding_pass_cred_def, boarding_pass_schema
     async with sirius_sdk.context(**LABORATORY['sdk']):  # работаем в контексте ковид-лаборатории (все вызовы будут происходить от имени агента ковид-лаборатории)
         # ковид лаборатория выпускает стандартизированную схему (форму) теста на ковид
         med_cred_def, med_schema = await create_med_creds(LABORATORY['did'])
     async with sirius_sdk.context(**AIR_COMPANY['sdk']):  # работаем в контексте авиакомпании (все вызовы будут происходить от имени агента авиакомпании)
         # авиакомпания выпускает стандартизированную схему (форму) посадочного талона
         boarding_pass_cred_def, boarding_pass_schema = await create_boarding_pass_creds(AIR_COMPANY['did'])
Ejemplo n.º 6
0
async def test_did_doc_extra_fields(test_suite: ServerTestSuite):
    inviter = test_suite.get_agent_params('agent1')
    invitee = test_suite.get_agent_params('agent2')

    # Get endpoints
    async with sirius_sdk.context(inviter['server_address'], inviter['credentials'], inviter['p2p']):
        inviter_endpoint_address = [e for e in await sirius_sdk.endpoints() if e.routing_keys == []][0].address
        connection_key = await sirius_sdk.Crypto.create_key()
        invitation = Invitation(label='Inviter', endpoint=inviter_endpoint_address, recipient_keys=[connection_key])

    # Init Me
    async with sirius_sdk.context(inviter['server_address'], inviter['credentials'], inviter['p2p']):
        did, verkey = await sirius_sdk.DID.create_and_store_my_did()
        inviter_me = sirius_sdk.Pairwise.Me(did, verkey)
    async with sirius_sdk.context(invitee['server_address'], invitee['credentials'], invitee['p2p']):
        did, verkey = await sirius_sdk.DID.create_and_store_my_did()
        invitee_me = sirius_sdk.Pairwise.Me(did, verkey)

    await run_coroutines(
        run_inviter(
            inviter['server_address'], inviter['credentials'], inviter['p2p'], connection_key, inviter_me,
            did_doc_extra={
                'creator': {'@id': 'uuid-xxx-yyy'},
                'extra': 'Any'
            }
        ),
        run_invitee(
            invitee['server_address'], invitee['credentials'], invitee['p2p'], invitation, 'Invitee', invitee_me,
            did_doc_extra={
                'creator': {'@id': 'uuid-www-zzz'},
                'extra': 'Test'
            }
        )
    )

    # Check for Inviter
    async with sirius_sdk.context(inviter['server_address'], inviter['credentials'], inviter['p2p']):
        pairwise = await sirius_sdk.PairwiseList.load_for_verkey(invitee_me.verkey)
        assert pairwise is not None
        assert pairwise.their.did == invitee_me.did
        assert pairwise.me.did_doc is not None
        assert pairwise.me.did_doc.get('creator', {}) == {'@id': 'uuid-xxx-yyy'}
        assert pairwise.me.did_doc.get('extra', None) == 'Any'
        assert pairwise.their.did_doc is not None
        assert pairwise.their.did_doc.get('creator', {}) == {'@id': 'uuid-www-zzz'}
        assert pairwise.their.did_doc.get('extra', None) == 'Test'
    # Check for Invitee
    async with sirius_sdk.context(invitee['server_address'], invitee['credentials'], invitee['p2p']):
        pairwise = await sirius_sdk.PairwiseList.load_for_verkey(inviter_me.verkey)
        assert pairwise is not None
        assert pairwise.their.did == inviter_me.did
        assert pairwise.me.did_doc is not None
        assert pairwise.me.did_doc.get('creator', {}) == {'@id': 'uuid-www-zzz'}
        assert pairwise.me.did_doc.get('extra', None) == 'Test'
        assert pairwise.their.did_doc is not None
        assert pairwise.their.did_doc.get('creator', {}) == {'@id': 'uuid-xxx-yyy'}
        assert pairwise.their.did_doc.get('extra', None) == 'Any'
Ejemplo n.º 7
0
async def generate_invitations_qr_codes() -> (str, str):
    # BANK
    async with sirius_sdk.context(**BANK):
        try:
            connection_key = await sirius_sdk.Crypto.create_key(
                seed='0000000000000000SIRIUS_BANK_CONN')
        except sirius_sdk.indy_exceptions.WalletItemAlreadyExists:
            log(f'Bank: conn key {CONN_KEY_BANK} already exists')
        else:
            log(f'Bank: conn key {connection_key} was created')
            assert connection_key == CONN_KEY_BANK
        endpoints = await sirius_sdk.endpoints()
        simple_endpoint = [e for e in endpoints if e.routing_keys == []][0]
        bank_invitation = sirius_sdk.aries_rfc.Invitation(
            label='Sirius Demo bank',
            recipient_keys=[CONN_KEY_BANK],
            endpoint=simple_endpoint.address,
            did=DID_BANK)
        log('Bank: invitation')
        log(json.dumps(bank_invitation, indent=2, sort_keys=True))

        # Sirius SDK provide method to generate URL for QR
        # bank_qr_url = await sirius_sdk.generate_qr_code(bank_invitation.invitation_url)
        # print('BANK QR URL: ' + bank_qr_url)

    # EMPLOYER
    async with sirius_sdk.context(**EMPLOYER):
        try:
            connection_key = await sirius_sdk.Crypto.create_key(
                seed='000000000000SIRIUS_EMPLOYER_CONN')
        except sirius_sdk.indy_exceptions.WalletItemAlreadyExists:
            log(f'Employer: conn key {CONN_KEY_EMPLOYER} already exists')
        else:
            log(f'Employer: conn key {connection_key} was created')
            assert connection_key == CONN_KEY_EMPLOYER
        endpoints = await sirius_sdk.endpoints()
        simple_endpoint = [e for e in endpoints if e.routing_keys == []][0]
        employer_invitation = sirius_sdk.aries_rfc.Invitation(
            label='Sirius Demo employer',
            recipient_keys=[CONN_KEY_EMPLOYER],
            endpoint=simple_endpoint.address,
            did=DID_EMPLOYER)
        log('Employer: invitation')
        log(json.dumps(employer_invitation, indent=2, sort_keys=True))

        # Sirius SDK provide method to generate URL for QR
        # employer_qr_url = await sirius_sdk.generate_qr_code(employer_invitation.invitation_url)
        # print('EMPLOYER QR URL: ' + employer_qr_url)

    return 'https://socialsirius.com' + bank_invitation.invitation_url, \
           'https://socialsirius.com' + employer_invitation.invitation_url
Ejemplo n.º 8
0
async def test_update_pairwise_metadata(test_suite: ServerTestSuite):
    inviter = test_suite.get_agent_params('agent1')
    invitee = test_suite.get_agent_params('agent2')

    # Get endpoints
    async with sirius_sdk.context(inviter['server_address'], inviter['credentials'], inviter['p2p']):
        inviter_endpoint_address = [e for e in await sirius_sdk.endpoints() if e.routing_keys == []][0].address
        connection_key = await sirius_sdk.Crypto.create_key()
        invitation = Invitation(label='Inviter', endpoint=inviter_endpoint_address, recipient_keys=[connection_key])
    async with sirius_sdk.context(invitee['server_address'], invitee['credentials'], invitee['p2p']):
        invitee_endpoint_address = [e for e in await sirius_sdk.endpoints() if e.routing_keys == []][0].address

    # Init Me
    async with sirius_sdk.context(inviter['server_address'], inviter['credentials'], inviter['p2p']):
        did, verkey = await sirius_sdk.DID.create_and_store_my_did()
        inviter_side = sirius_sdk.Pairwise.Me(did, verkey)
    async with sirius_sdk.context(invitee['server_address'], invitee['credentials'], invitee['p2p']):
        did, verkey = await sirius_sdk.DID.create_and_store_my_did()
        invitee_side = sirius_sdk.Pairwise.Me(did, verkey)
    # Manually set pairwise list
    async with sirius_sdk.context(inviter['server_address'], inviter['credentials'], inviter['p2p']):
        await sirius_sdk.DID.store_their_did(invitee_side.did, invitee_side.verkey)
        p = sirius_sdk.Pairwise(
            me=inviter_side,
            their=sirius_sdk.Pairwise.Their(
                invitee_side.did, 'Invitee', invitee_endpoint_address, invitee_side.verkey
            )
        )
        await sirius_sdk.PairwiseList.create(p)
    async with sirius_sdk.context(invitee['server_address'], invitee['credentials'], invitee['p2p']):
        await sirius_sdk.DID.store_their_did(inviter_side.did, inviter_side.verkey)
        p = sirius_sdk.Pairwise(
            me=invitee_side,
            their=sirius_sdk.Pairwise.Their(
                inviter_side.did, 'Inviter', inviter_endpoint_address, inviter_side.verkey
            )
        )
        await sirius_sdk.PairwiseList.create(p)

    await run_coroutines(
        run_inviter(
            inviter['server_address'], inviter['credentials'], inviter['p2p'], connection_key, inviter_side
        ),
        run_invitee(
            invitee['server_address'], invitee['credentials'], invitee['p2p'], invitation, 'Invitee', invitee_side
        )
    )

    # Check for Inviter
    async with sirius_sdk.context(inviter['server_address'], inviter['credentials'], inviter['p2p']):
        pairwise = await sirius_sdk.PairwiseList.load_for_did(invitee_side.did)
        assert pairwise.metadata != {}
        assert pairwise.metadata is not None

    # Check for Invitee
    async with sirius_sdk.context(invitee['server_address'], invitee['credentials'], invitee['p2p']):
        pairwise = await sirius_sdk.PairwiseList.load_for_did(inviter_side.did)
        assert pairwise.metadata != {}
        assert pairwise.metadata is not None
Ejemplo n.º 9
0
async def issue_credential(schema: sirius_sdk.Schema,
                           cred_def: sirius_sdk.CredentialDefinition,
                           first_name: str,
                           last_name: str,
                           age: int,
                           prover: sirius_sdk.Pairwise,
                           cred_id: str = None):
    async with sirius_sdk.context(**ISSUER):
        feature_0036 = sirius_sdk.aries_rfc.Issuer(holder=prover)
        log('Issuer: start issuing...')
        success = await feature_0036.issue(
            values={
                'first_name': first_name,
                'last_name': last_name,
                'age': age
            },
            schema=schema,
            cred_def=cred_def,
            comment='Hello, it is your Transcript',
            cred_id=cred_id or f'cred-id-' + uuid.uuid4().hex)
        if success:
            log('Issuer: issuing finished successfully')
        else:
            log('Issuer: issuing finished with ERROR')
            if feature_0036.problem_report:
                log('Issuer problem report:')
                log(
                    json.dumps(feature_0036.problem_report,
                               indent=2,
                               sort_keys=True))
        return success
Ejemplo n.º 10
0
 async def inviter_routine():
     # Работаем от имени Inviter
     async with sirius_sdk.context(**inviter_agent_params):
         # Создадим новый приватный DID для соединений в рамках ранее созданного invitation
         my_did, my_verkey = await sirius_sdk.DID.create_and_store_my_did()
         me = sirius_sdk.Pairwise.Me(did=my_did, verkey=my_verkey)
         inviter_endpoint = [
             e for e in await sirius_sdk.endpoints()
             if e.routing_keys == []
         ][0]
         # Создадим экземпляр автомата для установки соединения на стороне Inviter-а
         inviter_machine = Inviter(me=me,
                                   connection_key=connection_key,
                                   my_endpoint=inviter_endpoint,
                                   logger=Logger())
         listener = await sirius_sdk.subscribe()
         # Ждем сообщение от Invitee
         async for event in listener:
             request = event['message']
             # Inviter получает ConnRequest от Invitee и проверяет, что он относится к ранее созданному приглашению
             if isinstance(
                     request, ConnRequest
             ) and event['recipient_verkey'] == connection_key:
                 # запускаем процесс установки соединения
                 ok, pairwise = await inviter_machine.create_connection(
                     request)
                 # Сохраняем соединение в Wallet
                 await sirius_sdk.PairwiseList.ensure_exists(pairwise)
                 return
 async def sender(server_address: str, credentials: bytes,
                  p2p: sirius_sdk.P2PConnection, **kwargs):
     nonlocal thread_id
     async with sirius_sdk.context(server_address, credentials, p2p):
         msg = sirius_sdk.aries_rfc.Ping(comment='Test Ping')
         co = sirius_sdk.CoProtocolThreadedTheirs(thread_id, [pw1, pw2])
         await co.send(msg)
Ejemplo n.º 12
0
async def run_inviter(
        uri: str, credentials: bytes, p2p: sirius_sdk.P2PConnection, expected_connection_key: str,
        me: sirius_sdk.Pairwise.Me = None, replace_endpoints: bool = False, did_doc_extra: dict = None
):
    async with sirius_sdk.context(uri, credentials, p2p):
        endpoints_ = await sirius_sdk.endpoints()
        my_endpoint = [e for e in endpoints_ if e.routing_keys == []][0]
        if replace_endpoints:
            new_address = replace_url_components(my_endpoint.address, pytest.test_suite_overlay_address)
            my_endpoint = Endpoint(new_address, my_endpoint.routing_keys, is_default=my_endpoint.is_default)
        listener = await sirius_sdk.subscribe()
        async for event in listener:
            connection_key = event['recipient_verkey']
            if expected_connection_key == connection_key:
                request = event['message']
                assert isinstance(request, ConnRequest)
                if replace_endpoints:
                    request['connection']['did_doc']['service'][0]['serviceEndpoint'] = replace_url_components(
                        request['connection']['did_doc']['service'][0]['serviceEndpoint'],
                        pytest.old_agent_overlay_address
                    )
                # Setup state machine
                if me is None:
                    my_did, my_verkey = await sirius_sdk.DID.create_and_store_my_did()
                    me = sirius_sdk.Pairwise.Me(did=my_did, verkey=my_verkey)
                # create connection
                machine = Inviter(me, connection_key, my_endpoint)
                ok, pairwise = await machine.create_connection(request, did_doc_extra)
                assert ok is True
                await sirius_sdk.PairwiseList.ensure_exists(pairwise)
        pass
Ejemplo n.º 13
0
async def read_events(uri: str, credentials: bytes, p2p: sirius_sdk.P2PConnection):
    async with sirius_sdk.context(uri, credentials, p2p):
        listener = await sirius_sdk.subscribe()
        async for event in listener:
            print('========= EVENT ============')
            print(json.dumps(event, indent=2, sort_keys=True))
            print('============================')
async def run_invitee(uri: str,
                      credentials: bytes,
                      p2p: sirius_sdk.P2PConnection,
                      invitation: Invitation,
                      my_label: str,
                      me: sirius_sdk.Pairwise.Me = None,
                      replace_endpoints: bool = False,
                      did_doc_extra: dict = None):
    async with sirius_sdk.context(uri, credentials, p2p):
        if me is None:
            my_did, my_verkey = await sirius_sdk.DID.create_and_store_my_did()
            me = sirius_sdk.Pairwise.Me(did=my_did, verkey=my_verkey)
        endpoints_ = await sirius_sdk.endpoints()
        my_endpoint = [e for e in endpoints_ if e.routing_keys == []][0]
        if replace_endpoints:
            new_address = replace_url_components(
                my_endpoint.address, pytest.test_suite_overlay_address)
            my_endpoint = Endpoint(new_address,
                                   my_endpoint.routing_keys,
                                   is_default=my_endpoint.is_default)
            new_address = replace_url_components(
                invitation['serviceEndpoint'],
                pytest.old_agent_overlay_address)
            invitation['serviceEndpoint'] = new_address
        # Create and start machine
        machine = Invitee(me, my_endpoint)
        ok, pairwise = await machine.create_connection(invitation=invitation,
                                                       my_label=my_label,
                                                       did_doc=did_doc_extra)
        assert ok is True
        await sirius_sdk.PairwiseList.ensure_exists(pairwise)
Ejemplo n.º 15
0
async def verify_credential(prover: sirius_sdk.Pairwise, network_name: str,
                            proof_request: dict):
    async with sirius_sdk.context(**VERIFIER):
        if 'nonce' not in proof_request:
            proof_request['nonce'] = await sirius_sdk.AnonCreds.generate_nonce(
            )
        log('Verifier: start verify...')
        dkms = await sirius_sdk.ledger(network_name)
        feature_0037 = sirius_sdk.aries_rfc.Verifier(prover=prover,
                                                     ledger=dkms)
        success = await feature_0037.verify(proof_request)
        if success:
            log('Verifier: verification finished successfully')
            log('presented revealed part of credentials')
            log(
                json.dumps(feature_0037.requested_proof['revealed_attrs'],
                           indent=8))
        else:
            log('Verifier: verification with ERROR')
            if feature_0037.problem_report:
                log('Issuer problem report:')
                log(
                    json.dumps(feature_0037.problem_report,
                               indent=2,
                               sort_keys=True))
        return success
Ejemplo n.º 16
0
async def acceptor(
        topic: str, context: dict,
        microledger: List[sirius_sdk.Pairwise], ledger: AbstractLedger
):
    async with sirius_sdk.context(**context):
        listener = await sirius_sdk.subscribe()
        log(f'{topic}: start listening...')
        async for event in listener:
            if event.pairwise.their.did in [p.their.did for p in microledger]:
                msg_type = event.message.get('@type', None)
                leader: sirius_sdk.Pairwise = event.pairwise
                if msg_type == TYPE_BFT_CONSENSUS_PROPOSE:
                    log(f'{topic}: start accepting transaction')
                    state_machine = BFTPluggableConsensus(
                        microledger=microledger,
                        ledger=ledger
                    )
                    success = await state_machine.accept_transaction(
                        leader=leader,
                        txn_propose=event.message
                    )
                    if success:
                        log(f'{topic}: !!! transaction was successfully accepted')
                        log(f'{topic}: Ledger size: {ledger.size}')
                        log(f'{topic}: Ledger : [%s]' % ', '.join(str(txn) for txn in ledger.committed_txns))
                    else:
                        log(f'{topic}: !!! transaction was not accepted due to error')
                else:
                    log(f'{topic}: unexpected message type: {msg_type}')
            else:
                log(f'{topic}: ignore requests out of Microledger P2P space')
Ejemplo n.º 17
0
async def run_verifier(uri: str,
                       credentials: bytes,
                       p2p: sirius_sdk.P2PConnection,
                       prover: Pairwise,
                       proof_request: dict,
                       translation: List[AttribTranslation] = None) -> bool:
    async with sirius_sdk.context(uri, credentials, p2p):
        ledger = await sirius_sdk.ledger('default')
        machine = Verifier(prover=prover, ledger=ledger)
        success = await machine.verify(proof_request,
                                       translation=translation,
                                       comment='I am Verifier',
                                       proto_version='1.0')
        if not success:
            print(
                '===================== Verifier terminated with error ===================='
            )
            if machine.problem_report:
                print(
                    json.dumps(machine.problem_report,
                               indent=2,
                               sort_keys=True))
            print(
                '======================================================================='
            )
        return success
Ejemplo n.º 18
0
 async def __detect_current_environment(self) -> Environment:
     async with sirius_sdk.context(**BAY_DOOR):
         # Open communication channel to transmit requests and await events from participants
         communication = sirius_sdk.CoProtocolThreadedTheirs(
             thid='request-id-' + uuid.uuid4().hex,
             theirs=self.airlocks,
             time_to_live=5)
         log('Bay Door: check environment')
         # SWITCH method suspend runtime thread until events will be accumulated or error occur
         results = await communication.switch(
             message=Message({'@type': TYPE_STATE_REQUEST}))
         has_error = any(
             [ok is False for airlock, (ok, _) in results.items()])
         if has_error:
             ret = Environment.HOSTILE  # if almost one airlock unreachable environment is hostile
         else:
             # Parse responses
             airlock_statuses = [
                 response['status']
                 for airlock, (_, response) in results.items()
             ]
             if all([s == State.CLOSED.value for s in airlock_statuses]):
                 ret = Environment.FRIENDLY  # All airlocks should be closed
             else:
                 ret = Environment.HOSTILE
         log(f'Bay Door: current environment: {ret}')
         return ret
Ejemplo n.º 19
0
 async def create_track_id(self, track_id: str,
                           genesis: List[Transaction]) -> bool:
     """MarketPlace may create new goods track-id"""
     async with sirius_sdk.context(
             **self.agent_conn,
             # Dependency injection for Ledger storage (in-memory, file, database, etc)
             microledgers=self.storage):
         log(f'{self.caption}: propose new track-id: {track_id} ...')
         consensus = simple_consensus.MicroLedgerSimpleConsensus(
             self.me, time_to_live=15)
         ok, ledger = await consensus.init_microledger(
             ledger_name=track_id,
             participants=self.participants,
             genesis=genesis)
         if ok:
             log(f'{self.caption}: propose for new track-id: [{track_id}] was successfully accepted by All participants'
                 f'root_hash: {ledger.root_hash}')
         else:
             log(f'{self.caption}: propose for new track-id: [{track_id}] terminated with ERROR!!!'
                 )
             if consensus.problem_report:
                 log(f'{self.caption}: problem-report')
                 log(
                     json.dumps(consensus.problem_report,
                                indent=2,
                                sort_keys=True))
         return ok
Ejemplo n.º 20
0
 async def propose_transactions(self, track_id: str,
                                transactions: List[Transaction]) -> bool:
     async with sirius_sdk.context(
             **self.agent_conn,
             # Dependency injection for Ledger storage (in-memory, file, database, etc)
             microledgers=self.storage):
         log(f'{self.caption}: propose new transactions to track-id: {track_id} ...'
             )
         consensus = simple_consensus.MicroLedgerSimpleConsensus(self.me)
         ledger = await sirius_sdk.Microledgers.ledger(track_id)
         ok, txns = await consensus.commit(ledger=ledger,
                                           participants=self.participants,
                                           transactions=transactions)
         if ok:
             log(f'{self.caption}: propose new transactions to track-id: [{track_id}] was successfully accepted'
                 f'root_hash: {ledger.root_hash}')
         else:
             log(f'{self.caption}: propose new transactions to track-id: [{track_id}] terminated with ERROR!!!'
                 )
             if consensus.problem_report:
                 log(f'{self.caption}: problem-report')
                 log(
                     json.dumps(consensus.problem_report,
                                indent=2,
                                sort_keys=True))
         return ok
Ejemplo n.º 21
0
 async def process_connection_request(
         self, request: sirius_sdk.aries_rfc.ConnRequest,
         actor: sirius_sdk.Pairwise):
     async with sirius_sdk.context(**self.agent_conn):
         if actor is not None:
             log(f'{self.caption}: update p2p connection for {actor.their.label}'
                 )
         else:
             log(f'{self.caption}: establish new p2p connection')
         endpoints = await sirius_sdk.endpoints()
         my_endpoint = [e for e in endpoints if e.routing_keys == []][0]
         feature_0160 = sirius_sdk.aries_rfc.Inviter(
             me=self.me,
             connection_key=MARKET_CONN_KEY,
             my_endpoint=my_endpoint,
         )
         success, p2p = await feature_0160.create_connection(request)
         if success:
             await sirius_sdk.PairwiseList.ensure_exists(p2p)
             log(f'{self.caption}: pairwise established successfully')
             log(json.dumps(p2p.metadata, indent=2, sort_keys=True))
             # Involve Customer to digital services
             await self.run_virtual_assistant(p2p)
         else:
             log(f'{self.caption}: error while establish P2P connection')
             if feature_0160.problem_report:
                 log('problem report')
                 log(
                     json.dumps(feature_0160.problem_report,
                                indent=2,
                                sort_keys=True))
Ejemplo n.º 22
0
    async def generate_invite_qr(self) -> str:
        async with sirius_sdk.context(**self.agent_conn):
            try:
                connection_key = await sirius_sdk.Crypto.create_key(
                    seed='0000000000000000MARKETPLACE_CONN')
            except sirius_sdk.indy_exceptions.WalletItemAlreadyExists:
                log(f'{self.caption}: conn key {MARKET_CONN_KEY} already exists'
                    )
            else:
                log(f'{self.caption}: conn key {connection_key} was created')
                assert connection_key == MARKET_CONN_KEY
            endpoints = await sirius_sdk.endpoints()
            simple_endpoint = [e for e in endpoints if e.routing_keys == []][0]
            market_invitation = sirius_sdk.aries_rfc.Invitation(
                label='MarketPlace',
                recipient_keys=[MARKET_CONN_KEY],
                endpoint=simple_endpoint.address,
                did=DID_MARKET)
            log(f'{self.caption}: invitation')
            log(json.dumps(market_invitation, indent=2, sort_keys=True))

            qr_url = await sirius_sdk.generate_qr_code(
                market_invitation.invitation_url)
            print('MARKET QR URL: ' + qr_url)
            return qr_url
Ejemplo n.º 23
0
async def test_spawn_child_routines(test_suite: ServerTestSuite):
    params = test_suite.get_agent_params('agent1')

    hub_parent = None
    hub_child1 = None
    hub_child2 = None

    async def child1():
        nonlocal hub_child1
        hub_child1 = _current_hub()

    async def child2():
        nonlocal hub_child2
        hub_child2 = _current_hub()

    async def parent():
        nonlocal hub_parent
        hub_parent = _current_hub()
        await child1()
        fut = asyncio.ensure_future(child2())
        await asyncio.wait([fut])

    async with sirius_sdk.context(params['server_address'],
                                  params['credentials'], params['p2p']):
        await parent()

    assert id(hub_parent) == id(hub_child1)
    assert id(hub_parent) != id(hub_child2)
    assert id(hub_child1) != id(hub_child2)
Ejemplo n.º 24
0
 async def listen(self):
     async with sirius_sdk.context(**self.hub_credentials): # работаем в контексте лабы (все вызовы выполняются от имени агента лабы)
         await self.init_microledger()
         listener = await sirius_sdk.subscribe()
         async for event in listener:
             if isinstance(event.message, ProposeTransactionsMessage): # получен запрос на добавление транзакции в микрореестр положительных ковид справок
                 machine = MicroLedgerSimpleConsensus(self.me)
                 await machine.accept_commit(event.pairwise, event.message)
Ejemplo n.º 25
0
 async def listen(self):
     async with sirius_sdk.context(**self.hub_credentials):  # работаем в контексте аэропорта (все вызовы выполняются от имени агента аэропорта)
         listener = await sirius_sdk.subscribe()
         async for event in listener:
             if isinstance(event.message, InitRequestLedgerMessage):  # обработка предложения создания микрореестра положительных ковид справок
                 await self.process_init_microledger(event)
             elif isinstance(event.message, ProposeTransactionsMessage):  # получен запрос на добавление транзакции в микрореестр положительных ковид справок
                 await self.process_new_commit(event)
Ejemplo n.º 26
0
 async def responder(server_address: str, credentials: bytes,
                     p2p: sirius_sdk.P2PConnection, *args, **kwargs):
     async with sirius_sdk.context(server_address, credentials, p2p):
         listener = await sirius_sdk.subscribe()
         async for event in listener:
             if isinstance(event.message, sirius_sdk.agent.Question):
                 await make_answer('Yes', event.message, event.pairwise)
                 return True
 async def reader(server_address: str, credentials: bytes,
                  p2p: sirius_sdk.P2PConnection, **kwargs):
     nonlocal rcv_messages
     async with sirius_sdk.context(server_address, credentials, p2p):
         listener = await sirius_sdk.subscribe()
         async for event in listener:
             rcv_messages.append(event.message)
             return
async def test_establish_connection(test_suite: ServerTestSuite):
    inviter = test_suite.get_agent_params('agent1')
    invitee = test_suite.get_agent_params('agent2')

    # Get endpoints
    async with sirius_sdk.context(inviter['server_address'],
                                  inviter['credentials'], inviter['p2p']):
        inviter_endpoint_address = [
            e for e in await sirius_sdk.endpoints() if e.routing_keys == []
        ][0].address
        connection_key = await sirius_sdk.Crypto.create_key()
        invitation = Invitation(label='Inviter',
                                endpoint=inviter_endpoint_address,
                                recipient_keys=[connection_key])

    # Init Me
    async with sirius_sdk.context(inviter['server_address'],
                                  inviter['credentials'], inviter['p2p']):
        did, verkey = await sirius_sdk.DID.create_and_store_my_did()
        inviter_me = sirius_sdk.Pairwise.Me(did, verkey)
    async with sirius_sdk.context(invitee['server_address'],
                                  invitee['credentials'], invitee['p2p']):
        did, verkey = await sirius_sdk.DID.create_and_store_my_did()
        invitee_me = sirius_sdk.Pairwise.Me(did, verkey)

    await run_coroutines(
        run_inviter(inviter['server_address'], inviter['credentials'],
                    inviter['p2p'], connection_key, inviter_me),
        run_invitee(invitee['server_address'], invitee['credentials'],
                    invitee['p2p'], invitation, 'Invitee', invitee_me))

    # Check for Inviter
    async with sirius_sdk.context(inviter['server_address'],
                                  inviter['credentials'], inviter['p2p']):
        pairwise = await sirius_sdk.PairwiseList.load_for_verkey(
            invitee_me.verkey)
        assert pairwise is not None
        assert pairwise.their.did == invitee_me.did
    # Check for Invitee
    async with sirius_sdk.context(invitee['server_address'],
                                  invitee['credentials'], invitee['p2p']):
        pairwise = await sirius_sdk.PairwiseList.load_for_verkey(
            inviter_me.verkey)
        assert pairwise is not None
        assert pairwise.their.did == inviter_me.did
Ejemplo n.º 29
0
 async def requester(server_address: str, credentials: bytes,
                     p2p: sirius_sdk.P2PConnection, *args, **kwargs):
     async with sirius_sdk.context(server_address, credentials, p2p):
         q = sirius_sdk.agent.Question(valid_responses=['Yes', 'No'],
                                       question_text='Test question',
                                       question_detail='Question detail')
         q.set_ttl(30)
         success, answer = await ask_and_wait_answer(q, req2resp)
         return success and answer.response == 'Yes'
async def routine_of_txn_committer(uri: str, credentials: bytes,
                                   p2p: P2PConnection, me: Pairwise.Me,
                                   participants: List[str],
                                   ledger: Microledger, txns: List[dict]):
    async with sirius_sdk.context(uri, credentials, p2p):
        machine = MicroLedgerSimpleConsensus(me)
        txns = [Transaction.create(txn) for txn in txns]
        success, txns = await machine.commit(ledger, participants, txns)
        return success, txns