async def generate_invitation(agent, use_did_exchange: bool):
    agent._connection_ready = asyncio.Future()
    with log_timer("Generate invitation duration:"):
        # Generate an invitation
        log_status(
            "#7 Create a connection to alice and print out the invite details")
        if use_did_exchange:
            invi_rec = await agent.admin_POST(
                "/out-of-band/create-invitation",
                {"include_handshake": True},
            )
        else:
            invi_rec = await agent.admin_POST("/connections/create-invitation")

    qr = QRCode(border=1)
    qr.add_data(invi_rec["invitation_url"])
    log_msg(
        "Use the following JSON to accept the invite from another demo agent."
        " Or use the QR code to connect from a mobile agent.")
    log_msg(json.dumps(invi_rec["invitation"]),
            label="Invitation Data:",
            color=None)
    qr.print_ascii(invert=True)

    log_msg("Waiting for connection...")
    await agent.detect_connection()
    async def generate_invitation(
        self,
        use_did_exchange: bool,
        auto_accept: bool = True,
        display_qr: bool = False,
        wait: bool = False,
    ):
        self._connection_ready = asyncio.Future()
        with log_timer("Generate invitation duration:"):
            # Generate an invitation
            log_status(
                "#7 Create a connection to alice and print out the invite details"
            )
            invi_rec = await self.get_invite(use_did_exchange, auto_accept)

        if display_qr:
            qr = QRCode(border=1)
            qr.add_data(invi_rec["invitation_url"])
            log_msg(
                "Use the following JSON to accept the invite from another demo agent."
                " Or use the QR code to connect from a mobile agent.")
            log_msg(json.dumps(invi_rec["invitation"]),
                    label="Invitation Data:",
                    color=None)
            qr.print_ascii(invert=True)

        if wait:
            log_msg("Waiting for connection...")
            await self.detect_connection()

        return invi_rec
Exemple #3
0
def makeQRCode(data, mode):
    """ Make a graphical representation of a QRCODE in unicode."""
    sio = StringIO()
    qr_code = QRCode()
    qr_code.add_data(data)
    qr_code.print_ascii(out=sio, invert=mode == 'text')
    return '\n'.join(line.lstrip() for line in sio.getvalue().split('\n'))
Exemple #4
0
    def _qr_code_auth(self):
        print(
            'You must authenticate with your phone to be able to access your data.'
        )
        print(
            'Scan the QRCode below with you Nubank application on the following menu:'
        )
        print('Nu(Seu Nome) > Perfil > Acesso pelo site')
        content = uuid.uuid4()
        qr = QRCode()
        qr.add_data(content)
        qr.print_ascii(invert=True)
        input('After the scan, press enter do proceed')
        payload = {'qr_code_id': str(content), 'type': 'login-webapp'}
        req = requests.post(self.proxy_list_app_url['lift'],
                            json=payload,
                            headers=self.headers)
        if req.status_code != 200:
            raise NuException('Failed to authenticate with QRCode')

        data = json.loads(req.content.decode('utf-8'))
        self.headers['Authorization'] = 'Bearer {}'.format(
            data['access_token'])
        self.feed_url = data['_links']['events']['href']
        self.query_url = data['_links']['ghostflame']['href']
        self.bills_url = data['_links']['bills_summary']['href']
Exemple #5
0
def totp_setup(session, client_id, username, password):
    response = cognito_client.associate_software_token(Session=session)
    secret = response['SecretCode']
    qr_uri = f'otpauth://totp/Cognito:{username}?secret={secret}&issuer=Cognito'
    qr = QRCode()
    qr.add_data(qr_uri)
    qr.make(fit=True)
    qr.print_ascii()

    user_code = input('Scan the QR code, then input the TOTP: ')
    response = cognito_client.verify_software_token(
        Session=response['Session'], UserCode=user_code)

    if response['Status'] != 'SUCCESS':
        print(f'Failed to verify MFA: {json.dumps(auth_response)}')
        sys.exit(1)

    token_response = auth_req(client_id, username, password)

    cognito_client.set_user_mfa_preference(
        SoftwareTokenMfaSettings={
            'Enabled': True,
            'PreferredMfa': True
        },
        AccessToken=token_response['AuthenticationResult']['AccessToken'])

    return token_response
Exemple #6
0
def makeQRCode(data, mode):
    """ Make a graphical representation of a QRCODE in unicode."""
    sio = StringIO()
    qr_code = QRCode()
    qr_code.add_data(data)
    qr_code.print_ascii(out=sio, invert=mode == 'text')
    return '\n'.join(line.lstrip() for line in sio.getvalue().split('\n'))
Exemple #7
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
Exemple #8
0
def text2QRCode(value):
    from qrcode import QRCode

    qr = QRCode()
    qr.add_data(value)
    qr_code = StringIO()
    qr.print_ascii(out=qr_code)
    ascii = qr_code.getvalue()
    return ascii
Exemple #9
0
def print_qr_code(uuid: str):
    qr = QRCode()
    qr.add_data(uuid)
    try:
        get_ipython
        from IPython.display import display
        display(qr.make_image(fill_color="#111", back_color="#ccc"))
    except NameError:
        qr.print_ascii(invert=True)
Exemple #10
0
def show_qr_code(image_file):
    from pyzbar import pyzbar
    from qrcode import QRCode
    from PIL import Image
    qr = QRCode()
    results = pyzbar.decode(Image.open(image_file),
                            symbols=[pyzbar.ZBarSymbol.QRCODE])
    qr_data = results[0].data
    qr.add_data(qr_data)
    qr.print_ascii()
    qr.clear()
Exemple #11
0
def main():
    """Get command-line arguments and output results in specified formats"""
    args = cli(argv[0])
    excluded_network_list = args.excluded_network_list
    inclusive_netlist = exclude_nets_to_include_nets(excluded_network_list,
                                                     strict=args.strict)

    if args.no_ip6 is False:
        inclusive_netlist.append(ip_network_safe(IPV6_ALL_NET))

    csv_inclusive_netlist = ','.join(
        [included_net.compressed for included_net in inclusive_netlist])

    if args.enable_lines:
        output('')
        output('Line-based output:')
        for included_net in [net.compressed for net in inclusive_netlist]:
            output('{}'.format(included_net))

    if args.disable_csv is False:
        output('')
        output('{}{}'.format(
            'AllowedIPs = ' if args.wireguard_format is True else '',
            csv_inclusive_netlist))

    if args.qrencode is True:
        output('')
        if QRCode is not None:
            output('Generating QR code using Python QRCode()')
            output('========================================\n')
            qr = QRCode(error_correction=ERROR_CORRECT_M)
            qr.add_data(csv_inclusive_netlist)
            if isatty(stdout.fileno()):
                qr.print_ascii(tty=True)
                return
            fatal('Must have an allocated TTY to generate QR code!')
        else:
            output('Generating QR code using qrencode -t ansi')
            output('========================================\n')
            qr_encode_command = QR_ENCODE_COMMAND + [csv_inclusive_netlist]
            output('Generating WireGuard friendly QR code format:')
            try:
                result = run(qr_encode_command, stdout=PIPE, check=True)
            except CalledProcessError as err:
                fatal('failed to invoke `qrencode` app ({})'.format(err))
            output(result.stdout.decode('utf-8'))
            output('')
    else:
        output(
            'NOTE: Consider using `--qr` to generate a QR code on your terminal!'
        )
def passgenCommandLine(argv=[]):
    from derivatex.passgen import passgen
    if len(argv) == 0 or argv[1] is None:
        website_name = input("Enter the website name: ")
    else:
        website_name = argv[1]
    from pyperclip import copy
    from qrcode import QRCode
    short = False
    if len(argv) > 2:  # optional arguments
        if argv[2] == "short":
            short = True
    password = passgen(website_name, short)
    copy(password)
    print(password)
    print("")
    print("Password has been copied to your clipboard")
    print("")
    qr = QRCode(border=1)
    qr.add_data(password)
    qr.print_ascii()
Exemple #13
0
def qr_ver(veri,
           png: bool = False,
           favicon: str = None,
           txt: bool = False) -> str:
    qr = QRCode(border=2)
    qr.add_data(veri)
    qr.make(fit=True)

    f = StringIO()
    qr.print_ascii(out=f)
    f.seek(0)
    str_qr = f.read()[:-1]

    if png:
        img = qr.make_image(image_factory=StyledPilImage,
                            module_drawer=VerticalBarsDrawer(),
                            embeded_image_path=favicon)
        img.save('qr.png')

    if txt:
        with open("qr.txt", "w+") as dosya:
            dosya.write(str_qr)

    return str_qr
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"
                )
                await agent.create_and_publish_revocation_registry(
                    credential_definition_id, TAILS_FILE_COUNT)

        # TODO add an additional credential for Student ID

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

        agent.connection_id = connection["connection_id"]

        qr = QRCode()
        qr.add_data(connection["invitation_url"])
        log_msg(
            "Use the following JSON to accept the invite from another demo agent. Or use the QR code to connect from a mobile agent."
        )
        log_msg(json.dumps(connection["invitation"]),
                label="Invitation Data:",
                color=None)
        qr.print_ascii(invert=True)

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

        exchange_tracing = False
        options = ("    (1) Issue Credential\n"
                   "    (2) Send Proof Request\n"
                   "    (3) Send Message\n")
        if revocation:
            options += ("    (4) Revoke Credential\n"
                        "    (5) Publish Revocations\n"
                        "    (6) Add Revocation Registry\n")
        options += "    (T) Toggle tracing on credential/proof exchange\n"
        options += "    (X) Exit?\n[1/2/3/{}T/X] ".format(
            "4/5/6/" if revocation else "")
        async for option in prompt_loop(options):
            option = option.strip()
            if option is None or option in "xX":
                break

            elif option in "tT":
                exchange_tracing = not exchange_tracing
                log_msg(">>> Credential/Proof Exchange Tracing is {}".format(
                    "ON" if exchange_tracing else "OFF"))
            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": "Thapelo Sekwena",
                    "date": "2020-06-01",
                    "degree": "MBA",
                    "age": "26",
                    "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,
                    "trace": exchange_tracing,
                }
                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 Thapelo")
                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
                        }]
                    })
                if SELF_ATTESTED:
                    # 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",
                    "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,
                    "trace": exchange_tracing,
                }
                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:
                rev_reg_id = (
                    await prompt("Enter revocation registry ID: ")).strip()
                cred_rev_id = (
                    await prompt("Enter credential revocation ID: ")).strip()
                publish = json.dumps(
                    (await prompt("Publish now? [Y/N]: ", default="N")
                     ).strip() in ("yY"))
                try:
                    await agent.admin_POST("/issue-credential/revoke"
                                           f"?publish={publish}"
                                           f"&rev_reg_id={rev_reg_id}"
                                           f"&cred_rev_id={cred_rev_id}")
                except ClientError:
                    pass
            elif option == "5" and revocation:
                try:
                    resp = await agent.admin_POST(
                        "/issue-credential/publish-revocations")
                    agent.log(
                        "Published revocations for {} revocation registr{} {}".
                        format(
                            len(resp["results"]),
                            "y" if len(resp) == 1 else "ies",
                            json.dumps([k for k in resp["results"]], indent=4),
                        ))
                except ClientError:
                    pass
            elif option == "6" and revocation:
                log_status("#19 Add another revocation registry")
                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)
Exemple #15
0
 def make_code(self, code):
     q = QRCode()
     q.add_data(code)
     stream = FakeStream()
     q.print_ascii(stream)
     return self.template % u''.join(stream).replace('\n', self.eol)
Exemple #16
0
async def main(args):
    faber_agent = await create_agent_with_args(args, ident="faber")

    try:
        log_status(
            "#1 Provision an agent and wallet, get back configuration details"
            + (f" (Wallet type: {faber_agent.wallet_type})" if faber_agent.
               wallet_type else ""))
        agent = FaberAgent(
            "faber.agent",
            faber_agent.start_port,
            faber_agent.start_port + 1,
            genesis_data=faber_agent.genesis_txns,
            no_auto=faber_agent.no_auto,
            tails_server_base_url=faber_agent.tails_server_base_url,
            timing=faber_agent.show_timing,
            multitenant=faber_agent.multitenant,
            mediation=faber_agent.mediation,
            wallet_type=faber_agent.wallet_type,
            seed=faber_agent.seed,
            aip=faber_agent.aip,
        )

        if faber_agent.cred_type == CRED_FORMAT_INDY:
            faber_agent.public_did = True
            faber_schema_name = "degree schema"
            faber_schema_attrs = [
                "name",
                "date",
                "degree",
                "birthdate_dateint",
                "timestamp",
            ]
            await faber_agent.initialize(
                the_agent=agent,
                schema_name=faber_schema_name,
                schema_attrs=faber_schema_attrs,
            )
        elif faber_agent.cred_type == CRED_FORMAT_JSON_LD:
            faber_agent.public_did = True
            await faber_agent.initialize(the_agent=agent)
        else:
            raise Exception("Invalid credential type:" + faber_agent.cred_type)

        # generate an invitation for Alice
        await faber_agent.generate_invitation(display_qr=True, wait=True)

        exchange_tracing = False
        options = (
            "    (1) Issue Credential\n"
            "    (2) Send Proof Request\n"
            "    (2a) Send *Connectionless* Proof Request (requires a Mobile client)\n"
            "    (3) Send Message\n"
            "    (4) Create New Invitation\n")
        if faber_agent.revocation:
            options += "    (5) Revoke Credential\n" "    (6) Publish Revocations\n"
        if faber_agent.multitenant:
            options += "    (W) Create and/or Enable Wallet\n"
        options += "    (T) Toggle tracing on credential/proof exchange\n"
        options += "    (X) Exit?\n[1/2/3/4/{}{}T/X] ".format(
            "5/6/" if faber_agent.revocation else "",
            "W/" if faber_agent.multitenant else "",
        )
        async for option in prompt_loop(options):
            if option is not None:
                option = option.strip()

            if option is None or option in "xX":
                break

            elif option in "wW" and faber_agent.multitenant:
                target_wallet_name = await prompt("Enter wallet name: ")
                include_subwallet_webhook = await prompt(
                    "(Y/N) Create sub-wallet webhook target: ")
                if include_subwallet_webhook.lower() == "y":
                    created = await faber_agent.agent.register_or_switch_wallet(
                        target_wallet_name,
                        webhook_port=faber_agent.agent.get_new_webhook_port(),
                        public_did=True,
                        mediator_agent=faber_agent.mediator_agent,
                    )
                else:
                    created = await faber_agent.agent.register_or_switch_wallet(
                        target_wallet_name,
                        public_did=True,
                        mediator_agent=faber_agent.mediator_agent,
                    )
                # create a schema and cred def for the new wallet
                # TODO check first in case we are switching between existing wallets
                if created:
                    # TODO this fails because the new wallet doesn't get a public DID
                    await faber_agent.create_schema_and_cred_def(
                        schema_name=faber_schema_name,
                        schema_attrs=faber_schema_attrs,
                    )

            elif option in "tT":
                exchange_tracing = not exchange_tracing
                log_msg(">>> Credential/Proof Exchange Tracing is {}".format(
                    "ON" if exchange_tracing else "OFF"))

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

                if faber_agent.aip == 10:
                    offer_request = faber_agent.agent.generate_credential_offer(
                        faber_agent.aip, None, faber_agent.cred_def_id,
                        exchange_tracing)
                    await faber_agent.agent.admin_POST(
                        "/issue-credential/send-offer", offer_request)

                elif faber_agent.aip == 20:
                    if faber_agent.cred_type == CRED_FORMAT_INDY:
                        offer_request = faber_agent.agent.generate_credential_offer(
                            faber_agent.aip,
                            faber_agent.cred_type,
                            faber_agent.cred_def_id,
                            exchange_tracing,
                        )

                    elif faber_agent.cred_type == CRED_FORMAT_JSON_LD:
                        offer_request = faber_agent.agent.generate_credential_offer(
                            faber_agent.aip,
                            faber_agent.cred_type,
                            None,
                            exchange_tracing,
                        )

                    else:
                        raise Exception(
                            f"Error invalid credential type: {faber_agent.cred_type}"
                        )

                    await faber_agent.agent.admin_POST(
                        "/issue-credential-2.0/send-offer", offer_request)

                else:
                    raise Exception(
                        f"Error invalid AIP level: {faber_agent.aip}")

            elif option == "2":
                log_status("#20 Request proof of degree from alice")
                if faber_agent.aip == 10:
                    proof_request_web_request = (
                        faber_agent.agent.generate_proof_request_web_request(
                            faber_agent.aip,
                            faber_agent.cred_type,
                            faber_agent.revocation,
                            exchange_tracing,
                        ))
                    await faber_agent.agent.admin_POST(
                        "/present-proof/send-request",
                        proof_request_web_request)
                    pass

                elif faber_agent.aip == 20:
                    if faber_agent.cred_type == CRED_FORMAT_INDY:
                        proof_request_web_request = (
                            faber_agent.agent.
                            generate_proof_request_web_request(
                                faber_agent.aip,
                                faber_agent.cred_type,
                                faber_agent.revocation,
                                exchange_tracing,
                            ))

                    elif faber_agent.cred_type == CRED_FORMAT_JSON_LD:
                        proof_request_web_request = (
                            faber_agent.agent.
                            generate_proof_request_web_request(
                                faber_agent.aip,
                                faber_agent.cred_type,
                                faber_agent.revocation,
                                exchange_tracing,
                            ))

                    else:
                        raise Exception("Error invalid credential type:" +
                                        faber_agent.cred_type)

                    await agent.admin_POST("/present-proof-2.0/send-request",
                                           proof_request_web_request)

                else:
                    raise Exception(
                        f"Error invalid AIP level: {faber_agent.aip}")

            elif option == "2a":
                log_status(
                    "#20 Request * Connectionless * proof of degree from alice"
                )
                if faber_agent.aip == 10:
                    proof_request_web_request = (
                        faber_agent.agent.generate_proof_request_web_request(
                            faber_agent.aip,
                            faber_agent.cred_type,
                            faber_agent.revocation,
                            exchange_tracing,
                            connectionless=True,
                        ))
                    proof_request = await faber_agent.agent.admin_POST(
                        "/present-proof/create-request",
                        proof_request_web_request)
                    pres_req_id = proof_request["presentation_exchange_id"]
                    url = ("http://" + os.getenv("DOCKERHOST").replace(
                        "{PORT}", str(faber_agent.agent.admin_port + 1)) +
                           "/webhooks/pres_req/" + pres_req_id + "/")
                    log_msg(f"Proof request url: {url}")
                    qr = QRCode(border=1)
                    qr.add_data(url)
                    log_msg(
                        "Scan the following QR code to accept the proof request from a mobile agent."
                    )
                    qr.print_ascii(invert=True)

                elif faber_agent.aip == 20:
                    if faber_agent.cred_type == CRED_FORMAT_INDY:
                        proof_request_web_request = (
                            faber_agent.agent.
                            generate_proof_request_web_request(
                                faber_agent.aip,
                                faber_agent.cred_type,
                                faber_agent.revocation,
                                exchange_tracing,
                                connectionless=True,
                            ))
                    elif faber_agent.cred_type == CRED_FORMAT_JSON_LD:
                        proof_request_web_request = (
                            faber_agent.agent.
                            generate_proof_request_web_request(
                                faber_agent.aip,
                                faber_agent.cred_type,
                                faber_agent.revocation,
                                exchange_tracing,
                                connectionless=True,
                            ))
                    else:
                        raise Exception("Error invalid credential type:" +
                                        faber_agent.cred_type)

                    proof_request = await faber_agent.agent.admin_POST(
                        "/present-proof-2.0/create-request",
                        proof_request_web_request)
                    pres_req_id = proof_request["pres_ex_id"]
                    url = ("http://" + os.getenv("DOCKERHOST").replace(
                        "{PORT}", str(faber_agent.agent.admin_port + 1)) +
                           "/webhooks/pres_req/" + pres_req_id + "/")
                    log_msg(f"Proof request url: {url}")
                    qr = QRCode(border=1)
                    qr.add_data(url)
                    log_msg(
                        "Scan the following QR code to accept the proof request from a mobile agent."
                    )
                    qr.print_ascii(invert=True)
                else:
                    raise Exception(
                        f"Error invalid AIP level: {faber_agent.aip}")

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

            elif option == "4":
                log_msg("Creating a new invitation, please receive "
                        "and accept this invitation using Alice agent")
                await faber_agent.generate_invitation(display_qr=True,
                                                      wait=True)

            elif option == "5" and faber_agent.revocation:
                rev_reg_id = (
                    await prompt("Enter revocation registry ID: ")).strip()
                cred_rev_id = (
                    await prompt("Enter credential revocation ID: ")).strip()
                publish = (await prompt("Publish now? [Y/N]: ",
                                        default="N")).strip() in "yY"
                try:
                    await faber_agent.agent.admin_POST(
                        "/revocation/revoke",
                        {
                            "rev_reg_id": rev_reg_id,
                            "cred_rev_id": cred_rev_id,
                            "publish": publish,
                        },
                    )
                except ClientError:
                    pass

            elif option == "6" and faber_agent.revocation:
                try:
                    resp = await faber_agent.agent.admin_POST(
                        "/revocation/publish-revocations", {})
                    faber_agent.agent.log(
                        "Published revocations for {} revocation registr{} {}".
                        format(
                            len(resp["rrid2crid"]),
                            "y" if len(resp["rrid2crid"]) == 1 else "ies",
                            json.dumps([k for k in resp["rrid2crid"]],
                                       indent=4),
                        ))
                except ClientError:
                    pass

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

    finally:
        terminated = await faber_agent.terminate()

    await asyncio.sleep(0.1)

    if not terminated:
        os._exit(1)
Exemple #17
0
def main():
    s = socket.socket()
    thread1.start()
    print("Socket successfully created.")

    while True:
        try:
            print("Enter port (leave blank for 4444): ", end="")
            inp = input()

            if inp == '':
                port = 4444
            else:
                port = int(inp)

            s.bind(('', port))
            print("Socket bound to %s" % (port))
            break
        except OSError:
            print("Port " + str(port) +
                  " is already in use. Please use the following command:")
            print("lsof -n -i4TCP:" + str(port) + " | grep LISTEN")
            os._exit(os.EX_OK)
        except:
            print("Unexpected error while connecting to port")

    s.listen()
    try:
        # serverIP = socket.gethostbyname(socket.gethostname())+":"+str(port)
        serverIP = get_ip_address() + ":" + str(port)
    except socket.gaierror:
        output = subprocess.check_output("ipconfig getifaddr en0",
                                         shell=True).decode()[:-1]
        serverIP = output + ":" + str(port)

    qr = QRCode()
    qr.add_data(serverIP)

    while True:
        print("Connect at IP = " + serverIP)
        print('Or scan this:')
        qr.print_ascii(invert=True)
        qr.print_ascii()
        print("Socket is listening...")

        c, addr = s.accept()

        print('Got connection from', addr)

        while True:
            try:
                message = c.recv(256).decode("utf-8")
                #message comes in byte array so change it to string first

                message = message.split(
                    "%")  #use & to split tokens, and % to split messages.

                for msg in message:
                    if msg != '':
                        msg = msg.split("&")
                        print("DEBUG: ", msg)
                        if (msg[0] == 'button'):
                            handleButton(msg[1], msg[2])
                        elif (msg[0] == 'tilt'):
                            if (len(msg) == 2):
                                if (msg[1] == '0'):
                                    global button
                                    button = '$'
                            if (len(msg) < 3):
                                continue
                            elif (msg[2] == ''):
                                continue
                            elif msg[1] == '+':
                                tilt(True, float(msg[2]))
                            elif msg[1] == '-':
                                tilt(False, float(msg[2]))
                        elif (msg[0] == 'cont'):
                            handleController(msg[1:])
                        elif (msg[0] == 'track'):
                            handleTrackpad(msg[1:])
                        elif (msg[0] == 'status'):
                            c.send(bytes('pass' + msg[1], "utf-8"))
                        elif (msg[0] == 'disconnect'):
                            raise ConnectionResetError
            except ConnectionResetError:
                print("Disconnected from client")
                c.close()
                print("Socket closed")
                ans = input("Do you want to connect again? (y/n): ")
                if (ans == 'n'):
                    os._exit(0)
                break
    async def make_agent_POST_request(self,
                                      op,
                                      rec_id=None,
                                      data=None,
                                      text=False,
                                      params=None) -> (int, str):
        print("make_agent_POST_request:", op)

        if op["topic"] == "connection":
            operation = op["operation"]
            if operation == "receive-invitation":
                self.connection_state = "invited"
                print(
                    "================================================================="
                )

                message_bytes = json.dumps(data).encode("ascii")
                base64_bytes = base64.b64encode(message_bytes)
                base64_message = base64_bytes.decode("ascii")
                invitation_url = data[
                    "serviceEndpoint"] + "?c_i=" + base64_message

                qr = QRCode(border=1)
                qr.add_data(invitation_url)
                log_msg(
                    "Use the following JSON to accept the invite from another demo agent."
                    " Or use the QR code to connect from a mobile agent.")
                log_msg(json.dumps(data), label="Invitation Data:", color=None)
                qr.print_ascii(invert=True)
                log_msg("If you can't scan the QR code here is the url.")
                print("Invitation url:", invitation_url)
                print(
                    "================================================================="
                )

                return (
                    200,
                    '{"result": "ok", "connection_id": "1", "state": "' +
                    self.connection_state + '"}',
                )

            elif (operation == "accept-invitation"
                  or operation == "accept-request" or operation == "remove"
                  or operation == "start-introduction"
                  or operation == "send-ping"):
                self.connection_state = "requested"
                return (
                    200,
                    '{"result": "ok", "connection_id": "1", "state": "' +
                    self.connection_state + '"}',
                )

        elif op["topic"] == "issue-credential":
            operation = op["operation"]
            if operation == "send-request":
                print(
                    "================================================================="
                )
                print("Please respond to the Credential Offer!")
                print(
                    "================================================================="
                )
                return (
                    200,
                    '{"result": "ok", "thread_id": "1", "state": "request-sent"}',
                )
            elif operation == "store":
                return (
                    200,
                    '{"result": "ok", "thread_id": "1", "credential_id": "' +
                    rec_id + '", "state": "done"}',
                )
            else:
                return (200,
                        '{"result": "ok", "thread_id": "1", "state": "N/A"}')

        elif op["topic"] == "proof":
            operation = op["operation"]
            if operation == "send-presentation":
                print(
                    "================================================================="
                )
                print("Please respond to the Proof Request!")
                print(
                    "================================================================="
                )
                return (
                    200,
                    '{"result": "ok", "thread_id": "1", "state": "presentation-sent"}',
                )
            else:
                return (200,
                        '{"result": "ok", "thread_id": "1", "state": "N/A"}')

        return (501, "501: Not Implemented\n\n".encode("utf8"))
Exemple #19
0
    async def start(self) -> None:
        """Start the agent."""

        context = self.root_profile.context

        # Start up transports
        try:
            await self.inbound_transport_manager.start()
        except Exception:
            LOGGER.exception("Unable to start inbound transports")
            raise
        try:
            await self.outbound_transport_manager.start()
        except Exception:
            LOGGER.exception("Unable to start outbound transports")
            raise

        if self.outbound_queue:
            try:
                await self.outbound_queue.start()
            except Exception:
                LOGGER.exception("Unable to start outbound queue")
                raise

        # Start up Admin server
        if self.admin_server:
            try:
                await self.admin_server.start()
            except Exception:
                LOGGER.exception("Unable to start administration API")
            # Make admin responder available during message parsing
            # This allows webhooks to be called when a connection is marked active,
            # for example
            responder = AdminResponder(
                self.root_profile,
                self.admin_server.outbound_message_router,
            )
            context.injector.bind_instance(BaseResponder, responder)

        # Get agent label
        default_label = context.settings.get("default_label")

        # Show some details about the configuration to the user
        LoggingConfigurator.print_banner(
            default_label,
            self.inbound_transport_manager.registered_transports,
            self.outbound_transport_manager.registered_transports,
            self.outbound_queue,
            self.setup_public_did and self.setup_public_did.did,
            self.admin_server,
        )

        # record ACA-Py version in Wallet, if needed
        async with self.root_profile.session() as session:
            storage: BaseStorage = session.context.inject(BaseStorage)
            agent_version = f"v{__version__}"
            try:
                record = await storage.find_record(
                    type_filter=RECORD_TYPE_ACAPY_VERSION,
                    tag_query={},
                )
                if record.value != agent_version:
                    LOGGER.exception((f"Wallet storage version {record.value} "
                                      "does not match this ACA-Py agent "
                                      f"version {agent_version}. Run aca-py "
                                      "upgrade command to fix this."))
                    raise
            except StorageNotFoundError:
                pass

        # Create a static connection for use by the test-suite
        if context.settings.get("debug.test_suite_endpoint"):
            mgr = ConnectionManager(self.root_profile)
            their_endpoint = context.settings["debug.test_suite_endpoint"]
            test_conn = await mgr.create_static_connection(
                my_seed=hashlib.sha256(
                    b"aries-protocol-test-subject").digest(),
                their_seed=hashlib.sha256(
                    b"aries-protocol-test-suite").digest(),
                their_endpoint=their_endpoint,
                alias="test-suite",
            )
            print("Created static connection for test suite")
            print(" - My DID:", test_conn.my_did)
            print(" - Their DID:", test_conn.their_did)
            print(" - Their endpoint:", their_endpoint)
            print()
            del mgr

        # Clear default mediator
        if context.settings.get("mediation.clear"):
            mediation_mgr = MediationManager(self.root_profile)
            await mediation_mgr.clear_default_mediator()
            print("Default mediator cleared.")

        # Clear default mediator
        # Set default mediator by id
        default_mediator_id = context.settings.get("mediation.default_id")
        if default_mediator_id:
            mediation_mgr = MediationManager(self.root_profile)
            try:
                await mediation_mgr.set_default_mediator_by_id(
                    default_mediator_id)
                print(f"Default mediator set to {default_mediator_id}")
            except Exception:
                LOGGER.exception("Error updating default mediator")

        # Print an invitation to the terminal
        if context.settings.get("debug.print_invitation"):
            try:
                mgr = OutOfBandManager(self.root_profile)
                invi_rec = await mgr.create_invitation(
                    my_label=context.settings.get("debug.invite_label"),
                    public=context.settings.get("debug.invite_public", False),
                    multi_use=context.settings.get("debug.invite_multi_use",
                                                   False),
                    hs_protos=[HSProto.RFC23],
                    metadata=json.loads(
                        context.settings.get("debug.invite_metadata_json",
                                             "{}")),
                )
                base_url = context.settings.get("invite_base_url")
                invite_url = invi_rec.invitation.to_url(base_url)
                print("Invitation URL:")
                print(invite_url, flush=True)
                qr = QRCode(border=1)
                qr.add_data(invite_url)
                qr.print_ascii(invert=True)
                del mgr
            except Exception:
                LOGGER.exception("Error creating invitation")

        # Print connections protocol invitation to the terminal
        if context.settings.get("debug.print_connections_invitation"):
            try:
                mgr = ConnectionManager(self.root_profile)
                _record, invite = await mgr.create_invitation(
                    my_label=context.settings.get("debug.invite_label"),
                    public=context.settings.get("debug.invite_public", False),
                    multi_use=context.settings.get("debug.invite_multi_use",
                                                   False),
                    metadata=json.loads(
                        context.settings.get("debug.invite_metadata_json",
                                             "{}")),
                )
                base_url = context.settings.get("invite_base_url")
                invite_url = invite.to_url(base_url)
                print("Invitation URL (Connections protocol):")
                print(invite_url, flush=True)
                qr = QRCode(border=1)
                qr.add_data(invite_url)
                qr.print_ascii(invert=True)
                del mgr
            except Exception:
                LOGGER.exception("Error creating invitation")

        # mediation connection establishment
        provided_invite: str = context.settings.get("mediation.invite")

        try:
            async with self.root_profile.session() as session:
                invite_store = MediationInviteStore(
                    session.context.inject(BaseStorage))
                mediation_invite_record = (
                    await
                    invite_store.get_mediation_invite_record(provided_invite))
        except Exception:
            LOGGER.exception("Error retrieving mediator invitation")
            mediation_invite_record = None

        # Accept mediation invitation if one was specified or stored
        if mediation_invite_record is not None:
            try:
                mediation_connections_invite = context.settings.get(
                    "mediation.connections_invite", False)
                invitation_handler = (ConnectionInvitation
                                      if mediation_connections_invite else
                                      InvitationMessage)

                if not mediation_invite_record.used:
                    # clear previous mediator configuration before establishing a
                    # new one
                    await MediationManager(self.root_profile
                                           ).clear_default_mediator()

                    mgr = (ConnectionManager(self.root_profile)
                           if mediation_connections_invite else
                           OutOfBandManager(self.root_profile))

                    conn_record = await mgr.receive_invitation(
                        invitation=invitation_handler.from_url(
                            mediation_invite_record.invite),
                        auto_accept=True,
                    )
                    async with self.root_profile.session() as session:
                        await (MediationInviteStore(
                            session.context.inject(
                                BaseStorage)).mark_default_invite_as_used())

                        await conn_record.metadata_set(
                            session,
                            MediationManager.SEND_REQ_AFTER_CONNECTION, True)
                        await conn_record.metadata_set(
                            session,
                            MediationManager.SET_TO_DEFAULT_ON_GRANTED, True)

                    print("Attempting to connect to mediator...")
                    del mgr
            except Exception:
                LOGGER.exception("Error accepting mediation invitation")

        # notify protcols of startup status
        await self.root_profile.notify(STARTUP_EVENT_TOPIC, {})
Exemple #20
0
def _do_qr(args):
    uri = _gen_uri()

    qr = QRCode()
    qr.add_data(uri)
    qr.print_ascii(invert=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)

            elif int(option) == 3:
                invitation = input("Invite details: ")
                auto_accept = input("Auto accept invitation? n/y: ")
                if auto_accept == "y":
                    auto_accept = True
                else:
                    auto_accept = False
                api_handler.receive_invitation(invitation_url=invitation,
                                               alias=alias,
                                               auto_accept=True)

            elif int(option) == 4:
                connection_id = input("Send message to <connection id> :")
                message = input("Message <message>:")