async def input_invitation(agent):
    async for details in prompt_loop("Invite details: "):
        b64_invite = None
        try:
            url = urlparse(details)
            query = url.query
            if query and "c_i=" in query:
                pos = query.index("c_i=") + 4
                b64_invite = query[pos:]
            else:
                b64_invite = details
        except ValueError:
            b64_invite = details

        if b64_invite:
            try:
                padlen = 4 - len(b64_invite) % 4
                if padlen <= 2:
                    b64_invite += "=" * padlen
                invite_json = base64.urlsafe_b64decode(b64_invite)
                details = invite_json.decode("utf-8")
            except binascii.Error:
                pass
            except UnicodeDecodeError:
                pass

        if details:
            try:
                json.loads(details)
                break
            except json.JSONDecodeError as e:
                log_msg("Invalid invitation:", str(e))

    with log_timer("Connect duration:"):
        connection = await agent.admin_POST("/connections/receive-invitation",
                                            details)
        agent.connection_id = connection["connection_id"]
        log_json(connection, label="Invitation response:")

        await agent.detect_connection()
Exemple #2
0
    async def handle_issue_credential(self, message):
        state = message["state"]
        credential_exchange_id = message["credential_exchange_id"]
        prev_state = self.cred_state.get(credential_exchange_id)
        if prev_state == state:
            return  # ignore
        self.cred_state[credential_exchange_id] = state

        self.log(
            "Credential: state =",
            state,
            ", credential_exchange_id =",
            credential_exchange_id,
        )

        if state == "offer_received":
            await writeCommentToLogger("Credential offer received")

            log_status("#15 After receiving credential offer, send credential request")
            await self.admin_POST(
                "/issue-credential/records/" f"{credential_exchange_id}/send-request"
            )

        elif state == "credential_acked":
            await writeCommentToLogger("Credential received")

            self.log("Stored credential {cred_id} in wallet")
            cred_id = message["credential_id"]
            log_status(f"#18.1 Stored credential {cred_id} in wallet")
            resp = await self.admin_GET(f"/credential/{cred_id}")
            log_json(resp, label="Credential details:")
            log_json(
                message["credential_request_metadata"],
                label="Credential request metadata:",
            )
            self.log("credential_id", message["credential_id"])
            self.log("credential_definition_id", message["credential_definition_id"])
            self.log("schema_id", message["schema_id"])
    async def handle_issue_credential_v2_0(self, message):
        state = message["state"]
        cred_ex_id = message["cred_ex_id"]
        prev_state = self.cred_state.get(cred_ex_id)
        if prev_state == state:
            return  # ignore
        self.cred_state[cred_ex_id] = state

        self.log(f"Credential: state = {state}, cred_ex_id = {cred_ex_id}")
        print(f"Credential: state = {state}, cred_ex_id = {cred_ex_id}")

        if state == "request-received":
            log_status("#17 Issue credential to X")
            # issue credential based on offer preview in cred ex record
            await self.admin_POST(
                f"/issue-credential-2.0/records/{cred_ex_id}/issue",
                {"comment": f"Issuing credential, exchange {cred_ex_id}"},
            )
        elif state == "offer-received":
            log_status(
                "#15 After receiving credential offer, send credential request"
            )
            await self.admin_POST(
                f"/issue-credential-2.0/records/{cred_ex_id}/send-request")
        elif state == "done":
            if "cred_id_stored" in message:
                cred_id = message["cred_id_stored"]
                self.log(f"Stored credential {cred_id} in wallet")
                log_status(f"#18.1 Stored credential {cred_id} in wallet")
                cred = await self.admin_GET(f"/credential/{cred_id}")
                log_json(cred, label="Credential details:")
                self.log("credential_id", cred_id)
                self.log("cred_def_id", cred["cred_def_id"])
                self.log("schema_id", cred["schema_id"])
                # track last successfully received credential
                self.last_credential_received = cred
Exemple #4
0
    async def handle_issue_credential_v2_0_indy(self, message):
        cred_req_metadata = message.get("cred_request_metadata")
        if cred_req_metadata:
            log_json(cred_req_metadata, label="Credential request metadata:")

        log_json(message, label="indy message:")
        cred_id = message.get("cred_id_stored")
        if cred_id:
            self.log(f"Stored credential {cred_id} in wallet")
            log_status(f"#18.1 Stored credential {cred_id} in wallet")
            cred = await self.admin_GET(f"/credential/{cred_id}")
            log_json(cred, label="Credential details:")
            self.log("credential_id", cred_id)
            self.log("cred_def_id", cred["cred_def_id"])
            self.log("schema_id", cred["schema_id"])
async def main(start_port: int, show_timing: bool = False):

    genesis = await default_genesis_txns()
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)

    agent = None

    try:
        log_status(
            "#1 Provision an agent and wallet, get back configuration details")
        agent = RegulatorAgent(start_port,
                               start_port + 1,
                               genesis_data=genesis,
                               timing=show_timing)
        await agent.listen_webhooks(start_port + 2)
        await agent.register_did()

        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin url is at:", agent.admin_url)
        log_msg("Endpoint url is at:", agent.endpoint)

        # Create a schema
        with log_timer("Publish schema/cred def duration:"):
            log_status("#3/4 Create a new schema/cred def on the ledger")
            version = format("%d.%d.%d" % (
                random.randint(1, 101),
                random.randint(1, 101),
                random.randint(1, 101),
            ))
            (
                _,  # schema id
                credential_definition_id,
            ) = await agent.register_schema_and_creddef(
                "Certified Researcher schema", version,
                ["institution", "date"])

        # TODO add an additional credential for Student ID

        with log_timer("Generate invitation duration:"):
            # Generate an invitation
            log_status(
                "#5 Create a connection to Hospital and print out the invite details"
            )
            connection = await agent.admin_POST(
                "/connections/create-invitation")

        agent.active_connection_id = connection["connection_id"]
        agent.connection_list.append(connection["connection_id"])
        log_json(connection, label="Invitation response:")
        log_msg("*****************")
        log_msg(json.dumps(connection["invitation"]),
                label="Invitation:",
                color=None)
        log_msg("*****************")

        log_msg("Waiting for connection...")
        await agent.detect_connection()

        async for option in prompt_loop(
                "(1) Issue Credential, (2) Create a New Invitation, (X) Exit? [1/2/X] "
        ):
            if option is None or option in "xX":
                break

            elif option == "1":
                log_status("#13 Issue credential offer to X")

                today = date.today()
                # TODO define attributes to send for credential
                agent.cred_attrs[credential_definition_id] = {
                    # "name": str(credential_definition_id),
                    "date": str(today),
                    "institution": "Edinburgh Napier University",
                    # "age": "24",
                }

                cred_preview = {
                    "@type":
                    CRED_PREVIEW_TYPE,
                    "attributes":
                    [{
                        "name": n,
                        "value": v
                    } for (n, v) in
                     agent.cred_attrs[credential_definition_id].items()],
                }
                offer_request = {
                    "connection_id": agent.active_connection_id,
                    "credential_definition_id": credential_definition_id,
                    "comment":
                    f"Offer on cred def id {credential_definition_id}",
                    "credential_preview": cred_preview,
                }
                await agent.admin_POST("/issue-credential/send-offer",
                                       offer_request)
            elif option == "2":
                # handle new invitation
                with log_timer("Generate invitation duration:"):
                    # Generate an invitation
                    log_status(
                        "#5 Create a connection to alice and print out the invite details"
                    )
                    connection = await agent.admin_POST(
                        "/connections/create-invitation")
                agent.active_connection_id = connection["connection_id"]
                agent.connection_list.append(connection["connection_id"])
                log_msg("all connections :", agent.connection_list)
                log_json(connection, label="Invitation response:")
                log_msg("*****************")
                log_msg(json.dumps(connection["invitation"]),
                        label="Invitation:",
                        color=None)
                log_msg("*****************")
                agent._connection_ready = asyncio.Future()
                log_msg("Waiting for connection...")
                await agent.detect_connection()

        if show_timing:
            timing = await agent.fetch_timing()
            if timing:
                for line in agent.format_timing(timing):
                    log_msg(line)

    finally:
        terminated = True
        try:
            if agent:
                await agent.terminate()
        except Exception:
            LOGGER.exception("Error terminating agent:")
            terminated = False

    await asyncio.sleep(0.1)

    if not terminated:
        os._exit(1)
async def main(start_port: int, show_timing: bool = False):

    genesis = await default_genesis_txns()
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)

    agent = None

    try:
        log_status(
            "#1 Provision an agent and wallet, get back configuration details")
        agent = AcmeAgent(start_port,
                          start_port + 1,
                          genesis_data=genesis,
                          timing=show_timing)
        await agent.listen_webhooks(start_port + 2)
        await agent.register_did()

        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin url is at:", agent.admin_url)
        log_msg("Endpoint url is at:", agent.endpoint)

        # Create a schema
        log_status("#3 Create a new schema on the ledger")
        with log_timer("Publish schema duration:"):
            # define schema
            version = format("%d.%d.%d" % (
                random.randint(1, 101),
                random.randint(1, 101),
                random.randint(1, 101),
            ))
            (
                schema_id,
                credential_definition_id,
            ) = await agent.register_schema_and_creddef(
                "current_employee schema",
                version,
                ["employee_id", "name", "start_date", "position", "salary"],
            )

        with log_timer("Generate invitation duration:"):
            # Generate an invitation
            log_status(
                "#5 Create a connection to alice and print out the invite details"
            )
            connection = await agent.admin_POST(
                "/connections/create-invitation")

        agent.connection_id = connection["connection_id"]
        log_json(connection, label="Invitation response:")
        log_msg("*****************")
        log_msg(json.dumps(connection["invitation"]),
                label="Invitation:",
                color=None)
        log_msg("*****************")

        log_msg("Waiting for connection...")
        await agent.detect_connection()

        async for option in prompt_loop(
                "(1) Issue Credential, (2) Send Proof Request, " +
                "(3) Send Message (X) Exit? [1/2/3/X] "):
            if option in "xX":
                break

            elif option == "1":
                log_status("#13 Issue credential offer to X")
                # TODO credential offers
                agent.cred_attrs[credential_definition_id] = {
                    "employee_id": "ACME0009",
                    "name": "Alice Smith",
                    "start_date": "2019-05-28",
                    "position": "CEO",
                    "salary": "3000"
                }
                cred_preview = {
                    "@type":
                    CRED_PREVIEW_TYPE,
                    "attributes":
                    [{
                        "name": n,
                        "value": v
                    } for (n, v) in
                     agent.cred_attrs[credential_definition_id].items()],
                }
                offer_request = {
                    "connection_id": agent.connection_id,
                    "cred_def_id": credential_definition_id,
                    "comment":
                    f"Offer on cred def id {credential_definition_id}",
                    "credential_preview": cred_preview
                }
                await agent.admin_POST("/issue-credential/send-offer",
                                       offer_request)

            elif option == "2":
                log_status("#20 Request proof of employement from alice")
                # TODO presentation requests
                req_attrs = [{
                    "name":
                    "name",
                    "restrictions": [{
                        "schema_name": "ex_employee schema"
                    }]
                }, {
                    "name":
                    "end_date",
                    "restrictions": [{
                        "schema_name": "ex_employee schema"
                    }]
                }, {
                    "name":
                    "start_date",
                    "restrictions": [{
                        "schema_name": "ex_employee schema"
                    }]
                }]
                req_preds = []
                indy_proof_request = {
                    "name": "Proof of Employment",
                    "version": "1.0",
                    "nonce": str(uuid4().int),
                    "requested_attributes": {
                        f"0_{req_attr['name']}_uuid": req_attr
                        for req_attr in req_attrs
                    },
                    "requested_predicates": {}
                }
                proof_request_web_request = {
                    "connection_id": agent.connection_id,
                    "proof_request": indy_proof_request
                }
                # this sends the request to our agent, which forwards it to Alice
                # (based on the connection_id)
                await agent.admin_POST("/present-proof/send-request",
                                       proof_request_web_request)

            elif option == "3":
                msg = await prompt("Enter message: ")
                await agent.admin_POST(
                    f"/connections/{agent.connection_id}/send-message",
                    {"content": msg})

        if show_timing:
            timing = await agent.fetch_timing()
            if timing:
                for line in agent.format_timing(timing):
                    log_msg(line)

    finally:
        terminated = True
        try:
            if agent:
                await agent.terminate()
        except Exception:
            LOGGER.exception("Error terminating agent:")
            terminated = False

    await asyncio.sleep(0.1)

    if not terminated:
        os._exit(1)
async def main(
    start_port: int,
    no_auto: bool = False,
    revocation: bool = False,
    show_timing: bool = False,
):

    genesis = await default_genesis_txns()
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)

    agent = None

    try:
        log_status("#1 Provision an agent and wallet, get back configuration details")
        agent = FaberAgent(
            start_port,
            start_port + 1,
            genesis_data=genesis,
            no_auto=no_auto,
            timing=show_timing,
        )
        await agent.listen_webhooks(start_port + 2)
        await agent.register_did()

        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin url is at:", agent.admin_url)
        log_msg("Endpoint url is at:", agent.endpoint)

        # Create a schema
        with log_timer("Publish schema/cred def duration:"):
            log_status("#3/4 Create a new schema/cred def on the ledger")
            version = format(
                "%d.%d.%d"
                % (
                    random.randint(1, 101),
                    random.randint(1, 101),
                    random.randint(1, 101),
                )
            )
            (
                _,  # schema id
                credential_definition_id,
            ) = await agent.register_schema_and_creddef(
                "degree schema",
                version,
                ["name", "date", "degree", "age", "timestamp"],
                support_revocation=revocation,
            )

        if revocation:
            with log_timer("Publish revocation registry duration:"):
                log_status(
                    "#5/6 Create and publish the revocation registry on the ledger"
                )
                revocation_registry_id = await (
                    agent.create_and_publish_revocation_registry(
                        credential_definition_id, TAILS_FILE_COUNT
                    )
                )
        else:
            revocation_registry_id = None

        # TODO add an additional credential for Student ID

        with log_timer("Generate invitation duration:"):
            # Generate an invitation
            log_status(
                "#7 Create a connection to alice and print out the invite details"
            )
            connection = await agent.admin_POST("/connections/create-invitation")

        agent.connection_id = connection["connection_id"]
        log_json(connection, label="Invitation response:")
        log_msg("*****************")
        log_msg(json.dumps(connection["invitation"]), label="Invitation:", color=None)
        log_msg("*****************")

        log_msg("Waiting for connection...")
        await agent.detect_connection()

        options = "(1) Issue Credential (2) Send Proof Request (3) Send Message"
        if revocation:
            options += " (4) Revoke Credential (5) Add Revocation Registry"
        options += " (X) Exit? [1/2/3/X] "
        async for option in prompt_loop(options):
            if option is None or option in "xX":
                break

            elif option == "1":
                log_status("#13 Issue credential offer to X")

                # TODO define attributes to send for credential
                agent.cred_attrs[credential_definition_id] = {
                    "name": "Alice Smith",
                    "date": "2018-05-28",
                    "degree": "Maths",
                    "age": "24",
                    "timestamp": str(int(time.time())),
                }

                cred_preview = {
                    "@type": CRED_PREVIEW_TYPE,
                    "attributes": [
                        {"name": n, "value": v}
                        for (n, v) in agent.cred_attrs[credential_definition_id].items()
                    ],
                }
                offer_request = {
                    "connection_id": agent.connection_id,
                    "cred_def_id": credential_definition_id,
                    "comment": f"Offer on cred def id {credential_definition_id}",
                    "auto_remove": False,
                    "credential_preview": cred_preview,
                    "revoc_reg_id": revocation_registry_id,
                }
                await agent.admin_POST("/issue-credential/send-offer", offer_request)

                # TODO issue an additional credential for Student ID

            elif option == "2":
                log_status("#20 Request proof of degree from alice")
                req_attrs = [
                    {"name": "name", "restrictions": [{"issuer_did": agent.did}]},
                    {"name": "date", "restrictions": [{"issuer_did": agent.did}]},
                ]
                if revocation:
                    req_attrs.append(
                        {
                            "name": "degree",
                            "restrictions": [{"issuer_did": agent.did}],
                            "non_revoked": {"to": int(time.time() - 1)},
                        },
                    )
                else:
                    req_attrs.append(
                        {"name": "degree", "restrictions": [{"issuer_did": agent.did}]}
                    )
                # test self-attested claims
                req_attrs.append({"name": "self_attested_thing"},)
                req_preds = [
                    # test zero-knowledge proofs
                    {
                        "name": "age",
                        "p_type": ">=",
                        "p_value": 18,
                        "restrictions": [{"issuer_did": agent.did}],
                    }
                ]
                indy_proof_request = {
                    "name": "Proof of Education",
                    "version": "1.0",
                    "nonce": str(uuid4().int),
                    "requested_attributes": {
                        f"0_{req_attr['name']}_uuid": req_attr for req_attr in req_attrs
                    },
                    "requested_predicates": {
                        f"0_{req_pred['name']}_GE_uuid": req_pred
                        for req_pred in req_preds
                    },
                }
                if revocation:
                    indy_proof_request["non_revoked"] = {"to": int(time.time())}
                proof_request_web_request = {
                    "connection_id": agent.connection_id,
                    "proof_request": indy_proof_request,
                }
                await agent.admin_POST(
                    "/present-proof/send-request", proof_request_web_request
                )

            elif option == "3":
                msg = await prompt("Enter message: ")
                await agent.admin_POST(
                    f"/connections/{agent.connection_id}/send-message", {"content": msg}
                )
            elif option == "4" and revocation:
                revoking_cred_id = await prompt("Enter credential exchange id: ")
                await agent.admin_POST(
                    f"/issue-credential/records/{revoking_cred_id}/revoke"
                )
            elif option == "5" and revocation:
                log_status("#19 Add another revocation registry")
                revocation_registry_id = await (
                    agent.create_and_publish_revocation_registry(
                        credential_definition_id, TAILS_FILE_COUNT
                    )
                )

        if show_timing:
            timing = await agent.fetch_timing()
            if timing:
                for line in agent.format_timing(timing):
                    log_msg(line)

    finally:
        terminated = True
        try:
            if agent:
                await agent.terminate()
        except Exception:
            LOGGER.exception("Error terminating agent:")
            terminated = False

    await asyncio.sleep(0.1)

    if not terminated:
        os._exit(1)
    async def handle_issue_credential(self, message):
        state = message["state"]
        credential_exchange_id = message["credential_exchange_id"]
        prev_state = self.cred_state.get(credential_exchange_id)
        if prev_state == state:
            return  # ignore
        self.cred_state[credential_exchange_id] = state

        self.log(
            "Credential: state = {}, credential_exchange_id = {}".format(
                state,
                credential_exchange_id,
            )
        )

        if state == "offer_received":
            log_status("#15 After receiving credential offer, send credential request")
            await self.admin_POST(
                f"/issue-credential/records/{credential_exchange_id}/send-request"
            )

        elif state == "credential_acked":
            cred_id = message["credential_id"]
            self.log(f"Stored credential {cred_id} in wallet")
            log_status(f"#18.1 Stored credential {cred_id} in wallet")
            resp = await self.admin_GET(f"/credential/{cred_id}")
            log_json(resp, label="Credential details:")
            log_json(
                message["credential_request_metadata"],
                label="Credential request metadata:",
            )
            self.log("credential_id", message["credential_id"])
            self.log("credential_definition_id", message["credential_definition_id"])
            self.log("schema_id", message["schema_id"])

        elif state == "request_received":
            log_status("#17 Issue credential to X")
            # issue credentials based on the credential_definition_id
            cred_attrs = self.cred_attrs[message["credential_definition_id"]]
            cred_preview = {
                "@type": CRED_PREVIEW_TYPE,
                "attributes": [
                    {"name": n, "value": v} for (n, v) in cred_attrs.items()
                ],
            }
            try:
                cred_ex_rec = await self.admin_POST(
                    f"/issue-credential/records/{credential_exchange_id}/issue",
                    {
                        "comment": (
                            f"Issuing credential, exchange {credential_exchange_id}"
                        ),
                        "credential_preview": cred_preview,
                    },
                )
                rev_reg_id = cred_ex_rec.get("revoc_reg_id")
                cred_rev_id = cred_ex_rec.get("revocation_id")
                if rev_reg_id:
                    self.log(f"Revocation registry ID: {rev_reg_id}")
                if cred_rev_id:
                    self.log(f"Credential revocation ID: {cred_rev_id}")
            except ClientError:
                pass
async def main(start_port: int, show_timing: bool = False):

    genesis = await default_genesis_txns()
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)

    agent = None

    try:
        log_status(
            "#1 Provision an agent and wallet, get back configuration details")
        agent = NhsheadofficeAgent(start_port,
                                   start_port + 1,
                                   genesis_data=genesis,
                                   timing=show_timing)
        await agent.listen_webhooks(start_port + 2)
        await agent.register_did()

        log_msg("HEAD OFFICE DID: ", agent.did)

        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin url is at:", agent.admin_url)
        log_msg("Endpoint url is at:", agent.endpoint)

        # Create a schema
        with log_timer("Publish schema/cred def duration:"):
            log_status("#3/4 Create a new schema/cred def on the ledger")
            version = format("%d.%d.%d" % (
                random.randint(1, 101),
                random.randint(1, 101),
                random.randint(1, 101),
            ))
            (
                _,  # schema id
                credential_definition_id,
            ) = await agent.register_schema_and_creddef(
                "Verified Hospital schema", version, ["date", "hospital_name"])

        # TODO add an additional credential for Student ID

        with log_timer("Generate invitation duration:"):
            # Generate an invitation
            log_status(
                "#5 Create a connection to Hospital and print out the invite details"
            )
            connection = await agent.admin_POST(
                "/connections/create-invitation")

        agent.active_connection_id = connection["connection_id"]
        agent.connection_list.append(connection["connection_id"])
        log_json(connection, label="Invitation response:")
        log_msg("*****************")
        log_msg(json.dumps(connection["invitation"]),
                label="Invitation:",
                color=None)
        log_msg("*****************")

        log_msg("Waiting for connection...")
        await agent.detect_connection()

        async for option in prompt_loop(
                "(1) Request Hospital name, (2) Issue Verified Hospital Credential, (3) Create a New Invitation, (X) Exit? [1/2/X] "
        ):
            if option is None or option in "xX":
                break

            elif option == "1":
                log_status("#20 Request Self Attested Hospital Name")
                req_attrs = [{"name": "name"}]
                indy_proof_request = {
                    "name": "Proof of Hospital Name",
                    "version": "1.0",
                    "nonce": str(uuid4().int),
                    "requested_attributes": {
                        f"0_{req_attr['name']}_uuid": req_attr
                        for req_attr in req_attrs
                    },
                    "requested_predicates": {},
                }
                proof_request_web_request = {
                    "connection_id": agent.active_connection_id,
                    "proof_request": indy_proof_request,
                }
                await agent.admin_POST("/present-proof/send-request",
                                       proof_request_web_request)

            elif option == "2":
                log_status("#13 Issue Verified Hospital credential offer to X")

                today = date.today()
                # TODO define attributes to send for credential
                agent.cred_attrs[credential_definition_id] = {
                    "hospital_name": agent.current_hospital_name,
                    "date": str(today),
                    # "degree": "Health",
                    # "age": "24",
                }

                cred_preview = {
                    "@type":
                    CRED_PREVIEW_TYPE,
                    "attributes":
                    [{
                        "name": n,
                        "value": v
                    } for (n, v) in
                     agent.cred_attrs[credential_definition_id].items()],
                }
                offer_request = {
                    "connection_id": agent.active_connection_id,
                    "credential_definition_id": credential_definition_id,
                    "comment":
                    f"Offer on cred def id {credential_definition_id}",
                    "credential_preview": cred_preview,
                }
                await agent.admin_POST("/issue-credential/send-offer",
                                       offer_request)

            # elif option == "3":
            #     msg = await prompt("Enter message: ")
            #     await agent.admin_POST(
            #         f"/connections/{agent.active_connection_id}/send-message", {"content": msg}
            #     )
            elif option == "3":
                # handle new invitation
                with log_timer("Generate invitation duration:"):
                    # Generate an invitation
                    log_status(
                        "#5 Create a connection to alice and print out the invite details"
                    )
                    connection = await agent.admin_POST(
                        "/connections/create-invitation")
                agent.active_connection_id = connection["connection_id"]
                agent.connection_list.append(connection["connection_id"])
                log_msg("all connections :", agent.connection_list)
                log_json(connection, label="Invitation response:")
                log_msg("*****************")
                log_msg(json.dumps(connection["invitation"]),
                        label="Invitation:",
                        color=None)
                log_msg("*****************")
                agent._connection_ready = asyncio.Future()
                log_msg("Waiting for connection...")
                await agent.detect_connection()

        if show_timing:
            timing = await agent.fetch_timing()
            if timing:
                for line in agent.format_timing(timing):
                    log_msg(line)

    finally:
        terminated = True
        try:
            if agent:
                await agent.terminate()
        except Exception:
            LOGGER.exception("Error terminating agent:")
            terminated = False

    await asyncio.sleep(0.1)

    if not terminated:
        os._exit(1)
Exemple #10
0
async def main(start_port: int, show_timing: bool = False):

    genesis = await default_genesis_txns()
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)

    agent = None

    try:
        log_status(
            "#1 Provision an agent and wallet, get back configuration details")
        agent = AcmeAgent(start_port,
                          start_port + 1,
                          genesis_data=genesis,
                          timing=show_timing)
        await agent.listen_webhooks(start_port + 2)
        await agent.register_did()

        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin url is at:", agent.admin_url)
        log_msg("Endpoint url is at:", agent.endpoint)

        # Create a schema
        log_status("#3 Create a new schema on the ledger")
        with log_timer("Publish schema duration:"):
            pass
            # TODO define schema
            # version = format(
            #     "%d.%d.%d"
            #     % (
            #         random.randint(1, 101),
            #         random.randint(1, 101),
            #         random.randint(1, 101),
            #     )
            # )
            # (
            #     schema_id,
            #     credential_definition_id,
            # ) = await agent.register_schema_and_creddef(
            #     "employee id schema",
            #     version,
            #     ["employee_id", "name", "date", "position"],
            # )

        with log_timer("Generate invitation duration:"):
            # Generate an invitation
            log_status(
                "#5 Create a connection to alice and print out the invite details"
            )
            connection = await agent.admin_POST(
                "/connections/create-invitation")

        agent.connection_id = connection["connection_id"]
        log_json(connection, label="Invitation response:")
        log_msg("*****************")
        log_msg(json.dumps(connection["invitation"]),
                label="Invitation:",
                color=None)
        log_msg("*****************")

        log_msg("Waiting for connection...")
        await agent.detect_connection()

        async for option in prompt_loop(
                "(1) Issue Credential, (2) Send Proof Request, " +
                "(3) Send Message (X) Exit? [1/2/3/X] "):
            if option in "xX":
                break

            elif option == "1":
                log_status("#13 Issue credential offer to X")
                # TODO credential offers

            elif option == "2":
                log_status("#20 Request proof of degree from alice")
                # TODO presentation requests

            elif option == "3":
                msg = await prompt("Enter message: ")
                await agent.admin_POST(
                    f"/connections/{agent.connection_id}/send-message",
                    {"content": msg})

        if show_timing:
            timing = await agent.fetch_timing()
            if timing:
                for line in agent.format_timing(timing):
                    log_msg(line)

    finally:
        terminated = True
        try:
            if agent:
                await agent.terminate()
        except Exception:
            LOGGER.exception("Error terminating agent:")
            terminated = False

    await asyncio.sleep(0.1)

    if not terminated:
        os._exit(1)
async def main(start_port: int, show_timing: bool = False):

    genesis = await default_genesis_txns()
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)

    agent = None

    try:
        log_status("#1 Provision an agent and wallet, get back configuration details")
        agent = CoordinatorAgent(
            start_port, start_port + 1, genesis_data=genesis, timing=show_timing
        )
        await agent.listen_webhooks(start_port + 2)

        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin url is at:", agent.admin_url)
        log_msg("Endpoint url is at:", agent.endpoint)

        with log_timer("Generate invitation duration:"):
            # Generate an invitation
            log_status(
                "#5 Create a connection to alice and print out the invite details"
            )
            connection = await agent.admin_POST("/connections/create-invitation")

        agent.active_connection_id = connection["connection_id"]
        agent.connection_list.append(connection["connection_id"])
        log_json(connection, label="Invitation response:")
        log_msg("*****************")
        log_msg(json.dumps(connection["invitation"]), label="Invitation:", color=None)
        log_msg("*****************")

        # log_msg("Waiting for connection...")
        # await agent.detect_connection()

        async for option in prompt_loop(
            "(1) Request proof of Verified Hospital \n"
            + "(2) Input New Invitation \n"
            + "(3) Create New Invitation \n"
            + "(4) List trusted connections \n"
            + "(5) Initiate Learning \n"
            + "(6) Reset trusted connections \n"
            + "(X) Exit? \n[1/2/3/4/5/6/X] "
        ):
            if option is None or option in "xX":
                break

            elif option == "1":
                log_status("#20 Request proof of degree from alice")
                req_attrs = [
                    {"name": "date", "restrictions": [{"issuer_did": agent.nhsheadoffice_did}]},
                    {"name": "hospital_name", "restrictions": [{"issuer_did": agent.nhsheadoffice_did}]},
                ]
                # req_preds = [
                #     {
                #         "name": "age",
                #         "p_type": ">=",
                #         "p_value": 18,
                #         "restrictions": [{"issuer_did": agent.did}],
                #     }
                # ]
                indy_proof_request = {
                    "name": "Proof of Verified Hospital",
                    "version": "1.0",
                    "nonce": str(uuid4().int),
                    "requested_attributes": {
                        f"0_{req_attr['name']}_uuid": req_attr for req_attr in req_attrs
                    },
                    "requested_predicates": {
                    },
                }
                print("Asking for this proof: ", indy_proof_request)
                proof_request_web_request = {
                    "connection_id": agent.active_connection_id,
                    "proof_request": indy_proof_request,
                }
                await agent.admin_POST(
                    "/present-proof/send-request", proof_request_web_request
                )
            elif option == "2":
                # handle new invitation
                log_status("Input new invitation details")
                await input_invitation(agent)
            elif option == "3":
                # handle new invitation
                with log_timer("Generate invitation duration:"):
                    # Generate an invitation
                    log_status(
                        "#5 Create a connection to alice and print out the invite details"
                    )
                    connection = await agent.admin_POST("/connections/create-invitation")

                agent.active_connection_id = connection["connection_id"]
                agent.connection_list.append(connection["connection_id"])
                log_msg("all connections :", agent.connection_list)
                log_json(connection, label="Invitation response:")
                log_msg("*****************")
                log_msg(json.dumps(connection["invitation"]), label="Invitation:", color=None)
                log_msg("*****************")
                agent._connection_ready = asyncio.Future()

                log_msg("Waiting for connection...")
                await agent.detect_connection()
            elif option == "4":
                # handle new invitation
                log_status("List of Trusted Connections")
                log_msg(agent.trusted_connection_ids)
                # log_msg(agent.trusted_hospitals)
            elif option == "5":
                # handle new invitation
                log_status("Initiate Learning")
                # TODO Need to get the updated file somehow
                # Some sort of await until coordinator recieved message back

                successfully_generated = await generate_model()
                successfully_validated = await validate_model(agent.current_model_file)



                # f = open(agent.current_model_file, "rb")
                if successfully_generated:
                    log_msg("MODEL CREATED AND SAVED SUCCESSFULLY")
                    f = open(agent.current_model_file, "rb")
                    log_msg("MODEL OPENED FOR TRANSPORT")

                    contents = f.read()
                    f.close()
                    await agent.admin_POST(
                        f"/connections/{agent.trusted_connection_ids[0]}/send-message",
                        {"content": contents.hex()}
                    )
                    await agent.learning_complete
                else:
                    log_msg("THERE  WAS A PROBLEM WITH THE MODEL CREATION")

            elif option == "6":
                # handle new invitation
                log_status("Reset trusted connection list")
                agent.trusted_connection_ids = []
                agent.trusted_hospitals = []





        if show_timing:
            timing = await agent.fetch_timing()
            if timing:
                for line in agent.format_timing(timing):
                    log_msg(line)

    finally:
        terminated = True
        try:
            if agent:
                await agent.terminate()
        except Exception:
            LOGGER.exception("Error terminating agent:")
            terminated = False

    await asyncio.sleep(0.1)

    if not terminated:
        os._exit(1)
async def main(start_port: int, show_timing: bool = False):

    genesis = await default_genesis_txns()
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)

    agent = None

    try:
        log_status("#1 Provision an agent and wallet, get back configuration details")
        agent = AcmeAgent(
            start_port, start_port + 1, genesis_data=genesis, timing=show_timing
        )
        await agent.listen_webhooks(start_port + 2)
        await agent.register_did()

        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin URL is at:", agent.admin_url)
        log_msg("Endpoint URL is at:", agent.endpoint)

        # Create a schema
        log_status("#3 Create a new schema on the ledger")
        with log_timer("Publish schema duration:"):
            
             version = format(
                 "%d.%d.%d"
                 % (
                     random.randint(1, 101),
                     random.randint(1, 101),
                     random.randint(1, 101),
                 )
             )
             (
                 schema_id,
                 credential_definition_id,
             ) = await agent.register_schema_and_creddef(
                 "employee id schema",
                 version,
                 ["employee_id", "name", "date", "position"],
             )

        with log_timer("Generate invitation duration:"):
            # Generate an invitation
            log_status(
                "#5 Create a connection to alice and print out the invite details"
            )
            connection = await agent.admin_POST("/connections/create-invitation")

        agent.connection_id = connection["connection_id"]
        log_json(connection, label="Invitation response:")
        log_msg("*****************")
        log_msg(json.dumps(connection["invitation"]), label="Invitation:", color=None)
        log_msg("*****************")

        log_msg("Waiting for connection...")
        await agent.detect_connection()

        async for option in prompt_loop(
            "(1) Issue Credential, (2) Send Proof Request, "
            + "(3) Send Message (X) Exit? [1/2/3/X] "
        ):
            option = option.strip()
            if option in "xX":
                break

            elif option == "1":
                log_status("#13 Issue credential offer to X")
                     agent.cred_attrs[credential_definition_id] = {
                    "employee_id": "ACME0009",
                    "name": "Alice Smith",
                    "date": date.isoformat(date.today()),
                    "position": "CEO"
                }
                offer_request = {
                    "connection_id": agent.connection_id,
                    "cred_def_id": credential_definition_id,
                    "comment": f"Offer on cred def id {credential_definition_id}",
                }
                await agent.admin_POST(
                    "/issue-credential/send-offer",
                    offer_request
                )

            elif option == "2":
                log_status("#20 Request proof of degree from alice")
                req_attrs = [
                    {
                        "name": "name",
                        "restrictions": [{"schema_name": "degree schema"}]
                    },
                    {
                        "name": "date",
                        "restrictions": [{"schema_name": "degree schema"}]
                    },
                    {
                        "name": "degree",
                        "restrictions": [{"schema_name": "degree schema"}]
                    }
                ]
                req_preds = []
                indy_proof_request = {
                    "name": "Proof of Education",
                    "version": "1.0",
                    "nonce": str(uuid4().int),
                    "requested_attributes": {
                        f"0_{req_attr['name']}_uuid": req_attr
                        for req_attr in req_attrs
                    },
                    "requested_predicates": {}
                }
                proof_request_web_request = {
                    "connection_id": agent.connection_id,
                    "proof_request": indy_proof_request
                }
                # this sends the request to our agent, which forwards it to Alice
                # (based on the connection_id)
                await agent.admin_POST(
                    "/present-proof/send-request",
                    proof_request_web_request
                )

            elif option == "3":
                msg = await prompt("Enter message: ")
                await agent.admin_POST(
                    f"/connections/{agent.connection_id}/send-message", {"content": msg}
                )
 async def handle_issue_credential_v2_0_indy(self, message):
     cred_req_metadata = message.get("cred_request_metadata")
     if cred_req_metadata:
         log_json(cred_req_metadata, label="Credential request metadata:")
Exemple #14
0
async def main(start_port: int, show_timing: bool = False):

    genesis = await default_genesis_txns()
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)

    agent = None

    try:
        log_status(
            "#1 Provision an agent and wallet, get back configuration details")
        agent = FaberAgent(start_port,
                           start_port + 1,
                           genesis_data=genesis,
                           timing=show_timing)
        await agent.listen_webhooks(start_port + 2)
        await agent.register_did()

        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin url is at:", agent.admin_url)
        log_msg("Endpoint url is at:", agent.endpoint)

        # Create a schema
        with log_timer("Publish schema/cred def duration:"):
            log_status("#3/4 Create a new schema/cred def on the ledger")
            version = format("%d.%d.%d" % (
                random.randint(1, 101),
                random.randint(1, 101),
                random.randint(1, 101),
            ))
            (
                schema_id,
                credential_definition_id,
            ) = await agent.register_schema_and_creddef(
                "degree schema", version, ["name", "date", "degree", "age"])

        # TODO add an additional credential for Student ID

        with log_timer("Generate invitation duration:"):
            # Generate an invitation
            log_status(
                "#5 Create a connection to alice and print out the invite details"
            )
            connection = await agent.admin_POST(
                "/connections/create-invitation")

        agent.connection_id = connection["connection_id"]
        log_json(connection, label="Invitation response:")
        log_msg("*****************")
        log_msg(json.dumps(connection["invitation"]),
                label="Invitation:",
                color=None)
        log_msg("*****************")

        log_msg("Waiting for connection...")
        await agent.detect_connection()

        async for option in prompt_loop(
                "(1) Issue Credential, (2) Send Proof Request, " +
                "(3) Send Message (X) Exit? [1/2/3/X] "):
            if option is None or option in "xX":
                break

            elif option == "1":
                log_status("#13 Issue credential offer to X")
                offer = {
                    "credential_definition_id": credential_definition_id,
                    "connection_id": agent.connection_id,
                }
                # TODO define attributes to send for credential
                agent.cred_attrs[credential_definition_id] = {
                    "name": "Alice Smith",
                    "date": "2018-05-28",
                    "degree": "Maths",
                    "age": "24",
                }
                await agent.admin_POST("/credential_exchange/send-offer",
                                       offer)

                # TODO issue an additional credential for Student ID

            elif option == "2":
                log_status("#20 Request proof of degree from alice")
                proof_attrs = [
                    {
                        "name": "name",
                        "restrictions": [{
                            "issuer_did": agent.did
                        }]
                    },
                    {
                        "name": "date",
                        "restrictions": [{
                            "issuer_did": agent.did
                        }]
                    },
                    {
                        "name": "degree",
                        "restrictions": [{
                            "issuer_did": agent.did
                        }]
                    },
                    {
                        "name": "self_attested_thing"
                    },
                ]
                proof_predicates = [{
                    "name": "age",
                    "p_type": ">=",
                    "p_value": 18
                }]
                proof_request = {
                    "name": "Proof of Education",
                    "version": "1.0",
                    "connection_id": agent.connection_id,
                    "requested_attributes": proof_attrs,
                    "requested_predicates": proof_predicates,
                }
                await agent.admin_POST("/presentation_exchange/send_request",
                                       proof_request)

            elif option == "3":
                msg = await prompt("Enter message: ")
                await agent.admin_POST(
                    f"/connections/{agent.connection_id}/send-message",
                    {"content": msg})

        if show_timing:
            timing = await agent.fetch_timing()
            if timing:
                for line in agent.format_timing(timing):
                    log_msg(line)

    finally:
        terminated = True
        try:
            if agent:
                await agent.terminate()
        except Exception:
            LOGGER.exception("Error terminating agent:")
            terminated = False

    await asyncio.sleep(0.1)

    if not terminated:
        os._exit(1)
Exemple #15
0
async def main(start_port: int,
               no_auto: bool = False,
               show_timing: bool = False):

    genesis = await default_genesis_txns()
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)

    agent = None

    try:
        log_status(
            "#1 Provision an agent and wallet, get back configuration details")
        agent = FaberAgent(
            start_port,
            start_port + 1,
            genesis_data=genesis,
            no_auto=no_auto,
            timing=show_timing,
        )
        await agent.listen_webhooks(start_port + 2)
        await agent.register_did()

        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin url is at:", agent.admin_url)
        log_msg("Endpoint url is at:", agent.endpoint)

        # Create a schema
        with log_timer("Publish schema/cred def duration:"):
            log_status("#3/4 Create a new schema/cred def on the ledger")
            version = format("%d.%d.%d" % (
                random.randint(1, 101),
                random.randint(1, 101),
                random.randint(1, 101),
            ))
            (
                _,  # schema id
                credential_definition_id,
            ) = await agent.register_schema_and_creddef(
                "ethereum_identity", version, ["name", "address"])

        # TODO add an additional credential for Student ID

        with log_timer("Generate invitation duration:"):
            # Generate an invitation
            log_status(
                "#5 Create a connection to alice and print out the invite details"
            )
            connection = await agent.admin_POST(
                "/connections/create-invitation")

        agent.connection_id = connection["connection_id"]
        log_json(connection, label="Invitation response:")
        log_msg("*****************")
        log_msg(json.dumps(connection["invitation"]),
                label="Invitation:",
                color=None)
        log_msg("*****************")

        log_msg("Waiting for connection...")
        await agent.detect_connection()

        async for option in prompt_loop(
                "(1) Issue Credential, (2) Send Proof Request, " +
                "(3) Send Message (X) Exit? [1/2/3/X] "):
            if option is None or option in "xX":
                break

            elif option == "1":
                log_status("#13 Issue credential offer to X")

                # TODO define attributes to send for credential
                agent.cred_attrs[credential_definition_id] = {
                    "name": "Kai Jun Eer",
                    "address": "0xEDB4400a8b1DEccc6C62DFDDBD6F73E48537012A"
                }

                cred_preview = {
                    "@type":
                    CRED_PREVIEW_TYPE,
                    "attributes":
                    [{
                        "name": n,
                        "value": v
                    } for (n, v) in
                     agent.cred_attrs[credential_definition_id].items()],
                }
                offer_request = {
                    "connection_id": agent.connection_id,
                    "cred_def_id": credential_definition_id,
                    "comment":
                    f"Offer on cred def id {credential_definition_id}",
                    "credential_preview": cred_preview,
                }
                await agent.admin_POST("/issue-credential/send-offer",
                                       offer_request)

                # TODO issue an additional credential for Student ID

            elif option == "2":
                log_status("#20 Request proof of degree from alice")
                req_attrs = [
                    {
                        "name": "name",
                        "restrictions": [{
                            "issuer_did": agent.did
                        }]
                    },
                    {
                        "name": "address",
                        "restrictions": [{
                            "issuer_did": agent.did
                        }]
                    },
                    {
                        "name": "self_attested_thing"
                    },
                ]
                req_preds = [{
                    "name": "age",
                    "p_type": ">=",
                    "p_value": 18,
                    "restrictions": [{
                        "issuer_did": agent.did
                    }],
                }]
                indy_proof_request = {
                    "name": "Proof of Ethereum Identity",
                    "version": "1.0",
                    "nonce": str(uuid4().int),
                    "requested_attributes": {
                        f"0_{req_attr['name']}_uuid": req_attr
                        for req_attr in req_attrs
                    },
                }
                proof_request_web_request = {
                    "connection_id": agent.connection_id,
                    "proof_request": indy_proof_request,
                }
                await agent.admin_POST("/present-proof/send-request",
                                       proof_request_web_request)

            elif option == "3":
                msg = await prompt("Enter message: ")
                await agent.admin_POST(
                    f"/connections/{agent.connection_id}/send-message",
                    {"content": msg})

        if show_timing:
            timing = await agent.fetch_timing()
            if timing:
                for line in agent.format_timing(timing):
                    log_msg(line)

    finally:
        terminated = True
        try:
            if agent:
                await agent.terminate()
        except Exception:
            LOGGER.exception("Error terminating agent:")
            terminated = False

    await asyncio.sleep(0.1)

    if not terminated:
        os._exit(1)
Exemple #16
0
async def main(start_port: int, show_timing: bool = False):

    genesis = await default_genesis_txns()
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)

    agent = None

    try:
        log_status(
            "#1 Provision an agent and wallet, get back configuration details")
        agent = CoordinatorAgent(start_port,
                                 start_port + 1,
                                 genesis_data=genesis,
                                 timing=show_timing)
        await agent.listen_webhooks(start_port + 2)

        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin url is at:", agent.admin_url)
        log_msg("Endpoint url is at:", agent.endpoint)

        with log_timer("Generate invitation duration:"):
            # Generate an invitation
            log_status(
                "#5 Create a connection to alice and print out the invite details"
            )
            connection = await agent.admin_POST(
                "/connections/create-invitation")

        agent.active_connection_id = connection["connection_id"]
        agent.connection_list.append(connection["connection_id"])
        log_json(connection, label="Invitation response:")
        log_msg("*****************")
        log_msg(json.dumps(connection["invitation"]),
                label="Invitation:",
                color=None)
        log_msg("*****************")

        # log_msg("Waiting for connection...")
        # await agent.detect_connection()
        async for option in prompt_loop(
            "(1) Send Proof Request, " +
            "(2) Send Message (3) New Connection (4) Input New Invitation Details (X) Exit? [1/2/3/4/X] "
        ):
            if option is None or option in "xX":
                break

            elif option == "1":
                log_status("#20 Request proof of degree from alice")
                req_attrs = [
                    {
                        "name": "date",
                        "restrictions": [{
                            "issuer_did": agent.nhsheadoffice_did
                        }]
                    },
                    {
                        "name": "hospital_name",
                        "restrictions": [{
                            "issuer_did": agent.nhsheadoffice_did
                        }]
                    },
                ]
                # req_preds = [
                #     {
                #         "name": "age",
                #         "p_type": ">=",
                #         "p_value": 18,
                #         "restrictions": [{"issuer_did": agent.did}],
                #     }
                # ]
                indy_proof_request = {
                    "name": "Proof of Verified Hospital",
                    "version": "1.0",
                    "nonce": str(uuid4().int),
                    "requested_attributes": {
                        f"0_{req_attr['name']}_uuid": req_attr
                        for req_attr in req_attrs
                    },
                    "requested_predicates": {},
                }
                print("Asking for this proof: ", indy_proof_request)
                proof_request_web_request = {
                    "connection_id": agent.active_connection_id,
                    "proof_request": indy_proof_request,
                }
                await agent.admin_POST("/present-proof/send-request",
                                       proof_request_web_request)

            elif option == "2":
                msg = await prompt("Enter message: ")
                await agent.admin_POST(
                    f"/connections/{agent.active_connection_id}/send-message",
                    {"content": msg})
            elif option == "3":
                # handle new invitation
                with log_timer("Generate invitation duration:"):
                    # Generate an invitation
                    log_status(
                        "#5 Create a connection to alice and print out the invite details"
                    )
                    connection = await agent.admin_POST(
                        "/connections/create-invitation")

                agent.active_connection_id = connection["connection_id"]
                agent.connection_list.append(connection["connection_id"])
                log_msg("all connections :", agent.connection_list)
                log_json(connection, label="Invitation response:")
                log_msg("*****************")
                log_msg(json.dumps(connection["invitation"]),
                        label="Invitation:",
                        color=None)
                log_msg("*****************")
                agent._connection_ready = asyncio.Future()

                log_msg("Waiting for connection...")
                await agent.detect_connection()
            elif option == "4":
                # handle new invitation
                log_status("Input new invitation details")
                await input_invitation(agent)
        if show_timing:
            timing = await agent.fetch_timing()
            if timing:
                for line in agent.format_timing(timing):
                    log_msg(line)

    finally:
        terminated = True
        try:
            if agent:
                await agent.terminate()
        except Exception:
            LOGGER.exception("Error terminating agent:")
            terminated = False

    await asyncio.sleep(0.1)

    if not terminated:
        os._exit(1)