Ejemplo n.º 1
0
 def read_keyring(self, *args, **kwargs):
     if self.checksum_address is None:
         raise self.ConfigurationError(
             "No account specified to unlock keyring")
     self.keyring = NucypherKeyring(keyring_root=self.keyring_dir,
                                    account=self.checksum_address,
                                    *args,
                                    **kwargs)
Ejemplo n.º 2
0
    def post(self):

        if not request.data["account"] or not request.data["password"]:

            response = {'message': "User data missing"}

            return make_response(jsonify(response)), 404

        user = request.data["account"]

        password = request.data["password"]

        try:
            keyring = NucypherKeyring.generate(
                checksum_address=user,
                password=password,  # used to encrypt nucypher private keys
                keyring_root="//home/ghard/.local/share/nucypher/keyring")
            keyring.unlock(password=password)

            masterfile_contract.functions.RegisterUser(
                user, keyring.signing_public_key.to_bytes(),
                keyring.encrypting_public_key.to_bytes()).transact(
                    {"from": w3.eth.accounts[0]})

            response = {'message': "Registration Accepted"}

            keyring.lock()

            return make_response(jsonify(response)), 200

        except:

            try:
                keyring = NucypherKeyring(account=user)
                keyring.unlock(password=password)

                # Double check user has keys

                keys = masterfile_contract.functions.userKeys(user).call()

                print(keys)

                if not keys[0]:
                    masterfile_contract.functions.RegisterUser(
                        user, keyring.signing_public_key.to_bytes(),
                        keyring.encrypting_public_key.to_bytes()).transact(
                            {"from": w3.eth.accounts[0]})

                response = {'message': "Login Successful"}
                keyring.lock()

                return make_response(jsonify(response)), 200

            except:

                response = {'message': "Invalid Login"}

                return make_response(jsonify(response)), 404
Ejemplo n.º 3
0
 def attach_keyring(self, checksum_address: str = None, *args, **kwargs) -> None:
     account = checksum_address or self.checksum_address
     if not account:
         raise self.ConfigurationError("No account specified to unlock keyring")
     if self.keyring is not NO_KEYRING_ATTACHED:
         if self.keyring.checksum_address != account:
             raise self.ConfigurationError("There is already a keyring attached to this configuration.")
         return
     self.keyring = NucypherKeyring(keyring_root=self.keyring_root, account=account, *args, **kwargs)
Ejemplo n.º 4
0
    def attach_keyring(self, checksum_address: str = None, *args, **kwargs) -> None:
        if self.keyring is not NO_KEYRING_ATTACHED:
            if self.keyring.checksum_address != (checksum_address or self.checksum_public_address):
                raise self.ConfigurationError("There is already a keyring attached to this configuration.")
            return

        if (checksum_address or self.checksum_public_address) is None:
            raise self.ConfigurationError("No account specified to unlock keyring")

        self.keyring = NucypherKeyring(keyring_root=self.keyring_dir,  # type: str
                                       account=checksum_address or self.checksum_public_address,  # type: str
                                       *args, **kwargs)
Ejemplo n.º 5
0
    def get(self):
        "User should send Bob password to decrypt files"

        try:
            user = request.args.get("user")
            pw = request.args.get("password")
            label = request.args.get("label")
            frmt = request.args.get("frmt")

        except:
            response = {'message': "Insufficient Query Params"}

            return make_response(jsonify(response)), 404

        keyringBob = NucypherKeyring(account=user)

        keyringBob.unlock(password=pw)

        bob = Bob(keyring=keyringBob,
                  known_nodes=[ursula],
                  federated_only=True,
                  learn_on_same_thread=True,
                  domain=TEMPORARY_DOMAIN)

        bob.join_policy(label.encode(), alice_sig_pubkey)

        from nucypher.characters.lawful import Enrico

        global globalStorage

        enrico1 = Enrico.from_public_keys(
            verifying_key=globalStorage[label]["data_source_public_key"],
            policy_encrypting_key=globalStorage[label]["policy_pubkey"])

        imgUrl = base_uri + label + "." + frmt
        response = requests.get(imgUrl)

        ciphertext = UmbralMessageKit.from_bytes(response.content)

        decrypted_plaintext = bob.retrieve(
            ciphertext,
            label=label.encode(),
            enrico=enrico1,
            alice_verifying_key=alice_sig_pubkey)

        return send_file(io.BytesIO(decrypted_plaintext[0]),
                         mimetype="image/" + frmt,
                         as_attachment=False,
                         attachment_filename='{}.'.format(label) + frmt), 200
    def alice_from_configutation(self, username, password, account):
        path = self.user_path + username + '/'
        keyring_path = path + "keyring"
        full_path = path + 'alice.json'
        alice_config = self.configure_alice(path)
        
        configuration = alice_config.from_configuration_file(
            config_root=os.path.join(path),
            filepath=full_path,
            keyring=NucypherKeyring(
                account=account,
                keyring_root=os.path.join(keyring_path),
            ),
        )

        configuration.keyring.unlock(password)
        self.Alice = configuration.produce()
        return self.Alice
Ejemplo n.º 7
0
    def post(self):
        keys = request.json['keys']
        path = self.writeKeys(keys)

        password = request.json['password']
        address = request.json['address']
        passwd = PBKDF2(password,
                        address.encode(),
                        20,
                        count=30000,
                        hmac_hash_module=SHA256).hex()
        keyring = NucypherKeyring(account=address, keyring_root="./keys")
        keyring.unlock(password=passwd)

        bob = Bob(known_nodes=[self.URSULA],
                  checksum_address=address,
                  domain='lynx',
                  keyring=keyring)

        enrico_key = request.json['enrico_key']
        policy_key = request.json['policy_key']
        data_source = Enrico.from_public_keys(
            verifying_key=bytes.fromhex(enrico_key),
            policy_encrypting_key=UmbralPublicKey.from_bytes(
                bytes.fromhex(policy_key)))

        ciphertext = request.json['ciphertext']
        message_kit = UmbralMessageKit.from_bytes(bytes.fromhex(ciphertext))

        label = request.json['label']
        alice_pubkey = request.json['alice_pubkey']
        alice_pubkey_umbral = UmbralPublicKey.from_bytes(
            bytes.fromhex(alice_pubkey))

        print("Retrieving...")
        retrieved_plaintexts = bob.retrieve(
            message_kit,
            label=label.encode(),
            enrico=data_source,
            alice_verifying_key=alice_pubkey_umbral)
        print("Retrieved.")
        result = retrieved_plaintexts[0].decode("utf-8")
        self.readAndDeleteKeys(address, keyring)  #delete keys
        return result
Ejemplo n.º 8
0
async def onRequestBuy(event):
    SEEDNODE_URI = os.getenv("SEEDNODE_URI")
    ursula = Ursula.from_seed_and_stake_info(seed_uri="localhost:11500",
                                             federated_only=True,
                                             minimum_stake=0)

    NEW_PASSWORD = "******"

    try:
        keyring = NucypherKeyring.generate(
            checksum_address='0xf61DBAbF5Ac0A3F99e91b663A590cF4cB58563D9',
            password=NEW_PASSWORD,  # used to encrypt nucypher private keys
            keyring_root="//home/ghard/.local/share/nucypher/keyring")
    except:
        # Restore an existing Alice keyring
        keyring = NucypherKeyring(
            account='0xf61DBAbF5Ac0A3F99e91b663A590cF4cB58563D9')

    keyring.unlock(password=NEW_PASSWORD)

    alice = Alice(keyring=keyring,
                  known_nodes=[ursula],
                  federated_only=True,
                  learn_on_same_thread=True,
                  domain=TEMPORARY_DOMAIN)
    user = event.args["buyer"]
    keys = masterfile_contract.functions.userKeys(user).call()
    print(user)
    print(keys)

    bob = Bob.from_public_keys(verifying_key=keys[0],
                               encrypting_key=keys[1],
                               federated_only=True)

    policy = alice.grant(bob,
                         label=(str(event.args["tokenId"]) +
                                os.urandom(4).hex()).encode(),
                         m=2,
                         n=3,
                         expiration=maya.now() + timedelta(days=5))
    policy.treasure_map_publisher.block_until_complete()
    print("done")
Ejemplo n.º 9
0
 def post(self):
     keys = request.json['keys']
     password = request.json['password']
     address = request.json['address']
     alice_pubkey = request.json['alice_pubkey']
     label = request.json['label']
     path = self.writeKeys(keys)
     passwd = PBKDF2(password,
                     address.encode(),
                     20,
                     count=30000,
                     hmac_hash_module=SHA256).hex()
     keyring = NucypherKeyring(account=address, keyring_root="./keys")
     keyring.unlock(password=passwd)
     bob = Bob(known_nodes=[self.URSULA],
               checksum_address=address,
               domain='lynx',
               keyring=keyring)
     alice_pubkey_umbral = UmbralPublicKey.from_bytes(
         bytes.fromhex(alice_pubkey))
     bob.join_policy(label.encode(),
                     alice_verifying_key=alice_pubkey_umbral,
                     block=True)
     self.readAndDeleteKeys(address, keyring)  # delete keys
Ejemplo n.º 10
0
def accounts(config, action, checksum_address):
    """Manage local and hosted node accounts"""

    #
    # Initialize
    #
    config.get_node_configuration()
    if not config.federated_only:
        config.connect_to_blockchain()
        config.connect_to_contracts()

        if not checksum_address:
            checksum_address = config.blockchain.interface.w3.eth.coinbase
            click.echo(
                "WARNING: No checksum address specified - Using the node's default account."
            )

    def __collect_transfer_details(denomination: str):
        destination = click.prompt("Enter destination checksum_address")
        if not is_checksum_address(destination):
            click.secho("{} is not a valid checksum checksum_address".format(
                destination),
                        fg='red',
                        bold=True)
            raise click.Abort()
        amount = click.prompt(
            "Enter amount of {} to transfer".format(denomination),
            type=click.INT)
        return destination, amount

    #
    # Action Switch
    #
    if action == 'new':
        new_address = config.create_account()
        click.secho("Created new ETH address {}".format(new_address),
                    fg='blue')
        if click.confirm(
                "Set new address as the node's keying default account?".format(
                    new_address)):
            config.blockchain.interface.w3.eth.defaultAccount = new_address
            click.echo("{} is now the node's default account.".format(
                config.blockchain.interface.w3.eth.defaultAccount))

    if action == 'set-default':
        config.blockchain.interface.w3.eth.defaultAccount = checksum_address  # TODO: is there a better way to do this?
        click.echo("{} is now the node's default account.".format(
            config.blockchain.interface.w3.eth.defaultAccount))

    elif action == 'export':
        keyring = NucypherKeyring(account=checksum_address)
        click.confirm(
            "Export local private key for {} to node's keyring: {}?".format(
                checksum_address, config.provider_uri),
            abort=True)
        passphrase = click.prompt("Enter passphrase to decrypt account",
                                  type=click.STRING,
                                  hide_input=True,
                                  confirmation_prompt=True)
        keyring._export_wallet_to_node(blockchain=config.blockchain,
                                       passphrase=passphrase)

    elif action == 'list':
        if config.accounts == NO_BLOCKCHAIN_CONNECTION:
            click.echo('No account found.')
            raise click.Abort()

        for index, checksum_address in enumerate(config.accounts):
            token_balance = config.token_agent.get_balance(
                address=checksum_address)
            eth_balance = config.blockchain.interface.w3.eth.getBalance(
                checksum_address)
            base_row_template = ' {address}\n    Tokens: {tokens}\n    ETH: {eth}\n '
            row_template = (
                '\netherbase |' + base_row_template
            ) if not index else '{index} ....... |' + base_row_template
            row = row_template.format(index=index,
                                      address=checksum_address,
                                      tokens=token_balance,
                                      eth=eth_balance)
            click.secho(row, fg='blue')

    elif action == 'balance':
        if not checksum_address:
            checksum_address = config.blockchain.interface.w3.eth.etherbase
            click.echo(
                'No checksum_address supplied, Using the default {}'.format(
                    checksum_address))
        token_balance = config.token_agent.get_balance(
            address=checksum_address)
        eth_balance = config.token_agent.blockchain.interface.w3.eth.getBalance(
            checksum_address)
        click.secho("Balance of {} | Tokens: {} | ETH: {}".format(
            checksum_address, token_balance, eth_balance),
                    fg='blue')

    elif action == "transfer-tokens":
        destination, amount = __collect_transfer_details(denomination='tokens')
        click.confirm("Are you sure you want to send {} tokens to {}?".format(
            amount, destination),
                      abort=True)
        txhash = config.token_agent.transfer(amount=amount,
                                             target_address=destination,
                                             sender_address=checksum_address)
        config.blockchain.wait_for_receipt(txhash)
        click.echo("Sent {} tokens to {} | {}".format(amount, destination,
                                                      txhash))

    elif action == "transfer-eth":
        destination, amount = __collect_transfer_details(denomination='ETH')
        tx = {'to': destination, 'from': checksum_address, 'value': amount}
        click.confirm("Are you sure you want to send {} tokens to {}?".format(
            tx['value'], tx['to']),
                      abort=True)
        txhash = config.blockchain.interface.w3.eth.sendTransaction(tx)
        config.blockchain.wait_for_receipt(txhash)
        click.echo("Sent {} ETH to {} | {}".format(amount, destination,
                                                   str(txhash)))

    else:
        raise click.BadArgumentUsage
Ejemplo n.º 11
0
# "localhost:11500"
SEEDNODE_URI = os.getenv("SEEDNODE_URI")
ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URI,
                                         federated_only=True,
                                         minimum_stake=0)

NEW_PASSWORD = "******"

try:
    keyring = NucypherKeyring.generate(
        checksum_address='0xf61DBAbF5Ac0A3F99e91b663A590cF4cB58563D9',
        password=NEW_PASSWORD,  # used to encrypt nucypher private keys
        keyring_root="//home/ghard/.local/share/nucypher/keyring")
except:
    # Restore an existing Alice keyring
    keyring = NucypherKeyring(
        account='0xf61DBAbF5Ac0A3F99e91b663A590cF4cB58563D9')

keyring.unlock(password=NEW_PASSWORD)

alice = Alice(keyring=keyring,
              known_nodes=[ursula],
              federated_only=True,
              learn_on_same_thread=True,
              domain=TEMPORARY_DOMAIN)

alice_sig_pubkey = alice.stamp

size = 128, 128

formats = {"JPEG": ".jpg", "PNG": ".png", "GIF": ".gif"}
formatsReversed = {".jpg": "JPEG", ".png": "PNG", ".gif": "GIF"}
Ejemplo n.º 12
0
def test_keyring_restoration(tmpdir):
    keyring = _generate_keyring(tmpdir)
    keyring.unlock(password=INSECURE_DEVELOPMENT_PASSWORD)

    account = keyring.account
    checksum_address = keyring.checksum_address
    certificate_filepath = keyring.certificate_filepath
    encrypting_public_key_hex = keyring.encrypting_public_key.hex()
    signing_public_key_hex = keyring.signing_public_key.hex()

    # tls power
    tls_hosting_power = keyring.derive_crypto_power(
        power_class=TLSHostingPower, host=LOOPBACK_ADDRESS)
    tls_hosting_power_public_key_numbers = tls_hosting_power.public_key(
    ).public_numbers()
    tls_hosting_power_certificate_public_bytes = \
        tls_hosting_power.keypair.certificate.public_bytes(encoding=Encoding.PEM)
    tls_hosting_power_certificate_filepath = tls_hosting_power.keypair.certificate_filepath

    # decrypting power
    decrypting_power = keyring.derive_crypto_power(power_class=DecryptingPower)
    decrypting_power_public_key_hex = decrypting_power.public_key().hex()
    decrypting_power_fingerprint = decrypting_power.keypair.fingerprint()

    # signing power
    signing_power = keyring.derive_crypto_power(power_class=SigningPower)
    signing_power_public_key_hex = signing_power.public_key().hex()
    signing_power_fingerprint = signing_power.keypair.fingerprint()

    # get rid of object, but not persistent data
    del keyring

    restored_keyring = NucypherKeyring(keyring_root=tmpdir, account=account)
    restored_keyring.unlock(password=INSECURE_DEVELOPMENT_PASSWORD)

    assert restored_keyring.account == account
    assert restored_keyring.checksum_address == checksum_address
    assert restored_keyring.certificate_filepath == certificate_filepath
    assert restored_keyring.encrypting_public_key.hex(
    ) == encrypting_public_key_hex
    assert restored_keyring.signing_public_key.hex() == signing_public_key_hex

    # tls power
    restored_tls_hosting_power = restored_keyring.derive_crypto_power(
        power_class=TLSHostingPower, host=LOOPBACK_ADDRESS)
    assert restored_tls_hosting_power.public_key().public_numbers(
    ) == tls_hosting_power_public_key_numbers
    assert restored_tls_hosting_power.keypair.certificate.public_bytes(encoding=Encoding.PEM) == \
           tls_hosting_power_certificate_public_bytes
    assert restored_tls_hosting_power.keypair.certificate_filepath == tls_hosting_power_certificate_filepath

    # decrypting power
    restored_decrypting_power = restored_keyring.derive_crypto_power(
        power_class=DecryptingPower)
    assert restored_decrypting_power.public_key().hex(
    ) == decrypting_power_public_key_hex
    assert restored_decrypting_power.keypair.fingerprint(
    ) == decrypting_power_fingerprint

    # signing power
    restored_signing_power = restored_keyring.derive_crypto_power(
        power_class=SigningPower)
    assert restored_signing_power.public_key().hex(
    ) == signing_power_public_key_hex
    assert restored_signing_power.keypair.fingerprint(
    ) == signing_power_fingerprint