def recall_connection(): if not os.path.exists('.keys'): return None with open('.keys', 'r') as key_file: info = json.load(key_file) return StaticConnection(info['my_vk'], info['my_sk'], info['their_vk'], info['endpoint'])
def main(): """Start a server with a static connection.""" my_vk, my_sk = crypto.create_keypair( seed=hashlib.sha256(b'server').digest()) their_vk, _ = crypto.create_keypair( seed=hashlib.sha256(b'client').digest()) conn = StaticConnection(my_vk, my_sk, their_vk, 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 conn(dispatcher): """ Function scoped static connection fixture. This connection isn't actually connected to anything. """ yield StaticConnection( (b'', b''), dispatcher=dispatcher )
def test_their_vk_and_recipients_raises_error(my_test_info, their_test_info): """Test specifying both their_vk and recipients raises an error.""" with pytest.raises(ValueError): StaticConnection( my_test_info.keys, their_vk=their_test_info.keys.verkey, recipients=[their_test_info.keys.verkey] )
def main(): """Main.""" args = config() _did, my_vk, my_sk, their_vk, endpoint = create_or_recall_keys( args.replace) conn = StaticConnection(my_vk, my_sk, their_vk, endpoint) print('Pinging connection...') reply = conn.send_and_await_reply( { "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0/ping", "response_requested": True }, return_route='all', timeout=5) print('Response:', reply.pretty_print()) @conn.route('did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/basicmessage/1.0/message') async def basic_message_auto_responder(msg, conn): """Automatically respond to basicmessages.""" 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=args.port)
def main(): """Send message from cron job.""" args = config() conn = StaticConnection( (args.my_verkey, args.my_sigkey), their_vk=args.their_verkey, endpoint=args.endpoint, ) conn.send({ "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/" "basicmessage/1.0/message", "~l10n": { "locale": "en" }, "sent_time": utils.timestamp(), "content": "The Cron script was executed." })
def main(): """Main.""" args = config() _did, my_vk, my_sk, their_vk, endpoint = create_or_recall_keys( args.replace) conn = StaticConnection(my_vk, my_sk, their_vk, endpoint) print('Pinging connection...') reply = conn.send_and_await_reply( { "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0/ping", "response_requested": True }, return_route='all', timeout=5) print('Response:', reply.pretty_print())
def main(): """ Cron example. """ args = config() conn = StaticConnection( (args.mypublickey, args.myprivatekey), their_vk=args.endpointkey, endpoint=args.endpoint, ) conn.send({ "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/" "basicmessage/1.0/message", "~l10n": { "locale": "en" }, "sent_time": utils.timestamp(), "content": "The Cron Script has been executed." })
def main(): """Create StaticConnection and start web server.""" args = config() conn = StaticConnection( (args.my_verkey, args.my_sigkey), their_vk=args.their_verkey, endpoint=args.endpoint, ) @conn.route("did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/basicmessage/1.0/message") async def basic_message(msg, conn): """Respond to a basic message.""" 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 ws_handle(request): """Handle WS requests.""" sock = web.WebSocketResponse() await sock.prepare(request) with conn.session(sock.send_bytes) as session: async for msg in sock: if msg.type == aiohttp.WSMsgType.BINARY: await conn.handle(msg.data, session) elif msg.type == aiohttp.WSMsgType.ERROR: print( 'ws connection closed with exception %s' % sock.exception() ) if not session.returning(): await sock.close() return sock async def post_handle(request): """Handle posted messages.""" response = [] with conn.session(response.append) as session: await conn.handle(await request.read(), session) if response: return web.Response(text=response.pop()) raise web.HTTPAccepted() app = web.Application() app.add_routes([ web.get('/', ws_handle), web.post('/', post_handle) ]) web.run_app(app, port=args.port)
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 test_give_routing_keys_b58(my_test_info, their_test_info): """Test routing_keys set when specified.""" conn = StaticConnection( my_test_info.keys, their_vk=their_test_info.keys.verkey, routing_keys=[their_test_info.keys_b58.verkey] ) assert conn.recipients == [their_test_info.keys.verkey] assert conn.routing_keys == [their_test_info.keys.verkey]
def test_b58_inputs_with_their_info(my_test_info, their_test_info): """Test that valid b58 inputs yield expected values.""" conn = StaticConnection(my_test_info.keys_b58, their_vk=their_test_info.keys_b58.verkey) assert conn.verkey == my_test_info.keys.verkey assert conn.sigkey == my_test_info.keys.sigkey assert conn.verkey_b58 == my_test_info.keys_b58.verkey assert conn.did == my_test_info.did assert conn.recipients == [their_test_info.keys.verkey]
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 main(): """Main.""" args = config() _did, my_vk, my_sk, their_vk, endpoint = create_or_recall_keys( args.replace) conn = StaticConnection(my_vk, my_sk, their_vk, endpoint) session = Session(conn) session.ping() session.get_connections() session.get_credential_definitions()
def main(): """ Cron with return route example. """ args = config() conn = StaticConnection( args.mypublickey, args.myprivatekey, args.endpointkey, args.endpoint, ) # TODO: a.returnroute = "thread" @conn.route( "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0/ping_response") async def ping_response(_msg, _conn): """ Response to a ping. """ print("Ping Response Returned") conn.send({ "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0/ping", "response_requested": True })
def main(): """ Create connection and start web server. """ args = config() conn = StaticConnection( (args.mypublickey, args.myprivatekey), their_vk=args.endpointkey, endpoint=args.endpoint, ) bmc = BasicMessageCounter() conn.route_module(bmc) async def handle(request): """ aiohttp handle POST. """ await conn.handle(await request.read()) raise web.HTTPAccepted() app = web.Application() app.add_routes([web.post('/', handle)]) web.run_app(app, port=args.port)
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 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 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(): """ Create StaticConnection and start web server. """ args = config() conn = StaticConnection( args.mypublickey, args.myprivatekey, args.endpointkey, args.endpoint, ) @conn.route("did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/basicmessage/1.0/message") async def basic_message(msg, conn): """ Respond to a basic message """ 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(text=response.pop()) raise web.HTTPAccepted() app = web.Application() app.add_routes([web.post('/', handle)]) web.run_app(app, port=args.port)
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 alice_keys(): """Generate alice's keys.""" yield StaticConnection.Keys(*crypto.create_keypair())
def test_bad_inputs(args): """Test that bad inputs raise an error.""" with pytest.raises(TypeError): StaticConnection(*args)
def test_update(my_test_info, their_test_info): their_new_info = generate_test_info() conn = StaticConnection(my_test_info.keys, their_vk=their_test_info.keys.verkey, routing_keys=[their_test_info.keys.verkey], endpoint='endpoint1') assert conn.verkey == my_test_info.keys.verkey assert conn.sigkey == my_test_info.keys.sigkey assert conn.verkey_b58 == my_test_info.keys_b58.verkey assert conn.did == my_test_info.did assert conn.recipients == [their_test_info.keys.verkey] assert conn.routing_keys == [their_test_info.keys.verkey] assert conn.endpoint == 'endpoint1' with pytest.raises(ValueError): conn.update(their_vk=their_new_info.keys.verkey, recipients=[their_new_info.keys.verkey]) conn.update(their_vk=their_new_info.keys.verkey, routing_keys=[their_new_info.keys.verkey], endpoint='endpoint2') assert conn.recipients == [their_new_info.keys.verkey] assert conn.routing_keys == [their_new_info.keys.verkey] assert conn.endpoint == 'endpoint2' conn.update( their_vk=their_test_info.keys.verkey, routing_keys=[their_test_info.keys.verkey], ) assert conn.recipients == [their_test_info.keys.verkey] assert conn.routing_keys == [their_test_info.keys.verkey] assert conn.endpoint == 'endpoint2' conn.update(recipients=[their_new_info.keys.verkey]) assert conn.recipients == [their_new_info.keys.verkey] conn.update(recipients=[their_test_info.keys_b58.verkey]) assert conn.recipients == [their_test_info.keys.verkey]
def example_keys(): """Generate keys for example end of connection.""" yield StaticConnection.Keys(*crypto.create_keypair())
def test_keys(): """Generate keys for test end of connection.""" yield StaticConnection.Keys(*crypto.create_keypair())
def connection(example_keys, test_keys): """Connection fixture.""" return StaticConnection(test_keys, their_vk=example_keys.verkey)
def bob(bob_keys, alice_keys): """ Create Bob's StaticConnection. """ yield StaticConnection(bob_keys, their_vk=alice_keys.verkey)
def connection_ws(example_keys, test_keys): """Connection fixture with ws send.""" return StaticConnection(test_keys, their_vk=example_keys.verkey, send=utils.ws_send)