def main(): """Start a server with a static connection.""" keys = crypto.create_keypair( seed=hashlib.sha256(b'server').digest() ) their_vk, _ = crypto.create_keypair( seed=hashlib.sha256(b'client').digest() ) conn = StaticConnection(keys, their_vk=their_vk, endpoint=None) @conn.route('did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/basicmessage/1.0/message') async def basic_message_auto_responder(msg, conn): await conn.send_async({ "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/" "basicmessage/1.0/message", "~l10n": {"locale": "en"}, "sent_time": utils.timestamp(), "content": "You said: {}".format(msg['content']) }) async def handle(request): """aiohttp handle POST.""" response = [] with conn.reply_handler(response.append): await conn.handle(await request.read()) if response: return web.Response(body=response.pop()) raise web.HTTPAccepted() app = web.Application() app.add_routes([web.post('/', handle)]) web.run_app(app, port=3000)
def __init__(self, endpoint: str): """ Initialize Backchannel static connection using predefined identities. Args: endpoint: HTTP URL of test subjects backchannel endpoint """ test_suite_vk, test_suite_sk = crypto.create_keypair( hashlib.sha256(b'aries-protocol-test-suite').digest()) test_subject_vk, _test_subject_sk = crypto.create_keypair( hashlib.sha256(b'aries-protocol-test-subject').digest()) super().__init__(test_suite_vk, test_suite_sk, test_subject_vk, endpoint) self.frontchannels: Dict[str, StaticConnection] = {}
def main(): """Start a server with a static connection.""" their_vk, _ = crypto.create_keypair( seed=hashlib.sha256(b"client").digest()) conn = Connection.from_seed( hashlib.sha256(b"server").digest(), Target(their_vk=their_vk)) @conn.route("https://didcomm.org/basicmessage/1.0/message") async def basic_message_auto_responder(msg, conn): await conn.send_async({ "@type": "https://didcomm.org/" "basicmessage/1.0/message", "~l10n": { "locale": "en" }, "sent_time": utils.timestamp(), "content": "You said: {}".format(msg["content"]), }) async def handle(request): """aiohttp handle POST.""" response = [] with conn.session(response.append) as session: await conn.handle(await request.read(), session) if response: return web.Response(body=response.pop()) raise web.HTTPAccepted() app = web.Application() app.add_routes([web.post("/", handle)]) web.run_app(app, port=os.environ.get("PORT", 3000))
def test_create_keypair_from_seed(): """Test keypair creation creates sane values.""" verkey, sigkey = crypto.create_keypair( hashlib.sha256(b"test-keypair-from-seed").digest() ) assert isinstance(verkey, bytes) assert isinstance(sigkey, bytes)
def new_frontchannel( self, *, their_vk: Union[bytes, str] = None, recipients: [Union[bytes, str]] = None, routing_keys: [Union[bytes, str]] = None, endpoint: str = None) -> StaticConnection: """ Create a new connection and add it as a frontchannel. Args: fc_vk: The new frontchannel's verification key fc_sk: The new frontchannel's signing key their_vk: The test subject's verification key for this channel endpoint: The HTTP URL to the endpoint of the test subject. Returns: Returns the new front channel (static connection). """ fc_keys = crypto.create_keypair() new_fc = StaticConnection( fc_keys, their_vk=their_vk, endpoint=endpoint, recipients=recipients, routing_keys=routing_keys ) frontchannel_index = crypto.bytes_to_b58(new_fc.verkey) self.frontchannels[frontchannel_index] = new_fc return new_fc
def create_or_recall_keys(replace: bool = False): """Generate keys and save to .keys file.""" if not os.path.exists('.keys') or replace: # Create keypair and write to file my_vk, my_sk = crypto.create_keypair() did = crypto.bytes_to_b58(my_vk[:16]) print('DID:', did) print('VK:', crypto.bytes_to_b58(my_vk)) their_vk = input('Their VK: ') endpoint = input('Their Endpoint: ') with open('.keys', 'w+') as key_file: json.dump( { 'did': did, 'my_vk': crypto.bytes_to_b58(my_vk), 'my_sk': crypto.bytes_to_b58(my_sk), 'their_vk': their_vk, 'endpoint': endpoint }, key_file) else: with open('.keys', 'r') as key_file: info = json.load(key_file) did = info['did'] my_vk = info['my_vk'] my_sk = info['my_sk'] their_vk = info['their_vk'] endpoint = info['endpoint'] return did, my_vk, my_sk, their_vk, endpoint
def new_frontchannel( self, their_vk: Union[bytes, str], endpoint: str) -> StaticConnection: """ Create a new connection and add it as a frontchannel. Args: fc_vk: The new frontchannel's verification key fc_sk: The new frontchannel's signing key their_vk: The test subject's verification key for this channel endpoint: The HTTP URL to the endpoint of the test subject. Returns: Returns the new front channel (static connection). """ fc_vk, fc_sk = crypto.create_keypair() new_fc = StaticConnection( fc_vk, fc_sk, their_vk, endpoint ) frontchannel_index = crypto.bytes_to_b58(fc_vk) self.frontchannels[frontchannel_index] = new_fc return new_fc
def generate_test_info(seed=None): """Generate connection information from seed.""" test_keys = StaticConnection.Keys(*crypto.create_keypair(seed)) test_keys_b58 = StaticConnection.Keys( crypto.bytes_to_b58(test_keys.verkey), crypto.bytes_to_b58(test_keys.sigkey)) test_did = crypto.bytes_to_b58(test_keys.verkey[:16]) return ConnectionInfo(test_keys, test_keys_b58, test_did)
def __init__(self, their_vk, endpoint): self.client = MQTTClient("client-id") self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.did_conn = StaticConnection(crypto.create_keypair(), their_vk=their_vk, endpoint=endpoint)
def main(): """Start a server with a static connection.""" keys = crypto.create_keypair( seed=hashlib.sha256(b'client').digest() ) their_vk, _ = crypto.create_keypair( seed=hashlib.sha256(b'server').digest() ) conn = StaticConnection( keys, their_vk=their_vk, endpoint='http://*****:*****@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/" "basicmessage/1.0/message", "~l10n": {"locale": "en"}, "sent_time": utils.timestamp(), "content": "The Cron Script has been executed." }, return_route='all') print('Msg from conn:', reply and reply.pretty_print())
def test_pack_unpack_with_routing_keys(alice, bob): """Test packing for a connection with routing keys.""" route1 = StaticConnection(crypto.create_keypair()) route2 = StaticConnection(crypto.create_keypair()) alice.update(routing_keys=[route1.verkey, route2.verkey]) packed_message = alice.pack({'@type': 'doc;protocol/1.0/name'}) route2_msg = route2.unpack(packed_message) assert route2_msg.type == utils.FORWARD assert route2_msg['to'] == route1.verkey_b58 assert route2_msg.mtc.is_anoncrypted() assert route2_msg.mtc.sender is None route1_msg = route1.unpack(route2_msg['msg']) assert route1_msg.type == utils.FORWARD assert route1_msg['to'] == bob.verkey_b58 assert route1_msg.mtc.is_anoncrypted() assert route1_msg.mtc.sender is None bob_msg = bob.unpack(route1_msg['msg']) assert bob_msg.type == 'doc;protocol/1.0/name' assert bob_msg.mtc.is_authcrypted() assert bob_msg.mtc.sender == alice.verkey_b58 assert bob_msg.mtc.recipient == bob.verkey_b58
def test_pack_unpack_with_routing_keys(alice, bob): """Test packing for a connection with routing keys.""" route1 = Connection.from_parts(crypto.create_keypair()) route2 = Connection.from_parts(crypto.create_keypair()) alice.target.update(routing_keys=[route1.verkey, route2.verkey]) packed_message = alice.pack({"@type": "doc;protocol/1.0/name"}) route2_msg = route2.unpack(packed_message) assert route2_msg.type == utils.FORWARD assert route2_msg["to"] == route1.verkey_b58 assert route2_msg.mtc.is_anoncrypted() assert route2_msg.mtc.sender is None route1_msg = route1.unpack(route2_msg["msg"]) assert route1_msg.type == utils.FORWARD assert route1_msg["to"] == bob.verkey_b58 assert route1_msg.mtc.is_anoncrypted() assert route1_msg.mtc.sender is None bob_msg = bob.unpack(route1_msg["msg"]) assert bob_msg.type == "doc;protocol/1.0/name" assert bob_msg.mtc.is_authcrypted() assert bob_msg.mtc.sender == alice.verkey_b58 assert bob_msg.mtc.recipient == bob.verkey_b58
async def test_connection_started_by_suite(config, temporary_channel): """ Test a connection as started by the suite. """ with temporary_channel() as conn: invite_str = build_invite('test-suite-connection-started-by-suite', conn.my_vk_b58, config['endpoint']) print('Encoding invitation:', parse_invite(invite_str)) print("\n\nInvitation encoded as URL: ", invite_str) print("Awaiting request from tested agent...") def condition(msg): print(msg) return msg.type == REQUEST request = await conn.await_message(condition=condition, timeout=30) REQUEST_SCHEMA(request) print("\nReceived request:\n", request.pretty_print()) (_, conn.their_vk_b58, conn.endpoint) = ( request['connection']['DIDDoc']['publicKey'][0]['controller'], request['connection']['DIDDoc']['publicKey'][0]['publicKeyBase58'], request['connection']['DIDDoc']['service'][0]['serviceEndpoint']) conn.their_vk = crypto.b58_to_bytes(conn.their_vk_b58) conn.my_vk, conn.my_sk = crypto.create_keypair() conn.did = crypto.bytes_to_b58(conn.my_vk[:16]) conn.my_vk_b58 = crypto.bytes_to_b58(conn.my_vk) response = build_response(request.id, conn.did, conn.my_vk_b58, config['endpoint']) print("\nSending Response (pre signature packing):\n", response.pretty_print()) response['connection~sig'] = crypto.sign_message_field( response['connection'], signer=conn.my_vk_b58, secret=conn.my_sk) del response['connection'] print("\nSending Response (post signature packing):\n", response.pretty_print()) await conn.send_async(response)
async def invitation(self, msg, _agent): """ Process an invitation. """ print(msg.pretty_print()) their_conn_key = msg['recipientKeys'][0] my_vk, my_sk = crypto.create_keypair() new_connection = StaticConnection(my_vk, my_sk, msg['recipientKeys'][0], msg['serviceEndpoint'], dispatcher=self.dispatcher) new_connection.did = crypto.bytes_to_b58(my_vk[:16]) new_connection.vk_b58 = crypto.bytes_to_b58(my_vk) new_connection.state = ConnectionState() new_connection.state.role = Roles.INVITEE new_connection.state.transition(Events.RECV_INVITE) self.connections[their_conn_key] = new_connection await new_connection.send_async({ '@type': self.type('request'), 'label': 'apts-demo-agent-as-invitee', 'connection': { 'DID': new_connection.did, 'DIDDoc': { "@context": "https://w3id.org/did/v1", "id": new_connection.did, "publicKey": [{ "id": new_connection.did + "#keys-1", "type": "Ed25519VerificationKey2018", "controller": new_connection.did, "publicKeyBase58": new_connection.vk_b58 }], "service": [{ "id": new_connection.did + ";indy", "type": "IndyAgent", "recipientKeys": [new_connection.vk_b58], "routingKeys": [], "serviceEndpoint": self.endpoint, }], } } }) new_connection.state.transition(Events.SEND_REQ)
def main(): conn = StaticConnection(crypto.create_keypair(), dispatcher=PrintDispatcher()) print('Verkey:', conn.verkey_b58) async def handle(request): """aiohttp handle POST.""" response = [] with conn.reply_handler(response.append): await conn.handle(await request.read()) if response: return web.Response(text=response.pop()) raise web.HTTPAccepted() app = web.Application() app.add_routes([web.post('/', handle)]) web.run_app(app, port=3000)
def main(): """Send a message and await the reply.""" their_vk, _ = crypto.create_keypair( seed=hashlib.sha256(b"server").digest()) conn = Connection.from_seed( hashlib.sha256(b"client").digest(), Target( their_vk=their_vk, endpoint="http://*****:*****@type": "https://didcomm.org/basicmessage/1.0/message", "~l10n": { "locale": "en" }, "sent_time": utils.timestamp(), "content": "The Cron script has been executed.", }, return_route="all", ) print("Msg from conn:", reply and reply.pretty_print())
def create_invitation(self): """ Create and return an invite. """ conn_vk, conn_sk = crypto.create_keypair() connection = StaticConnection(conn_vk, conn_sk, b'', '', dispatcher=self.dispatcher) conn_vk_b58 = crypto.bytes_to_b58(conn_vk) self.connections[conn_vk_b58] = connection connection.state = ConnectionState() connection.state.role = Roles.INVITER connection.state.transition(Events.SEND_INVITE) invitation = Message({ '@type': self.type('invitation'), 'label': 'static-iiw', 'recipientKeys': [conn_vk_b58], 'serviceEndpoint': self.endpoint, 'routingKeys': [] }) invitation_url = '{}?c_i={}'.format( self.endpoint, crypto.bytes_to_b64(invitation.serialize().encode())) return connection, invitation_url
def bob_keys(): """Generate bob's keys.""" yield Keys(*crypto.create_keypair())
def test_keys(): """Generate keys for test end of connection.""" yield Keys(*crypto.create_keypair())
def example_keys(): """Generate keys for example end of connection.""" yield Keys(*crypto.create_keypair())
def alice_keys(): """Alice's keys.""" return StaticConnection.Keys(*crypto.create_keypair())
def bob_keys(): """Bob's keys.""" return StaticConnection.Keys(*crypto.create_keypair())
def bob_keys(): """Generate bob's keys.""" yield StaticConnection.Keys(*crypto.create_keypair())
def alice_keys(): """Generate alice's keys.""" yield StaticConnection.Keys(*crypto.create_keypair())
def alice_keys(): """Generate alice's keys.""" yield Keys(*crypto.create_keypair())
async def request(self, msg, _agent): """ Process a request. """ print(msg.pretty_print()) connection = self.connections[msg.mtc.ad['recip_vk']] connection.state.transition(Events.RECV_REQ) # Old connection keys, need to sign new keys with these conn_vk, conn_sk = connection.my_vk, connection.my_sk # Relationship keys, replacing connection keys my_vk, my_sk = crypto.create_keypair() # Update connection connection.my_vk, connection.my_sk = my_vk, my_sk connection.did = crypto.bytes_to_b58(my_vk[:16]) connection.vk_b58 = crypto.bytes_to_b58(my_vk) connection.their_did = msg['connection']['DIDDoc']['publicKey'][0][ 'controller'] connection.their_vk = crypto.b58_to_bytes( msg['connection']['DIDDoc']['publicKey'][0]['publicKeyBase58']) connection.endpoint = msg['connection']['DIDDoc']['service'][0][ 'serviceEndpoint'] del self.connections[msg.mtc.ad['recip_vk']] self.connections[connection.vk_b58] = connection # Prepare response connection_block = { 'DID': connection.did, 'DIDDoc': { "@context": "https://w3id.org/did/v1", "id": connection.did, "publicKey": [{ "id": connection.did + "#keys-1", "type": "Ed25519VerificationKey2018", "controller": connection.did, "publicKeyBase58": connection.vk_b58 }], "service": [{ "id": connection.did + ";indy", "type": "IndyAgent", "recipientKeys": [connection.vk_b58], "routingKeys": [], "serviceEndpoint": self.endpoint, }], } } connection.state.transition(Events.SEND_RESP) await connection.send_async({ '@type': self.type('response'), '~thread': { 'thid': msg.id, 'sender_order': 0 }, 'connection~sig': crypto.sign_message_field(connection_block, crypto.bytes_to_b58(conn_vk), conn_sk) })
def keys(): """ Generate keys for testing. """ alice_vk, alice_sk = crypto.create_keypair() bob_vk, bob_sk = crypto.create_keypair() return alice_vk, alice_sk, bob_vk, bob_sk
def alice_keys(): """Alice's keys.""" return Keys(*crypto.create_keypair())
def bob_keys(): """Bob's keys.""" return Keys(*crypto.create_keypair())
from aries_staticagent import crypto vk_bytes, sk_bytes = crypto.create_keypair() did_bytes = vk_bytes[0:16] vk = crypto.bytes_to_b58(vk_bytes) sk = crypto.bytes_to_b58(sk_bytes) did = crypto.bytes_to_b58(did_bytes) print('For full agent:\n\tDID: {}\n\tVK: {}\n'.format(did, vk)) print('For static agent:\n\tVK: {}\n\tSK: {}'.format(vk, sk))