def retire_ggo(self, url):
        key_ggo = self.master_key.ChildKey(4)
        key_mea = self.master_key.ChildKey(10)

        signer_mea = self.crypto.new_signer(
            PrivateKey.from_bytes(key_mea.PrivateKey()))
        signer_ggo = self.crypto.new_signer(
            PrivateKey.from_bytes(key_ggo.PrivateKey()))

        mea_add = generate_address(AddressPrefix.MEASUREMENT,
                                   key_mea.PublicKey())
        set_add = generate_address(AddressPrefix.SETTLEMENT,
                                   key_mea.PublicKey())
        ggo_add = generate_address(AddressPrefix.GGO, key_ggo.PublicKey())

        retire_request = RetireGGORequest(origin=ggo_add,
                                          settlement_address=set_add)

        retire_response = self.send_request(url, retire_request,
                                            [mea_add, set_add, ggo_add],
                                            signer_ggo)

        self.wait_for_commit(retire_response.json()['link'])

        request = SettlementRequest(settlement_address=set_add,
                                    measurement_address=mea_add,
                                    ggo_addresses=[ggo_add])

        return self.send_request(url, request, [mea_add, set_add, ggo_add],
                                 signer_mea)
Esempio n. 2
0
def _read_signer(key_filename):
    """Reads the given file as a hex, or (as a fallback) a WIF formatted key.

    Args:
        key_filename: The filename where the key is stored. If None,
            defaults to the default key for the current user.

    Returns:
        Signer: the signer

    Raises:
        CliException: If unable to read the file.
    """
    filename = key_filename
    if filename is None:
        filename = os.path.join(config.get_key_dir(), 'validator.priv')

    try:
        with open(filename, 'r') as key_file:
            signing_key = key_file.read().strip()
    except IOError as e:
        raise CliException('Unable to read key file: {}'.format(str(e)))

    try:
        private_key = Secp256k1PrivateKey.from_hex(signing_key)
    except ParseError:
        try:
            private_key = Secp256k1PrivateKey.from_wif(signing_key)
        except ParseError:
            raise CliException('Unable to read key in file: {}'.format(str(e)))

    context = create_context('secp256k1')
    crypto_factory = CryptoFactory(context)
    return crypto_factory.new_signer(private_key)
    def __init__(self, base_url, keyfile, wait=None):
        """
        Member variables:
            _base_url
            _private_key
            _public_key
            _transaction_family
            _family_version
            _wait
        """
        self._base_url = base_url

        try:
            with open(keyfile) as fd:
                private_key_str = fd.read().strip()
        except OSError as err:
            raise IOError("Failed to read keys: {}.".format(str(err)))

        try:
            private_key = Secp256k1PrivateKey.from_hex(private_key_str)
        except ParseError:
            try:
                private_key = Secp256k1PrivateKey.from_wif(private_key_str)
            except ParseError as e:
                raise BattleshipException(
                    'Unable to load private key: {}'.format(str(e)))

        self._signer = CryptoFactory(
            create_context('secp256k1')).new_signer(private_key)

        self._transaction_family = "battleship"
        self._family_version = "1.0"
        self._wait = wait
Esempio n. 4
0
    def __init__(self, base_url, keyfile=None):

        self._base_url = base_url

        if keyfile is None:
            self._signer = None
            return

        try:
            with open(keyfile) as fd:
                private_key_str = fd.read().strip()
        except OSError as err:
            raise XoException('Failed to read private key {}: {}'.format(
                keyfile, str(err)))

        try:
            private_key = Secp256k1PrivateKey.from_hex(private_key_str)
        except ParseError:
            try:
                private_key = Secp256k1PrivateKey.from_wif(private_key_str)
            except ParseError as e:
                raise XoException('Unable to load private key: {}'.format(
                    str(e)))

        self._signer = CryptoFactory(create_context('secp256k1')) \
            .new_signer(private_key)
    def test_wif_key(self):
        priv_key1 = Secp256k1PrivateKey.from_wif(KEY1_PRIV_WIF)
        self.assertEqual(priv_key1.get_algorithm_name(), "secp256k1")
        self.assertEqual(priv_key1.as_hex(), KEY1_PRIV_HEX)

        priv_key2 = Secp256k1PrivateKey.from_wif(KEY2_PRIV_WIF)
        self.assertEqual(priv_key2.get_algorithm_name(), "secp256k1")
        self.assertEqual(priv_key2.as_hex(), KEY2_PRIV_HEX)
 def test_private_key_sawtooth_random(self):
     """Generates two private keys using Sawtooth Signing's
     Secp256k1PrivateKey class, and make sure they don't match;
     and thus are hopefully random and non-deterministic"""
     key1 = Secp256k1PrivateKey.new_random()
     key2 = Secp256k1PrivateKey.new_random()
     self.assertNotEqual(key1.as_hex(), key2.as_hex())
     self.assertNotEqual(key1.as_bytes(), key2.as_bytes())
    def test_check_invalid_digit(self):
        priv_chars = list(KEY1_PRIV_HEX)
        priv_chars[3] = 'i'
        with self.assertRaises(ParseError):
            Secp256k1PrivateKey.from_hex(''.join(priv_chars))

        pub_chars = list(KEY1_PUB_HEX)
        pub_chars[3] = 'i'
        with self.assertRaises(ParseError):
            Secp256k1PublicKey.from_hex(''.join(pub_chars))
Esempio n. 8
0
 def assertIsPrivateKeyBytes(self, key):
     """Sanity checks a private key in bytes"""
     self.assertIsInstance(key, bytes)
     self.assertEqual(len(key), PRIVATE_KEY_LENGTH)
     key = Secp256k1PrivateKey.from_hex(str(binascii.hexlify(key), "ascii"))
     self.assertIsPrivateKeySecp256k1(key)
     return key
Esempio n. 9
0
 def assertIsPrivateKeyHex(self, key):
     """Sanity checks a hexidecimal string private key"""
     self.assertIsInstance(key, str)
     self.assertTrue(PRIVATE_KEY_PATTERN.match(key))
     key = Secp256k1PrivateKey.from_hex(key)
     self.assertIsPrivateKeySecp256k1(key)
     return key
Esempio n. 10
0
 def __init__(self, private_key):
     self._baseUrl = "http://localhost:8008"
     privateKey = Secp256k1PrivateKey.from_hex(private_key)
     self._signer = CryptoFactory(create_context('secp256k1')) \
         .new_signer(privateKey)
     self._publicKey = self._signer.get_public_key().as_hex()
     self._address = get_wallet_address(self._publicKey)
Esempio n. 11
0
    def __init__(self, base_url, key_file=None):
        '''Initialize the client class.
        '''
        self._base_url = base_url

        if key_file is None:
            self._signer = None
            return

        try:
            with open(key_file) as key_fd:
                private_key_str = key_fd.read().strip()
        except OSError as err:
            raise Exception('Failed to read private key {}: {}'.format(
                key_file, str(err)))

        try:
            private_key = Secp256k1PrivateKey.from_hex(private_key_str)
        except ParseError as err:
            raise Exception( \
                'Failed to load private key: {}'.format(str(err)))

        self._signer = CryptoFactory(create_context('secp256k1')) \
            .new_signer(private_key)
        self._public_key = self._signer.get_public_key().as_hex()
Esempio n. 12
0
    def __init__(self, baseUrl, keyFile=None):
        '''Initialize the client class.

           This is mainly getting the key pair and computing the address.
        '''

        self._baseUrl = baseUrl

        if keyFile is None:
            self._signer = None
            return

        try:
            with open(keyFile) as fd:
                privateKeyStr = fd.read().strip()
        except OSError as err:
            raise Exception('Failed to read private key {}: {}'.format(
                keyFile, str(err)))

        try:
            privateKey = Secp256k1PrivateKey.from_hex(privateKeyStr)
        except ParseError as err:
            raise Exception('Failed to load private key: {}'.format(str(err)))

        self._signer = CryptoFactory(create_context('secp256k1')) \
            .new_signer(privateKey)

        self._publicKey = self._signer.get_public_key().as_hex()

#Erzeugung der Adresse einer Wallet. Erste 6 Zeichen, Family name. Der Rest Public Key des Eigentümers.
        self._address = _hash(FAMILY_NAME.encode('utf-8'))[0:6] + \
            _hash(self._publicKey.encode('utf-8'))[0:64]
Esempio n. 13
0
def close_asset(name):
    """Create an CloseOffer txn and wrap it in a Batch and list.
    Args:
        name (str): The identifier of the Offer.
    Returns:
        tuple: List of Batch, signature tuple
    """
    global context
    global signer

    batcher_private_key = Secp256k1PrivateKey.from_hex(BATCHER_PRIVATE_KEY)
    batcher_signer = CryptoFactory(context).new_signer(batcher_private_key)

    public_key = signer.get_public_key().as_hex()

    inputs = [addresshandler.make_asset_address(asset_id=name)]

    outputs = [addresshandler.make_asset_address(asset_id=name)]

    close_txn = payload_pb2.CloseAsset(
        name=name)

    payload = payload_pb2.TransactionPayload(
        payload_type=payload_pb2.TransactionPayload.CLOSE_ASSET,
        close_asset=close_txn)

    return make_header_and_batch(
        payload=payload,
        inputs=inputs,
        outputs=outputs,
        txn_key=signer,
        batch_key=batcher_signer)
Esempio n. 14
0
async def master_mnemonic(app):
    """
    This will check if the zeroth key generated from the ADMIN mnemonic is valid or Invalid
    If it is invalid, it will stop the application

    """
    master_pub, master_priv, zero_pub, zero_priv = await from_mnemonic(
        app.config.GOAPI_URL, app.config.ADMIN_MNEMONIC)
    if zero_pub != app.config.ADMIN_ZERO_PUB:
        logging.error("Wrong mnemonic provided")
        sys.exit(1)
    else:
        logging.info("ADMIN ZERO_PUB matched")

    app.config.BATCHER_PRIVATE_KEY = zero_priv
    app.config.ADMIN_ZERO_PRIV = zero_priv
    app.config.ADMIN_MSTR_PUB = master_pub
    app.config.ADMIN_MSTR_PRIV = master_priv

    try:
        private_key = Secp256k1PrivateKey.from_hex(
            app.config.BATCHER_PRIVATE_KEY)
        app.config.CONTEXT = create_context('secp256k1')
        app.config.SIGNER = CryptoFactory(
            app.config.CONTEXT).new_signer(private_key)
        logging.info(
            "app.config.CONTEXT and app.config.SIGNER has been set up")
    except Exception as e:
        logging.error(f"from {__file__} error occurred {e}")
        sys.exit(1)
    return
    def setUpClass(cls):
        super().setUpClass()
        context = create_context('secp256k1')
        private_key = Secp256k1PrivateKey.from_hex(PRIVATE)
        signer = CryptoFactory(context).new_signer(private_key)

        cls.factory = ValidatorRegistryMessageFactory(signer=signer)
Esempio n. 16
0
    def init_bc(self, family_name=None):
        if self._family_name:
            return
        self._family_name = family_name
        self._base_url = config.get('blockchain_client_url') or os.environ.get(
            'BLOCKCHAIN_CLIENT_URL', 'http://localhost:8008')
        if not self._signer:
            key_file = config.get('sawtooth_key') or os.environ.get(
                'SAWTOOTH_KEY', 'sawtooth-key.priv')
            if key_file is None:
                self._signer = None
                return
        try:
            with open(key_file) as key_fd:
                private_key_str = key_fd.read().strip()
        except OSError as err:
            raise UserError(
                _('Failed to read private key {}: {}'.format(
                    key_file, str(err))))

        try:
            private_key = Secp256k1PrivateKey.from_hex(private_key_str)
        except ParseError as err:
            raise UserError(
                _('Failed to load private key: {}'.format(str(err))))

        self._signer = CryptoFactory(create_context('secp256k1')) \
            .new_signer(private_key)
        self._public_key = self._signer.get_public_key().as_hex()

        self._address = _hash(self._family_name.encode('utf-8'))[0:6] + \
                        _hash(self._public_key.encode('utf-8'))[0:64]
Esempio n. 17
0
def _read_signer(key_filename):
    """Reads the given file as a hex key.

    Args:
        key_filename: The filename where the key is stored. If None,
            defaults to the default key for the current user.

    Returns:
        Signer: the signer

    Raises:
        CliException: If unable to read the file.
    """
    filename = key_filename
    if filename is None:
        filename = os.path.join(os.path.expanduser('~'), '.sawtooth', 'keys',
                                getpass.getuser() + '.priv')

    try:
        with open(filename, 'r') as key_file:
            signing_key = key_file.read().strip()
    except IOError as e:
        raise CliException('Unable to read key file: {}'.format(str(e))) from e

    try:
        private_key = Secp256k1PrivateKey.from_hex(signing_key)
    except ParseError as e:
        raise CliException('Unable to read key in file: {}'.format(
            str(e))) from e

    context = create_context('secp256k1')
    crypto_factory = CryptoFactory(context)
    return crypto_factory.new_signer(private_key)
Esempio n. 18
0
    def __init__(self, base_url, keyfile=None):

        self._base_url = base_url

        if keyfile is None:
            self._signer = None
            return

        try:
            with open(keyfile) as fd:
                private_key_str = fd.read().strip()
        except OSError as err:
            raise XoException(
                'Failed to read private key {}: {}'.format(
                    keyfile, str(err)))

        try:
            private_key = Secp256k1PrivateKey.from_hex(private_key_str)
        except ParseError as e:
            raise XoException(
                'Unable to load private key: {}'.format(str(e)))

        self._signer = CryptoFactory(create_context('secp256k1')) \
            .new_signer(private_key)

        self._publicKey = self._signer.get_public_key().as_hex()

        self._address_file = _hash(FAMILY_NAME.encode('utf-8'))[0:6] + \
                        _hash(self._publicKey.encode('utf-8'))[0:64]
Esempio n. 19
0
    def __init__(self, base_url, keyfile, wait=None):
        """
        Member variables:
            _base_url
            _private_key
            _public_key
            _transaction_family
            _family_version
            _wait
        """
        self._base_url = base_url

        try:
            with open(keyfile) as fd:
                private_key_str = fd.read().strip()
        except OSError as err:
            raise IOError("Failed to read keys: {}.".format(str(err)))

        try:
            private_key = Secp256k1PrivateKey.from_hex(private_key_str)
        except ParseError as e:
            raise BattleshipException(
                'Unable to load private key: {}'.format(str(e)))

        self._signer = CryptoFactory(
            create_context('secp256k1')).new_signer(private_key)

        self._transaction_family = "battleship"
        self._family_version = "1.0"
        self._wait = wait
 def __init__(self, base_url, private_key):
     self._base_url = base_url
     private_key = Secp256k1PrivateKey.from_hex(private_key)
     self._signer = CryptoFactory(create_context('secp256k1')) \
         .new_signer(private_key)
     self._public_key = self._signer.get_public_key().as_hex()
     self._address = generate_address(self._public_key)
Esempio n. 21
0
    def __init__(self, base_url, keyfile=None):
        """
        Set the URL, handles the Private Key and Set the Signer
        """

        self._base_url = base_url  # Set the URL

        if keyfile is None:  # Check if there is no Signer
            self._signer = None  # Set the Signer to None
            return

        try:  # Open the private key from a file
            with open(keyfile) as fd:
                private_key_str = fd.read().strip(
                )  # Read the Private Key as a String
        except OSError as err:
            raise CertException('Failed to read private key {}: {}'.format(
                keyfile, str(err)))

        try:  # Convert the Private Key from String to Object
            private_key = Secp256k1PrivateKey.from_hex(private_key_str)
        except ParseError as e:
            raise CertException('Unable to load private key: {}'.format(
                str(e)))

        self._signer = CryptoFactory(create_context('secp256k1')) \
            .new_signer(private_key)  # Set the signer using the Private Key
    def _validate_user(self, restrict=False):
        # validate user incase of update

        self.key_file = self._get_key_file()
        pub_key_file = self._get_pub_key_file()
        if os.path.isfile(pub_key_file):
            try:
                with open(pub_key_file) as fd:
                        self.pub_key_str = fd.read().strip()
            except OSError:
                    raise Exception(
                        'Failed to read public key {key} of user {user}'.format(key=pub_key_file, user=self.user)
                    )
        else:
            raise Exception('Unable to find public kye {key} of user {user}'.format(key=pub_key_file, user=self.user))

        username, tag, priv_key = self._get_user_from_block_chain()
        private_key = Secp256k1PrivateKey.from_hex(priv_key)
        public_key = Secp256k1PublicKey(private_key.secp256k1_private_key.pubkey)

        if self.pub_key_str == public_key.as_hex():
            import pdb;pdb.set_trace()
            if restrict and tag != 'admin':
                raise Exception('Only Admin type users are allowed to perform these operations')
            print('Validation successful')
            return

        raise Exception(
            'Should have correct public keyfile {file} to create user'.format(file=pub_key_file))
Esempio n. 23
0
    def __init__(self, delegate, args):
        super(IntKeyWorkload, self).__init__(delegate, args)
        self._auth_info = args.auth_info
        self._urls = []
        self._pending_batches = {}
        self._lock = threading.Lock()
        self._delegate = delegate
        self._deps = {}
        context = create_context('secp256k1')
        crypto_factory = CryptoFactory(context=context)
        if args.key_file is not None:
            try:
                with open(args.key_file, 'r') as infile:
                    signing_key = infile.read().strip()
                private_key = Secp256k1PrivateKey.from_hex(signing_key)

                self._signer = crypto_factory.new_signer(
                    private_key=private_key)
            except ParseError as pe:
                raise IntKeyCliException(str(pe))
            except IOError as ioe:
                raise IntKeyCliException(str(ioe))
        else:
            self._signer = crypto_factory.new_signer(
                context.new_random_private_key())
Esempio n. 24
0
    def __init__(self, base_url, keyfile=None):

        # Checks to see if keyfile is provided
        if keyfile is None:
            self._signer = None
            return

        # Base url of http address
        self._base_url = base_url

        # Open keyfile to read private key
        try:
            with open(keyfile) as fd:
                private_key_str = fd.read().strip()
        except OSError as err:
            raise IdentityException(
                'Failed to read private key {}: {}'.format(
                    keyfile, str(err)))
            return

        # Load the private key to create signer
        try:
            private_key = Secp256k1PrivateKey.from_hex(private_key_str)
        except ParseError as e:
            raise IdentityException(
                'Unable to load private key: {}'.format(str(e)))
            return
        else:
            # Creating signer with the provided private key
            self._signer = CryptoFactory(create_context('secp256k1')) \
                .new_signer(private_key)
Esempio n. 25
0
    def __init__(self, conf: DistributedManagerConfig):
        self.conf = conf
        self.url = conf.CLIENT_URL

        # Transaction batcher
        self.transaction_queue = queue.Queue()
        self.pending_transactions = []
        self.run_check = None
        self.transaction_batcher_thread = None
        self.last_batch_time = 0

        # Get the key from the local machine
        keyfile = conf.CLIENT_KEY_PATH

        # The signer requires a key from the local user/machine
        # See sawtooth documentation for producing a key
        if keyfile is not None:
            try:
                with open(keyfile) as fd:
                    private_key_str = fd.read().strip()
                    fd.close()
            except OSError as err:
                raise Exception('Failed to read private key at {}'.format(err))

            try:
                private_key = Secp256k1PrivateKey.from_hex(private_key_str)
            except ParseError as e:
                raise Exception(
                    'Unable to load the private key correctly {}'.format(
                        str(e)))

            self._signer = CryptoFactory(
                create_context('secp256k1')).new_signer(private_key)

        self.logger = None
Esempio n. 26
0
    def __init__(self, delegate, args):
        super(IntKeyWorkload, self).__init__(delegate, args)
        self._auth_info = args.auth_info
        self._urls = []
        self._pending_batches = {}
        self._lock = threading.Lock()
        self._delegate = delegate
        self._deps = {}
        context = create_context('secp256k1')
        crypto_factory = CryptoFactory(context=context)
        if args.key_file is not None:
            try:
                with open(args.key_file, 'r') as infile:
                    signing_key = infile.read().strip()
                private_key = Secp256k1PrivateKey.from_hex(signing_key)

                self._signer = crypto_factory.new_signer(
                    private_key=private_key)
            except ParseError as pe:
                raise IntKeyCliException(str(pe))
            except IOError as ioe:
                raise IntKeyCliException(str(ioe))
        else:
            self._signer = crypto_factory.new_signer(
                context.new_random_private_key())
    def __init__(self, base_url, key_file=None):
        '''Initialize the client class.

           This is mainly getting the key pair and computing the address.
        '''
        self._base_url = base_url

        if key_file is None:
            self._signer = None
            return

        try:
            with open(key_file) as key_fd:
                private_key_str = key_fd.read().strip()
        except OSError as err:
            raise Exception('Failed to read private key {}: {}'.format(
                key_file, str(err)))

        try:
            private_key = Secp256k1PrivateKey.from_hex(private_key_str)
        except ParseError as err:
            raise Exception( \
                'Failed to load private key: {}'.format(str(err)))

        self._signer = CryptoFactory(create_context('secp256k1')) \
            .new_signer(private_key)
        self._public_key = self._signer.get_public_key().as_hex()

        # Address is 6-char TF prefix + hash of "mycookiejar"'s public key
        self._address = _hash(FAMILY_NAME.encode('utf-8'))[0:6] + \
            _hash(self._public_key.encode('utf-8'))[0:64]
Esempio n. 28
0
    def _create_batch_list(self, transactions):
        """
        Helps create a batch list to be transmitted to the ledger.
        
        Args:
            transactions (list of Transaction): List containing transaction IDs
        
        Returns:
            type: BatchList
            BatchList object where each batch in the list are constructed in
            the function. 
            
        """
        transaction_signatures = [t.header_signature for t in transactions]

        header = BatchHeader(
            signer_public_key=self._public_key,
            transaction_ids=transaction_signatures).SerializeToString()

        signature = CryptoFactory(create_context("secp256k1")) \
            .new_signer(Secp256k1PrivateKey.from_hex(self._private_key)) \
            .sign(header)

        batch = Batch(header=header,
                      transactions=transactions,
                      header_signature=signature)
        return BatchList(batches=[batch])
 def test_private_key_sawtooth(self):
     """Generates a random private key using Sawtooth Signing's
     Secp256k1PrivateKey class, and make sure it passes sanity checks"""
     self.assertTrue(callable(Secp256k1PrivateKey.new_random))
     private_key = Secp256k1PrivateKey.new_random()
     self.assertIsPrivateKeySecp256k1(private_key)
     return private_key
Esempio n. 30
0
async def create_new_user(request):
    required_fields = ['name', 'password']
    utils.validate_fields(required_fields, request.json)

    # Generate keys
    private_key = Secp256k1PrivateKey.new_random()
    txn_key = Key(private_key.as_hex())
    encrypted_private_key = utils.encrypt_private_key(
        request.app.config.AES_KEY, txn_key.public_key, private_key.as_bytes())

    # Build create user transaction
    batch_list = create_user(txn_key, request.app.config.BATCHER_KEY_PAIR,
                             request.json.get('name'), txn_key.public_key,
                             request.json.get('metadata'),
                             request.json.get('manager'))

    # Submit transaction and wait for complete
    await utils.send(request.app.config.VAL_CONN, batch_list[0],
                     request.app.config.TIMEOUT)

    # Save new user in auth table
    hashed_password = hashlib.sha256(
        request.json.get('password').encode('utf-8')).hexdigest()

    auth_entry = {
        'user_id': txn_key.public_key,
        'hashed_password': hashed_password,
        'encrypted_private_key': encrypted_private_key,
        'email': request.json.get('email')
    }
    await auth_query.create_auth_entry(request.app.config.DB_CONN, auth_entry)

    # Send back success response
    return create_user_response(request, txn_key.public_key)
Esempio n. 31
0
def _load_identity_signer(key_dir, key_name):
    """Loads a private key from the key directory, based on a validator's
    identity.

    Args:
        key_dir (str): The path to the key directory.
        key_name (str): The name of the key to load.

    Returns:
        Signer: the cryptographic signer for the key
    """
    key_path = os.path.join(key_dir, '{}.priv'.format(key_name))

    if not os.path.exists(key_path):
        raise Exception("No such signing key file: {}".format(key_path))
    if not os.access(key_path, os.R_OK):
        raise Exception("Key file is not readable: {}".format(key_path))

    LOGGER.info('Loading signing key: %s', key_path)
    try:
        with open(key_path, 'r') as key_file:
            private_key_str = key_file.read().strip()
    except IOError as e:
        raise Exception("Could not load key file: {}".format(str(e)))

    try:
        private_key = Secp256k1PrivateKey.from_hex(private_key_str)
    except signing.ParseError as e:
        raise Exception("Invalid key in file {}: {}".format(key_path, str(e)))

    context = signing.create_context('secp256k1')
    crypto_factory = CryptoFactory(context)
    return crypto_factory.new_signer(private_key)
Esempio n. 32
0
def _read_signer(key_filename):
    """Reads the given file as a hex key.

    Args:
        key_filename: The filename where the key is stored. If None,
            defaults to the default key for the current user.

    Returns:
        Signer: the signer

    Raises:
        CliException: If unable to read the file.
    """
    filename = key_filename
    if filename is None:
        filename = os.path.join(os.path.expanduser('~'),
                                '.sawtooth',
                                'keys',
                                getpass.getuser() + '.priv')

    try:
        with open(filename, 'r') as key_file:
            signing_key = key_file.read().strip()
    except IOError as e:
        raise CliException('Unable to read key file: {}'.format(str(e)))

    try:
        private_key = Secp256k1PrivateKey.from_hex(signing_key)
    except ParseError as e:
        raise CliException('Unable to read key in file: {}'.format(str(e)))

    context = create_context('secp256k1')
    crypto_factory = CryptoFactory(context)
    return crypto_factory.new_signer(private_key)
    def setUpClass(cls):
        super().setUpClass()
        context = create_context('secp256k1')
        private_key = Secp256k1PrivateKey.from_hex(PRIVATE)
        signer = CryptoFactory(context).new_signer(private_key)

        cls.factory = ValidatorRegistryMessageFactory(
            signer=signer)
Esempio n. 34
0
def get_signature(message, private_key, privkey_format="wif"):
    context = create_context("secp256k1")
    factory = CryptoFactory(context)
    
    privkey = Secp256k1PrivateKey.from_hex(private_key)  
    signer = factory.new_signer(privkey)
    signature = signer.sign(message.encode())    
    return signature
Esempio n. 35
0
def load_config(app):  # pylint: disable=too-many-branches
    app.config.update(DEFAULT_CONFIG)
    config_file_path = os.path.join(
        os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
        'config.py')
    try:
        app.config.from_pyfile(config_file_path)
    except FileNotFoundError:
        LOGGER.warning("No config file provided")

    # CLI Options will override config file options
    opts = parse_args(sys.argv[1:])

    if opts.host is not None:
        app.config.HOST = opts.host
    if opts.port is not None:
        app.config.PORT = opts.port
    if opts.timeout is not None:
        app.config.TIMEOUT = opts.timeout

    if opts.validator is not None:
        app.config.VALIDATOR_URL = opts.validator
    if opts.db_host is not None:
        app.config.DB_HOST = opts.db_host
    if opts.db_port is not None:
        app.config.DB_PORT = opts.db_port
    if opts.db_name is not None:
        app.config.DB_NAME = opts.db_name

    if opts.debug is not None:
        app.config.DEBUG = opts.debug

    if opts.secret_key is not None:
        app.config.SECRET_KEY = opts.secret_key
    if app.config.SECRET_KEY is None:
        LOGGER.exception("API secret key was not provided")
        sys.exit(1)

    if opts.aes_key is not None:
        app.config.AES_KEY = opts.aes_key
    if app.config.AES_KEY is None:
        LOGGER.exception("AES key was not provided")
        sys.exit(1)

    if opts.batcher_private_key is not None:
        app.config.BATCHER_PRIVATE_KEY = opts.batcher_private_key
    if app.config.BATCHER_PRIVATE_KEY is None:
        LOGGER.exception("Batcher private key was not provided")
        sys.exit(1)
    try:
        private_key = Secp256k1PrivateKey.from_hex(
            app.config.BATCHER_PRIVATE_KEY)
    except ParseError as err:
        LOGGER.exception('Unable to load private key: %s', str(err))
        sys.exit(1)
    app.config.CONTEXT = create_context('secp256k1')
    app.config.SIGNER = CryptoFactory(
        app.config.CONTEXT).new_signer(private_key)
    def create_wait_timer(cls,
                          sealed_signup_data,
                          validator_address,
                          previous_certificate_id,
                          local_mean):
        with cls._lock:
            # Extract keys from the 'sealed' signup data
            signup_data = \
                json2dict(
                    base64.b64decode(sealed_signup_data.encode()).decode())
            poet_private_key = signup_data['poet_private_key']

            if poet_private_key is None:
                raise \
                    ValueError(
                        'Invalid signup data. No poet private key.')

            try:
                poet_private_key = Secp256k1PrivateKey.from_hex(
                    poet_private_key)
            except ParseError:
                raise \
                    ValueError(
                        'Invalid signup data. Badly formatted poet key(s).')

            # In a TEE implementation we would increment the HW counter here.
            # We can't usefully simulate a HW counter though.

            # Create some value from the cert ID.  We are just going to use
            # the seal key to sign the cert ID.  We will then use the
            # low-order 64 bits to change that to a number [0, 1]
            tag = \
                base64.b64decode(
                    cls._context.sign(
                        previous_certificate_id.encode(),
                        cls._seal_private_key))

            tagd = float(struct.unpack('Q', tag[-8:])[0]) / (2**64 - 1)

            # Now compute the duration with a minimum wait time guaranteed
            duration = \
                _PoetEnclaveSimulator.MINIMUM_WAIT_TIME \
                - local_mean * math.log(tagd)

            # Create and sign the wait timer
            wait_timer = \
                EnclaveWaitTimer(
                    validator_address=validator_address,
                    duration=duration,
                    previous_certificate_id=previous_certificate_id,
                    local_mean=local_mean)
            wait_timer.signature = \
                cls._context.sign(
                    wait_timer.serialize().encode(),
                    poet_private_key)

            return wait_timer
Esempio n. 37
0
async def get_signer(request):
    email = deserialize_auth_token(
        request.app.config.SECRET_KEY, request.token).get('email')
    auth_info = await auth_query.fetch_info_by_email(
        request.app.config.DB_CONN, email)
    private_key_hex = decrypt_private_key(
        request.app.config.AES_KEY,
        auth_info.get('public_key'),
        auth_info.get('encrypted_private_key'))
    private_key = Secp256k1PrivateKey.from_hex(private_key_hex)
    return CryptoFactory(request.app.config.CONTEXT).new_signer(private_key)
def _read_signing_keys(key_filename):
    """Reads the given file as a HEX formatted key.

    Args:
        key_filename: The filename where the key is stored.

    Returns:
        tuple (str, str): the public and private key pair

    Raises:
        CliException: If unable to read the file.
    """

    filename = key_filename

    with open(filename, 'r') as key_file:
        signing_key = key_file.read().strip()

        return Secp256k1PrivateKey.from_hex(signing_key)
Esempio n. 39
0
    def __init__(self, url, keyfile=None):
        self.url = url

        if keyfile is not None:
            try:
                with open(keyfile) as fd:
                    private_key_str = fd.read().strip()
                    fd.close()
            except OSError as err:
                raise IntkeyClientException(
                    'Failed to read private key: {}'.format(str(err)))

            try:
                private_key = Secp256k1PrivateKey.from_hex(private_key_str)
            except ParseError as e:
                raise IntkeyClientException(
                    'Unable to load private key: {}'.format(str(e)))

            self._signer = CryptoFactory(
                create_context('secp256k1')).new_signer(private_key)
    def __init__(self, name, rest_endpoint):
        """
        Args:
            name (str): An identifier for this Transactor
            rest_endpoint (str): The rest api that this Transactor will
                communicate with.
        """

        self.name = name
        self._rest_endpoint = rest_endpoint \
            if rest_endpoint.startswith("http://") \
            else "http://{}".format(rest_endpoint)
        with open('/root/.sawtooth/keys/{}.priv'.format(name)) as priv_file:
            private_key = Secp256k1PrivateKey.from_hex(
                priv_file.read().strip('\n'))
        self._signer = CryptoFactory(create_context('secp256k1')) \
            .new_signer(private_key)
        self._factories = {}
        self._client = RestClient(url=self._rest_endpoint)

        self._add_transaction_family_factory(Families.INTKEY)
        self._add_transaction_family_factory(Families.XO)
Esempio n. 41
0
def load_identity_signer(key_dir, key_name):
    """Loads a private key from the key directory, based on a validator's
    identity.

    Args:
        key_dir (str): The path to the key directory.
        key_name (str): The name of the key to load.

    Returns:
        Signer: the cryptographic signer for the key
    """
    key_path = os.path.join(key_dir, '{}.priv'.format(key_name))

    if not os.path.exists(key_path):
        raise LocalConfigurationError(
            "No such signing key file: {}".format(key_path))
    if not os.access(key_path, os.R_OK):
        raise LocalConfigurationError(
            "Key file is not readable: {}".format(key_path))

    LOGGER.info('Loading signing key: %s', key_path)
    try:
        with open(key_path, 'r') as key_file:
            private_key_str = key_file.read().strip()
    except IOError as e:
        raise LocalConfigurationError(
            "Could not load key file: {}".format(str(e)))

    try:
        private_key = Secp256k1PrivateKey.from_hex(private_key_str)
    except signing.ParseError as e:
        raise LocalConfigurationError(
            "Invalid key in file {}: {}".format(key_path, str(e)))

    context = signing.create_context('secp256k1')
    crypto_factory = CryptoFactory(context)
    return crypto_factory.new_signer(private_key)
Esempio n. 42
0
    def __init__(self, base_url, keyfile=None):

        self._base_url = base_url

        if keyfile is None:
            self._signer = None
            return

        try:
            with open(keyfile) as fd:
                private_key_str = fd.read().strip()
        except OSError as err:
            raise XoException(
                'Failed to read private key {}: {}'.format(
                    keyfile, str(err)))

        try:
            private_key = Secp256k1PrivateKey.from_hex(private_key_str)
        except ParseError as e:
            raise XoException(
                'Unable to load private key: {}'.format(str(e)))

        self._signer = CryptoFactory(create_context('secp256k1')) \
            .new_signer(private_key)
 def _create_random_key(cls):
     return Secp256k1PrivateKey.new_random()
Esempio n. 44
0
def create_random_private_key():
    return Secp256k1PrivateKey.new_random()
    def create_signup_info(cls,
                           originator_public_key_hash,
                           nonce):
        with cls._lock:
            # First we need to create a public/private key pair for the PoET
            # enclave to use.
            # Counter ID is a placeholder for a hardware counter in a TEE.
            poet_private_key = Secp256k1PrivateKey.new_random()
            poet_public_key = \
                cls._context.get_public_key(poet_private_key)
            counter_id = None

            # Simulate sealing (encrypting) the signup data.
            signup_data = {
                'poet_private_key': poet_private_key.as_hex(),
                'poet_public_key': poet_public_key.as_hex(),
                'counter_id': counter_id
            }
            sealed_signup_data = \
                base64.b64encode(
                    dict2json(signup_data).encode()).decode('utf-8')

            # Build up a fake SGX quote containing:
            # 1. The basename
            # 2. The report body that contains:
            #    a. The enclave measurement
            #    b. The report data SHA256(SHA256(OPK)|PPK)
            sgx_basename = \
                sgx_structs.SgxBasename(name=cls.__VALID_BASENAME__)
            sgx_measurement = \
                sgx_structs.SgxMeasurement(
                    m=cls.__VALID_ENCLAVE_MEASUREMENT__)

            hash_input = \
                '{0}{1}'.format(
                    originator_public_key_hash.upper(),
                    poet_public_key.as_hex().upper()).encode()
            report_data = hashlib.sha256(hash_input).digest()
            sgx_report_data = sgx_structs.SgxReportData(d=report_data)
            sgx_report_body = \
                sgx_structs.SgxReportBody(
                    mr_enclave=sgx_measurement,
                    report_data=sgx_report_data)

            sgx_quote = \
                sgx_structs.SgxQuote(
                    basename=sgx_basename,
                    report_body=sgx_report_body)

            # Create a fake PSE manifest.  A base64 encoding of the
            # originator public key hash should suffice.
            pse_manifest = \
                base64.b64encode(originator_public_key_hash.encode())

            timestamp = datetime.datetime.now().isoformat()

            # Fake our "proof" data.
            verification_report = {
                'epidPseudonym': cls._anti_sybil_id,
                'id': base64.b64encode(
                    hashlib.sha256(
                        timestamp.encode()).hexdigest().encode()).decode(),
                'isvEnclaveQuoteStatus': 'OK',
                'isvEnclaveQuoteBody':
                    base64.b64encode(sgx_quote.serialize_to_bytes()).decode(),
                'pseManifestStatus': 'OK',
                'pseManifestHash':
                    hashlib.sha256(base64.b64decode(pse_manifest)).hexdigest(),
                'nonce': nonce,
                'timestamp': timestamp
            }

            # Serialize the verification report, sign it, and then put
            # in the proof data
            verification_report_json = dict2json(verification_report)
            signature = \
                cls._report_private_key.sign(
                    verification_report_json.encode(),
                    padding.PKCS1v15(),
                    hashes.SHA256())

            proof_data_dict = {
                'evidence_payload': {
                    'pse_manifest': pse_manifest.decode()
                },
                'verification_report': verification_report_json,
                'signature': base64.b64encode(signature).decode()
            }
            proof_data = dict2json(proof_data_dict)

            return \
                EnclaveSignupInfo(
                    poet_public_key=signup_data['poet_public_key'],
                    proof_data=proof_data,
                    anti_sybil_id=cls._anti_sybil_id,
                    sealed_signup_data=sealed_signup_data)
    def create_wait_certificate(cls,
                                sealed_signup_data,
                                wait_timer,
                                block_hash):
        with cls._lock:
            # Extract keys from the 'sealed' signup data
            if sealed_signup_data is None:
                raise ValueError('Sealed Signup Data is None')
            signup_data = \
                json2dict(
                    base64.b64decode(sealed_signup_data.encode()).decode())
            poet_private_key = signup_data['poet_private_key']
            poet_public_key = signup_data['poet_public_key']

            if poet_private_key is None or poet_public_key is None:
                raise \
                    ValueError(
                        'Invalid signup data. No poet key(s).')

            try:
                poet_public_key = Secp256k1PublicKey.from_hex(poet_public_key)
                poet_private_key = Secp256k1PrivateKey.from_hex(
                    poet_private_key)
            except ParseError:
                raise \
                    ValueError(
                        'Invalid signup data. Badly formatted poet key(s).')

            # Several criteria need to be met before we can create a wait
            # certificate:
            # 1. This signup data was used to sign this timer.
            #    i.e. the key sealed / unsealed by the TEE signed this
            #    wait timer.
            # 2. This timer has expired
            # 3. This timer has not timed out
            #
            # In a TEE implementation we would check HW counter agreement.
            # We can't usefully simulate a HW counter though.
            # i.e. wait_timer.counter_value == signup_data.counter.value

            #
            # Note - we make a concession for the genesis block (i.e., a wait
            # timer for which the previous certificate ID is the Null
            # identifier) in that we don't require the timer to have expired
            # and we don't worry about the timer having timed out.

            if wait_timer is None or \
                    not cls._context.verify(
                        wait_timer.signature,
                        wait_timer.serialize().encode(),
                        poet_public_key):
                raise \
                    ValueError(
                        'Validator is not using the current wait timer')

            is_not_genesis_block = \
                (wait_timer.previous_certificate_id !=
                 NULL_BLOCK_IDENTIFIER)

            now = time.time()
            expire_time = \
                wait_timer.request_time + \
                wait_timer.duration

            if is_not_genesis_block and now < expire_time:
                raise \
                    ValueError(
                        'Cannot create wait certificate because timer has '
                        'not expired')

            time_out_time = \
                wait_timer.request_time + \
                wait_timer.duration + \
                TIMER_TIMEOUT_PERIOD

            if is_not_genesis_block and time_out_time < now:
                raise \
                    ValueError(
                        'Cannot create wait certificate because timer '
                        'has timed out')

            # Create a random nonce for the certificate.  For our "random"
            # nonce we will take the timer signature, concat that with the
            # current time, JSON-ize it and create a SHA-256 hash over it.
            # Probably not considered random by security professional
            # standards, but it is good enough for the simulator.
            random_string = \
                dict2json({
                    'wait_timer_signature': wait_timer.signature,
                    'now': datetime.datetime.utcnow().isoformat()
                })
            nonce = hashlib.sha256(random_string.encode()).hexdigest()

            # First create a new enclave wait certificate using the data
            # provided and then sign the certificate with the PoET private key
            wait_certificate = \
                EnclaveWaitCertificate.wait_certificate_with_wait_timer(
                    wait_timer=wait_timer,
                    nonce=nonce,
                    block_hash=block_hash)
            wait_certificate.signature = \
                cls._context.sign(
                    wait_certificate.serialize().encode(),
                    poet_private_key)

            # In a TEE implementation we would increment the HW counter here
            # to prevent replay.
            # We can't usefully simulate a HW counter though.

            return wait_certificate