Пример #1
0
def test_validate_passphrase():
    # Passphrase too short
    passphrase = 'x' * 5
    with pytest.raises(ValueError):
        _keyring = NucypherKeyring.generate(passphrase=passphrase)

    # Empty passphrase is provided
    with pytest.raises(ValueError):
        _keyring = NucypherKeyring.generate(passphrase="")
Пример #2
0
def test_validate_password():
    # Password too short
    password = '******' * 5
    with pytest.raises(ValueError):
        _keyring = NucypherKeyring.generate(password=password)

    # Empty password is provided
    with pytest.raises(ValueError):
        _keyring = NucypherKeyring.generate(password="")
Пример #3
0
    def write_keyring(
        self,
        passphrase: str,
        encrypting: bool,
        wallet: bool,
        tls: bool,
        host: str,
        tls_curve,
    ) -> NucypherKeyring:

        self.keyring = NucypherKeyring.generate(passphrase=passphrase,
                                                encrypting=encrypting,
                                                wallet=wallet,
                                                tls=tls,
                                                host=host,
                                                curve=tls_curve,
                                                keyring_root=self.keyring_dir)

        # TODO: Operating mode switch
        if self.federated_only or not wallet:
            self.checksum_address = self.keyring.federated_address
        else:
            self.checksum_address = self.keyring.checksum_address
        if tls:
            self.certificate_filepath = self.keyring.certificate_filepath

        return self.keyring
Пример #4
0
    def write_keyring(self, password: str, checksum_address: str = None, **generation_kwargs) -> NucypherKeyring:

        if self.federated_only:
            checksum_address = FEDERATED_ADDRESS

        elif not checksum_address:

            # Note: It is assumed the blockchain interface is not yet connected.
            if self.provider_process:

                # Generate Geth's "datadir"
                if not os.path.exists(self.provider_process.data_dir):
                    os.mkdir(self.provider_process.data_dir)

                # Get or create wallet address
                if not self.checksum_address:
                    self.checksum_address = self.provider_process.ensure_account_exists(password=password)
                elif self.checksum_address not in self.provider_process.accounts():
                    raise self.ConfigurationError(f'Unknown Account {self.checksum_address}')

            elif not self.checksum_address:
                raise self.ConfigurationError(f'No checksum address provided for decentralized configuration.')

            checksum_address = self.checksum_address

        self.keyring = NucypherKeyring.generate(password=password,
                                                keyring_root=self.keyring_root,
                                                checksum_address=checksum_address,
                                                **generation_kwargs)

        if self.federated_only:
            self.checksum_address = self.keyring.checksum_address

        return self.keyring
Пример #5
0
    def write_keyring(self,
                      password: str,
                      checksum_address: str = None,
                      **generation_kwargs) -> NucypherKeyring:

        # Configure checksum address
        checksum_address = checksum_address or self.checksum_address
        if self.federated_only:
            checksum_address = FEDERATED_ADDRESS
        elif not checksum_address:
            raise self.ConfigurationError(
                f'No checksum address provided for decentralized configuration.'
            )

        # Generate new keys
        self.keyring = NucypherKeyring.generate(
            password=password,
            keyring_root=self.keyring_root,
            checksum_address=checksum_address,
            **generation_kwargs)

        # In the case of a federated keyring generation,
        # the generated federated address must be set here.
        if self.federated_only:
            self.checksum_address = self.keyring.checksum_address

        return self.keyring
Пример #6
0
    def create_account(self, passphrase: str = None) -> str:
        """Creates a new local or hosted ethereum wallet"""
        choice = click.prompt("Create a new Hosted or Local account?",
                              default='hosted',
                              type=click.STRING).strip().lower()
        if choice not in ('hosted', 'local'):
            click.echo("Invalid Input")
            raise click.Abort()

        if not passphrase:
            message = "Enter a passphrase to encrypt your wallet's private key"
            passphrase = click.prompt(message,
                                      hide_input=True,
                                      confirmation_prompt=True)

        if choice == 'local':
            keyring = NucypherKeyring.generate(
                passphrase=passphrase,
                keyring_root=self.node_configuration.keyring_dir,
                encrypting=False,
                wallet=True)
            new_address = keyring.checksum_address
        elif choice == 'hosted':
            new_address = self.blockchain.interface.w3.personal.newAccount(
                passphrase)
        else:
            raise click.BadParameter(
                "Invalid choice; Options are hosted or local.")
        return new_address
Пример #7
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
Пример #8
0
    def write_keyring(self, password: str, **generation_kwargs) -> NucypherKeyring:

        self.keyring = NucypherKeyring.generate(password=password,
                                                keyring_root=self.keyring_dir,
                                                **generation_kwargs)
        # Operating mode switch TODO: #466
        if self.federated_only:
            self.checksum_public_address = self.keyring.federated_address
        else:
            self.checksum_public_address = self.keyring.checksum_address

        return self.keyring
Пример #9
0
def _generate_keyring(root,
                      checksum_address=FEDERATED_ADDRESS,
                      password=INSECURE_DEVELOPMENT_PASSWORD,
                      encrypting=True,
                      rest=True,
                      host=LOOPBACK_ADDRESS):
    keyring = NucypherKeyring.generate(checksum_address=checksum_address,
                                       password=password,
                                       encrypting=encrypting,
                                       rest=rest,
                                       host=host,
                                       keyring_root=root)
    return keyring
Пример #10
0
def test_tls_hosting_certificate_remains_the_same(tmpdir, mocker):
    keyring = NucypherKeyring.generate(checksum_address=FEDERATED_ADDRESS,
                                       password=INSECURE_DEVELOPMENT_PASSWORD,
                                       encrypting=True,
                                       rest=True,
                                       host=LOOPBACK_ADDRESS,
                                       keyring_root=tmpdir)
    keyring.unlock(password=INSECURE_DEVELOPMENT_PASSWORD)

    rest_port = 12345
    db_filepath = tempfile.mkdtemp()

    ursula = Ursula(federated_only=True,
                    start_learning_now=False,
                    keyring=keyring,
                    rest_host=LOOPBACK_ADDRESS,
                    rest_port=rest_port,
                    db_filepath=db_filepath,
                    domain=TEMPORARY_DOMAIN)

    assert ursula.keyring is keyring
    assert ursula.certificate == ursula._crypto_power.power_ups(
        TLSHostingPower).keypair.certificate

    original_certificate_bytes = ursula.certificate.public_bytes(
        encoding=Encoding.PEM)
    ursula.disenchant()
    del ursula

    spy_rest_server_init = mocker.spy(ProxyRESTServer, '__init__')
    recreated_ursula = Ursula(federated_only=True,
                              start_learning_now=False,
                              keyring=keyring,
                              rest_host=LOOPBACK_ADDRESS,
                              rest_port=rest_port,
                              db_filepath=db_filepath,
                              domain=TEMPORARY_DOMAIN)

    assert recreated_ursula.keyring is keyring
    assert recreated_ursula.certificate.public_bytes(
        encoding=Encoding.PEM) == original_certificate_bytes
    tls_hosting_power = recreated_ursula._crypto_power.power_ups(
        TLSHostingPower)
    spy_rest_server_init.assert_called_once_with(
        ANY,  # self
        rest_host=LOOPBACK_ADDRESS,
        rest_port=rest_port,
        rest_app=IsType(Flask),
        datastore=IsType(Datastore),
        hosting_power=tls_hosting_power)
    recreated_ursula.disenchant()
Пример #11
0
def test_characters_use_keyring(tmpdir):
    keyring = NucypherKeyring.generate(checksum_address=FEDERATED_ADDRESS,
                                       password=INSECURE_DEVELOPMENT_PASSWORD,
                                       encrypting=True,
                                       rest=False,
                                       keyring_root=tmpdir)
    keyring.unlock(password=INSECURE_DEVELOPMENT_PASSWORD)
    Alice(federated_only=True, start_learning_now=False, keyring=keyring)
    Bob(federated_only=True, start_learning_now=False, keyring=keyring)
    Ursula(federated_only=True,
           start_learning_now=False,
           keyring=keyring,
           rest_host='127.0.0.1',
           rest_port=12345)
Пример #12
0
 def post(self):
     password = request.json['password']
     address = request.json['address']
     passwd = PBKDF2(password,
                     address.encode(),
                     20,
                     count=30000,
                     hmac_hash_module=SHA256).hex()
     keyring = NucypherKeyring.generate(checksum_address=address,
                                        password=passwd,
                                        keyring_root="./keys")
     keyring.unlock(password=passwd)
     keyring.lock()
     json = self.readAndDeleteKeys(address, keyring)
     return json
Пример #13
0
    def write_keyring(self, password: str, wallet: bool = True, **generation_kwargs) -> NucypherKeyring:

        checksum_address = None

        #
        # Decentralized
        #
        if wallet:

            # Note: It is assumed the blockchain is not yet available.
            if not self.federated_only and not self.checksum_address:

                # "Casual Geth"
                if self.provider_process:

                    if not os.path.exists(self.provider_process.data_dir):
                        os.mkdir(self.provider_process.data_dir)

                    # Get or create wallet address (geth etherbase)
                    checksum_address = self.provider_process.ensure_account_exists(password=password)

                # "Formal Geth" - Manual Web3 Provider, We assume is already running and available
                else:
                    self.connect_to_blockchain()
                    if not self.blockchain.interface.client.accounts:
                        raise self.ConfigurationError(f'Web3 provider "{self.provider_uri}" does not have any accounts')
                    checksum_address = self.blockchain.interface.client.etherbase

                # Addresses read from some node keyrings (clients) are *not* returned in checksum format.
                checksum_address = to_checksum_address(checksum_address)

            # Use explicit address
            elif self.checksum_address:
                checksum_address = self.checksum_address

        self.keyring = NucypherKeyring.generate(password=password,
                                                keyring_root=self.keyring_dir,
                                                checksum_address=checksum_address,
                                                **generation_kwargs)
        # Operating mode switch
        if self.federated_only or not wallet:
            self.checksum_address = self.keyring.federated_address
        else:
            self.checksum_address = self.keyring.account

        return self.keyring
def test_characters_use_keyring(tmpdir):
    keyring = NucypherKeyring.generate(checksum_address=FEDERATED_ADDRESS,
                                       password=INSECURE_DEVELOPMENT_PASSWORD,
                                       encrypting=True,
                                       rest=False,
                                       keyring_root=tmpdir)
    keyring.unlock(password=INSECURE_DEVELOPMENT_PASSWORD)
    a = Alice(federated_only=True, start_learning_now=False, keyring=keyring)
    Bob(federated_only=True, start_learning_now=False, keyring=keyring)
    Ursula(federated_only=True,
           start_learning_now=False,
           keyring=keyring,
           rest_host='127.0.0.1',
           rest_port=12345,
           db_filepath=tempfile.mkdtemp())
    a.disenchant(
    )  # To stop Alice's publication threadpool.  TODO: Maybe only start it at first enactment?
Пример #15
0
    def write_keyring(self, password: str, **generation_kwargs) -> NucypherKeyring:

        if not self.federated_only and not self.checksum_public_address:
            checksum_address = self.blockchain.interface.w3.eth.accounts[0]  # etherbase
        else:
            checksum_address = self.checksum_public_address

        self.keyring = NucypherKeyring.generate(password=password,
                                                keyring_root=self.keyring_dir,
                                                checksum_address=checksum_address,
                                                **generation_kwargs)
        # Operating mode switch TODO: #466
        if self.federated_only:
            self.checksum_public_address = self.keyring.federated_address
        else:
            self.checksum_public_address = self.keyring.account

        return self.keyring
Пример #16
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")
Пример #17
0
    def write_keyring(self, password: str,
                      **generation_kwargs) -> NucypherKeyring:

        # Note: It is assumed the blockchain is not yet available.
        if not self.federated_only:

            if self.provider_process:

                # Generate Geth's "datadir"
                if not os.path.exists(self.provider_process.data_dir):
                    os.mkdir(self.provider_process.data_dir)

                # Get or create wallet address
                if not self.checksum_address:
                    self.checksum_address = self.provider_process.ensure_account_exists(
                        password=password)
                elif self.checksum_address not in self.provider_process.accounts(
                ):
                    raise self.ConfigurationError(
                        f'Unknown Account {self.checksum_address}')

            # Determine etherbase (web3)
            elif not self.checksum_address:
                self.connect_to_blockchain()
                if not self.blockchain.client.accounts:
                    raise self.ConfigurationError(
                        f'Web3 provider "{self.provider_uri}" does not have any accounts'
                    )
                self.checksum_address = self.blockchain.client.etherbase

        self.keyring = NucypherKeyring.generate(
            password=password,
            keyring_root=self.keyring_root,
            checksum_address=self.checksum_address,
            federated=self.federated_only,
            **generation_kwargs)

        self.checksum_address = self.keyring.account
        return self.keyring
def test_generate_alice_keyring(tmpdir):

    keyring = NucypherKeyring.generate(
        checksum_address=FEDERATED_ADDRESS,
        password=INSECURE_DEVELOPMENT_PASSWORD,
        encrypting=True,
        rest=False,
        keyring_root=tmpdir
    )

    enc_pubkey = keyring.encrypting_public_key
    assert enc_pubkey is not None

    with pytest.raises(NucypherKeyring.KeyringLocked):
        _dec_keypair = keyring.derive_crypto_power(DecryptingPower).keypair

    keyring.unlock(password=INSECURE_DEVELOPMENT_PASSWORD)
    dec_keypair = keyring.derive_crypto_power(DecryptingPower).keypair

    assert enc_pubkey == dec_keypair.pubkey

    label = b'test'

    delegating_power = keyring.derive_crypto_power(DelegatingPower)
    delegating_pubkey = delegating_power.get_pubkey_from_label(label)

    bob_pubkey = SecretKey.random().public_key()
    signer = Signer(SecretKey.random())
    delegating_pubkey_again, _kfrags = delegating_power.generate_kfrags(
        bob_pubkey, signer, label, m=2, n=3
    )

    assert delegating_pubkey == delegating_pubkey_again

    another_delegating_power = keyring.derive_crypto_power(DelegatingPower)
    another_delegating_pubkey = another_delegating_power.get_pubkey_from_label(label)

    assert delegating_pubkey == another_delegating_pubkey
Пример #19
0
def test_generate_alice_keyring(tmpdir):
    password = '******' * 16

    keyring = NucypherKeyring.generate(password=password,
                                       encrypting=True,
                                       wallet=False,
                                       rest=False,
                                       keyring_root=tmpdir)

    enc_pubkey = keyring.encrypting_public_key
    assert enc_pubkey is not None

    with pytest.raises(NucypherKeyring.KeyringLocked):
        _dec_keypair = keyring.derive_crypto_power(DecryptingPower).keypair

    keyring.unlock(password)
    dec_keypair = keyring.derive_crypto_power(DecryptingPower).keypair

    assert enc_pubkey == dec_keypair.pubkey

    label = b'test'

    delegating_power = keyring.derive_crypto_power(DelegatingPower)
    delegating_pubkey = delegating_power.get_pubkey_from_label(label)

    bob_pubkey = UmbralPrivateKey.gen_key().get_pubkey()
    signer = Signer(UmbralPrivateKey.gen_key())
    delegating_pubkey_again, _kfrags = delegating_power.generate_kfrags(
        bob_pubkey, signer, label, m=2, n=3)

    assert delegating_pubkey == delegating_pubkey_again

    another_delegating_power = keyring.derive_crypto_power(DelegatingPower)
    another_delegating_pubkey = another_delegating_power.get_pubkey_from_label(
        label)

    assert delegating_pubkey == another_delegating_pubkey
Пример #20
0
from nucypher.crypto.kits import UmbralMessageKit

SESSION_ID = os.getenv("SESSION_ID")
BUCKET_ID = os.getenv("BUCKET_ID")

# "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