예제 #1
0
    async def generate_invitation(self,
                                  auto_accept: bool = True,
                                  multi_use: bool = False,
                                  display_qr: bool = False) -> tuple:
        """
        Create a connection invitation

        :param auto_accept: Auto accept connection handshake?
        :param multi_use: Can this invite be used multiple times?
        :param display_qr: Bool to indicate whether a QR code should be displayed in the terminal
        :return: A tuple containing the connection id and base64 encoded invite url
        """
        invitation_id, invitation = self.api_handler.create_invitation(
            alias=self.identity, multi_use=multi_use, auto_accept=auto_accept)
        if display_qr:
            qr = QRCode(border=1)
            qr.add_data(json.dumps(invitation))
            log_msg(
                f"Use the following JSON to accept the invite from another demo agent. Or use the QR code to connect from a mobile agent.",
                color=LOG_COLOR)
            log_msg(f"Invitation Data:",
                    json.dumps(invitation),
                    color=LOG_COLOR)
            qr.print_ascii(invert=True)
        return invitation_id, invitation
예제 #2
0
def log_args(args) -> None:
    """
    Function that logs command line arguments to the terminal

    :param args: A list of args
    """
    log_msg(f"Starting Agent with args:", color=LOG_COLOR)
    for arg in vars(args):
        # TODO: ledger port als argument toevoegen
        log_msg(f"\t{arg:<30}{getattr(args, arg)}", color=LOG_COLOR)
예제 #3
0
    async def terminate(self):
        """
        Terminate the Agent by closing the admin API, webhook server and docker container.

        :return: True if termination is complete
        """
        log_msg(f"Shutting down {self.identity}", color=LOG_COLOR)

        await self.client_session.close()  # Close session to admin api
        await self.webhook_server.terminate()  # Shut down web hooks first
        await self.docker_container.terminate()  # now shut down the agent

        return True
예제 #4
0
    async def issue_credential(self) -> dict:
        """
        Issue a credential to one of the agent. Promts the user for inputs.

        :return: The result of the issue credential operation
        """
        connection_id = await prompt("Connection ID <id>: ")
        cred_def_id = await prompt("Connection definition ID <id>: ")
        schema = json.loads(await prompt("Schema <schema>: "))
        log_msg(schema)
        attributes = json.loads(await prompt("Attributes <attributes>: "))
        log_msg(attributes)
        return self.api_handler.issue_credential(connection_id, cred_def_id,
                                                 attributes, schema)
예제 #5
0
    async def initialize(self) -> None:
        """
        Start a webhook server, register a DID and start a docker container process
        """
        await self.webhook_server.start_process()
        await self.register_did()
        await self.docker_container.start_process()

        # TODO:  Timeout toevoegen, wanneer verkeerde key wordt gegeven, geeft hij alsog aan dat er een goeie connectie is
        if self.api_handler.test_connection() is False:
            return
        self.admin_url = f"{self.transport_protocol}://{self.local_ip}:{self.start_port+1}"
        self.endpoint = f"{self.transport_protocol}://{self.local_ip}:{self.start_port}"
        log_msg(f"Admin URL is at: {self.admin_url}", color=LOG_COLOR)
        log_msg(f"Endpoint URL is at: {self.endpoint}", color=LOG_COLOR)
예제 #6
0
    async def start_process(self):
        """
        Start a webhook process

        Add a webhook route, setup callback function and start the webhook server
        """
        log_msg("Start webhook server", color=LOG_COLOR)
        app = web.Application()
        app.add_routes(
            [web.post("/webhooks/topic/{topic}/", self._receive_webhook)])

        runner = web.AppRunner(app)
        await runner.setup()

        self.webhook_site = web.TCPSite(runner, "0.0.0.0", self.webhook_port)
        await self.webhook_site.start()
        log_msg("Webhook server started", color=LOG_COLOR)
예제 #7
0
    async def handle_webhook(self, topic: str, payload, headers: dict):
        """
        Higher level function to handle incoming webhooks. 
        Deducts a function to call based on received webhook topic
        """

        log_msg("Topic", topic, color=LOG_COLOR)
        if topic != "webhook":  # would recurse
            handler = f"handle_{topic}"
            wallet_id = headers.get("x-wallet-id")
            method = getattr(self, handler, None)
            if method:
                log_msg("Agent called controller webhook: %s%s%s%s",
                        handler,
                        f"\nPOST {self.webhook_url}/topic/{topic}/",
                        (f" for wallet: {wallet_id}" if wallet_id else ""),
                        (f" with payload: \n{json.dumps(payload, indent=4)}\n"
                         if payload else ""),
                        color=LOG_COLOR)
                asyncio.get_event_loop().create_task(method(payload))
            else:
                log_msg(
                    f"Error: agent {self.identity} "
                    f"has no method {handler} "
                    f"to handle webhook on topic {topic}",
                    color=LOG_COLOR)
예제 #8
0
    async def register_did(self,
                           ledger_ip: str = None,
                           alias: str = None,
                           did: str = None,
                           verkey: str = None,
                           role: str = "TRUST_ANCHOR"):
        """
        Function registers a DID on the ledger

        :param ledger_url: The ledger_url of the ledger
        :param alias: The alias to gerister on the ledger
        :param did: Did to register
        :param verkey: Verkey to register
        :param role: role of the registered DID
        :raises Exception: raises an exception when an invalid response is given by the ledger
        """
        log_msg(f"Registering {self.identity} ...", color=LOG_COLOR)
        data = {"alias": alias or self.identity, "role": role}
        if did and verkey:
            data["did"] = did
            data["verkey"] = verkey
        else:
            data["seed"] = self.seed
        async with self.client_session.post(f"{self.ledger_url}/register",
                                            json=data) as resp:
            if resp.status != 200:
                raise Exception(
                    f"Error registering DID, response code {resp.status}")
            nym_info = await resp.json()
            self.did = nym_info["did"]
            log_msg(f"nym_info: {nym_info}", color=LOG_COLOR)
        log_msg(f"Registered DID: {self.did}", color=LOG_COLOR)
예제 #9
0
    async def handle_issue_credential(self, message):
        state = message["state"]
        cred_ex_id = message["credential_exchange_id"]

        log_msg(
            f"Credential: state = {state}, credential_exchange_id {cred_ex_id}",
            color=LOG_COLOR)

        if state == "offer_received":
            response = self.api_handler.send_credential_request(cred_ex_id)
            log_msg("response", response, color=LOG_COLOR)
        elif state == "done":
            cred_id = message["cred_id_stored"]
            log_msg(f"Stored credential {cred_id} in wallet", color=LOG_COLOR)
예제 #10
0
    async def start_process(self, wait: bool = True) -> None:
        """
        Start the container process by executing a docker subprocess.
        Optionally, the function waits for 10 seconds in order to give the container time to start-up

        :param wait: Wait for 10 seconds to make sure the docker container has been initialized
        """
        log_msg("Start Docker container", color=LOG_COLOR)

        agent_args = self.get_process_args()
        log_msg(f"Starting agent with args: {agent_args}", color=LOG_COLOR)

        self.container_process = await asyncio.create_subprocess_exec(  # TODO: Catch invalid key/ arguments error.
            *agent_args)
        if wait:
            # TODO: Timeout verplaatsen naar api handler
            await asyncio.sleep(10.0)
        log_msg("Docker container started", color=LOG_COLOR)
예제 #11
0
    async def terminate(self):
        """
        Shut down the Docker container process

        :raises Exception: raises exception if docker container did not terminate in time
        """
        log_msg(f"Shutting down agent", color=LOG_COLOR)

        # Check if process exists and is running
        if self.container_process and self.container_process.returncode is None:
            try:
                self.container_process.terminate()
                await asyncio.wait_for(self.container_process.communicate(),
                                       timeout=1)
                log_msg(
                    f"Docker Container exited with return code {self.container_process.returncode}",
                    color=LOG_COLOR)
            except asyncio.TimeoutError:
                msg = f"Process did not terminate in time"
                log_msg(msg, color=LOG_COLOR)
                await self.container_process.kill()
                raise Exception(msg)
예제 #12
0
 async def handle_basicmessages(self, message):
     log_msg(f"Received message:", message["content"], color=LOG_COLOR)
예제 #13
0
 async def terminate(self):
     log_msg(f"Shutting down web hooks site", color=LOG_COLOR)
     if self.webhook_site:
         await self.webhook_site.stop()
         await asyncio.sleep(0.5)
예제 #14
0
async def main(args):
    """
    Main function that: initializes the aries agent and
    show a prompt loop to interact with the agent
    """
    global aries_cloudagent_agent

    incoming_tunnel = LocalTunnel(args.port)
    api_tunnel = LocalTunnel(args.port+1)
    
    await incoming_tunnel.start_local_tunnel()
    await api_tunnel.start_local_tunnel()
    
    log_msg("incoming_tunnel_url: ", incoming_tunnel.tunnel_url, color=LOG_COLOR)
    log_msg("api_tunnel_url: ", api_tunnel.tunnel_url, color=LOG_COLOR)
    
    aries_cloudagent_agent = Agent(
        identity=args.identity,
        start_port=args.port,
        transport_protocol=args.transport_protocol,
        endpoint=incoming_tunnel.tunnel_url,
        ledger_url=args.ledger_url,
        local_ip=args.local_ip,
        wallet_name=args.wallet_name,
        wallet_key=args.wallet_key,
        seed=args.seed,
        public_did=args.public_did,
        auto_response=args.no_auto
    )

    await aries_cloudagent_agent.initialize()

    options = ("1. Show Connections\n2. Generate invitation\n3. Receive inivtaiotn\n4. Send Message\n5. Get connection state\n6. Create Schema\n7. Create credential definition\n8. Issue credential\n9. Get credentials\n10. Exit\n")

    # async for option in prompt_loop(options):
    #     # try:
    #     if int(option) == 1:
    #         connections = await aries_cloudagent_agent.connections()
    #         log_msg(f"{json.dumps(connections, indent=4, sort_keys=True)}", color=LOG_COLOR)
    #         log_msg(f"Total connections:", len(connections["results"]), color=LOG_COLOR)
    #     elif int(option) == 2:
    #         await aries_cloudagent_agent.generate_invitation(display_qr=True)
    #     elif int(option) == 3:
    #         await aries_cloudagent_agent.receive_invitation(invitation=None, alias=None, auto_accept=None)
    #     elif int(option) == 4:
    #         await aries_cloudagent_agent.send_message(connection_id=None, message=None)
    #     elif int(option) == 5:
    #         connection_state = await aries_cloudagent_agent.get_connection_state(connection_id=None)
    #         log_msg(f"Connection state", connection_state, color=LOG_COLOR)
    #     elif int(option) == 6:
    #         schema_id = await aries_cloudagent_agent.create_schema()
    #         log_msg(f"schema id: {schema_id}", color=LOG_COLOR)
    #     elif int(option) == 7:
    #         cred_def_id = await aries_cloudagent_agent.create_credential_definition()
    #         log_msg(f"credential def id: {cred_def_id}", color=LOG_COLOR)
    #     elif int(option) == 8:
    #         credential = await aries_cloudagent_agent.issue_credential()
    #         log_msg(f"Credential exchange id: {credential['credential_exchange_id']}", color=LOG_COLOR)
    #     elif int(option) == 9:
    #         credentials = await aries_cloudagent_agent.get_credentials()
    #         log_msg(f"There is/are {len(credentials['results'])} credential(s)", color=LOG_COLOR)
    #         for i in range(len(credentials['results'])):
    #             log_msg(f"\tCredential: {credentials['results'][i]['attrs']}", color=LOG_COLOR)
    #     elif int(option) == 10:
    #         return
    #     # except:
    #     #     pass
    while True:
        await asyncio.sleep(1.0)
예제 #15
0
    msg = utilities.join_strings("Ended function for local comm \"", comm_l_n,
                                 "\" and world comm \"", comm_w_n,
                                 "\" and rank \"", "%d" % comm_l_r, "\".")
    msg = "".join(msg)

    logger.info(msg)


# ------------------------------------------------------------------------------

if __name__ == "__main__":

    if rank_w == 0:
        msg = "STARTED LOG"
        logger = utilities.log_msg(msg, log_file)
        msg = utilities.join_strings("NUMBER OF GRIDS: ", "%d." % n_grids)
        utilities.log_msg(msg, log_file, logger)
        msg = utilities.join_strings("ANCHORS: ", str(anchors), ".")
        utilities.log_msg(msg, log_file, logger)
        msg = utilities.join_strings("EDGES: ", str(edges), ".")
        utilities.log_msg(msg, log_file, logger)
        msg = utilities.join_strings("REFINEMENT LEVELS: ", str(refinements),
                                     ".")
        utilities.log_msg(msg, log_file, logger)

    t_start = time.time()

    import cProfile
    # http://stackoverflow.com/questions/3898266/what-is-this-cprofile-result-telling-me-i-need-to-fix
    #cProfile.run('main()', sort='cumulative')
예제 #16
0
 async def handle_connections(self, test):
     log_msg("Handle connections", color=LOG_COLOR)
예제 #17
0
                 "ascii")
    # Call parallelization and writing onto file.
    vtk.print_vtk()

    msg = "Ended function for local comm \"" + str(comm_l.Get_name())        + \
          "\" and world comm \"" + str(comm_w.Get_name()) + "\" and rank \"" + \
          str(comm_l.Get_rank()) + "\"."

    logger.info(msg)
# ------------------------------------------------------------------------------
    
if __name__ == "__main__":

    if rank_w == 0:
        msg = "STARTED LOG"
        logger = utilities.log_msg(msg, 
                                   log_file)
        msg = "NUMBER OF GRIDS: " + str(n_grids) + "."
        utilities.log_msg(msg     ,
                          log_file,
                          logger)
        msg = "ANCHORS: " + str(anchors) + "." 
        utilities.log_msg(msg     ,
                          log_file,
                          logger)
        msg = "EDGES: " + str(edges) + "."        
        utilities.log_msg(msg     ,
                          log_file,
                          logger)
        msg = "REFINEMENT LEVELS: " + str(refinements) + "."        
        utilities.log_msg(msg     ,
                          log_file,
예제 #18
0
if __name__ == "__main__":
    print(sys.argv[1], sys.argv[2])
    api_handler = ApiHandler(sys.argv[1], sys.argv[2])

    options = (
        "1. Show Connections\n2. Generate invitation\n3. Receive inivtaiotn\n4. Send Message\n5. Get connection state\n6. Create Schema\n7. Create credential definition\n8. Issue credential\n9. Get credentials\n10. Exit\n"
    )
    alias = "api_handler_test"

    while True:
        option = input(options)
        try:
            if int(option) == 1:
                connections = api_handler.connections()
                log_msg(f"{json.dumps(connections, indent=4, sort_keys=True)}",
                        color=LOG_COLOR)
                log_msg(f"Total connections:",
                        len(connections["results"]),
                        color=LOG_COLOR)
            elif int(option) == 2:
                invitation_id, invitation = api_handler.create_invitation(
                    alias=alias, multi_use=False, auto_accept=True)
                qr = QRCode(border=1)
                qr.add_data(json.dumps(invitation))
                log_msg(
                    f"Use the following JSON to accept the invite from another demo agent. Or use the QR code to connect from a mobile agent.",
                    color=LOG_COLOR)
                log_msg(f"Invitation Data:",
                        json.dumps(invitation),
                        color=LOG_COLOR)
                qr.print_ascii(invert=True)