def do_populate(args): context = create_context('secp256k1') signer = CryptoFactory(context).new_signer( context.new_random_private_key()) words = generate_word_list(args.pool_size) batches = [] total_txn_count = 0 txns = [] for i in range(0, len(words)): txn = create_intkey_transaction( verb='set', name=words[i], value=random.randint(9000, 100000), signer=signer) total_txn_count += 1 txns.append(txn) batch = create_batch( transactions=txns, signer=signer) batches.append(batch) batch_list = batch_pb2.BatchList(batches=batches) print("Writing to {}...".format(args.output)) with open(args.output, "wb") as fd: fd.write(batch_list.SerializeToString())
def setUp(self): self.dir = tempfile.mkdtemp() self.block_db = NativeLmdbDatabase( os.path.join(self.dir, 'block.lmdb'), BlockStore.create_index_configuration()) self.block_store = BlockStore(self.block_db) self.block_manager = BlockManager() self.block_manager.add_commit_store(self.block_store) self.gossip = MockGossip() self.completer = Completer( block_manager=self.block_manager, transaction_committed=self.block_store.has_transaction, get_committed_batch_by_id=self.block_store.get_batch, get_committed_batch_by_txn_id=( self.block_store.get_batch_by_transaction ), get_chain_head=lambda: self.block_store.chain_head, gossip=self.gossip) self.completer.set_on_block_received(self._on_block_received) self.completer.set_on_batch_received(self._on_batch_received) self._has_block_value = True context = create_context('secp256k1') private_key = context.new_random_private_key() crypto_factory = CryptoFactory(context) self.signer = crypto_factory.new_signer(private_key) self.blocks = [] self.batches = []
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, 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 is_valid_batch(batch): # validate batch signature header = BatchHeader() header.ParseFromString(batch.header) context = create_context('secp256k1') public_key = Secp256k1PublicKey.from_hex(header.signer_public_key) if not context.verify(batch.header_signature, batch.header, public_key): LOGGER.debug("batch failed signature validation: %s", batch.header_signature) return False # validate all transactions in batch for txn in batch.transactions: if not is_valid_transaction(txn): return False txn_header = TransactionHeader() txn_header.ParseFromString(txn.header) if txn_header.batcher_public_key != header.signer_public_key: LOGGER.debug("txn batcher public_key does not match signer" "public_key for batch: %s txn: %s", batch.header_signature, txn.header_signature) return False return True
def do_populate(batches, keys): context = create_context('secp256k1') private_key = context.new_random_private_key() crypto_factory = CryptoFactory(context) signer = crypto_factory.new_signer(private_key) total_txn_count = 0 txns = [] for i in range(0, len(keys)): name = list(keys)[i] txn = create_intkey_transaction( verb='set', name=name, value=random.randint(9000, 100000), deps=[], signer=signer) total_txn_count += 1 txns.append(txn) # Establish the signature of the txn associated with the word # so we can create good dependencies later keys[name] = txn.header_signature batch = create_batch( transactions=txns, signer=signer) batches.append(batch)
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 __init__(self, delegate, args): super(NoopWorkload, self).__init__(delegate, args) self._urls = [] self._lock = threading.Lock() self._delegate = delegate context = create_context('secp256k1') self._signer = CryptoFactory(context).new_signer( context.new_random_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)
def _create_key(self, key_name='validator.priv'): context = create_context('secp256k1') private_key = context.new_random_private_key() priv_file = os.path.join(self._temp_dir, key_name) with open(priv_file, 'w') as priv_fd: priv_fd.write(private_key.as_hex()) return context.get_public_key(private_key).as_hex()
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 __init__(self, rest_endpoint): context = create_context('secp256k1') private_key = context.new_random_private_key() self.priv_key = private_key.as_hex() self.pub_key = context.get_public_key(private_key).as_hex() self._priv_key_file = os.path.join("/tmp", uuid4().hex[:20]) with open(self._priv_key_file, mode='w') as out: out.write(self.priv_key) self._rest_endpoint = rest_endpoint
def setUp(self): context = create_context('secp256k1') crypto_factory = CryptoFactory(context) private_key = context.new_random_private_key() self.signer = crypto_factory.new_signer(private_key) self._identity_view_factory = MockIdentityViewFactory() self.permissions = {} self._identity_cache = IdentityCache( self._identity_view_factory) self.permission_verifier = \ PermissionVerifier( permissions=self.permissions, current_root_func=self._current_root_func, identity_cache=self._identity_cache)
def test_deserialized_wait_certificate(self): wait_timer = \ EnclaveWaitTimer( validator_address='1600 Pennsylvania Avenue NW', duration=3.14159, previous_certificate_id='Smart, Maxwell Smart', local_mean=2.71828) wait_certificate = \ EnclaveWaitCertificate.wait_certificate_with_wait_timer( wait_timer=wait_timer, nonce='Eeny, meeny, miny, moe.', block_hash='Indigestion. Pepto Bismol.') serialized = wait_certificate.serialize() private_key = self._create_random_key() wait_certificate.signature = \ create_context('secp256k1').sign(serialized.encode(), private_key) copy_wait_certificate = \ EnclaveWaitCertificate.wait_certificate_from_serialized( serialized, wait_certificate.signature) self.assertAlmostEqual( wait_certificate.request_time, copy_wait_certificate.request_time) self.assertAlmostEqual( wait_certificate.duration, copy_wait_certificate.duration) self.assertEqual( wait_certificate.previous_certificate_id, copy_wait_certificate.previous_certificate_id) self.assertAlmostEqual( wait_certificate.local_mean, copy_wait_certificate.local_mean) self.assertEqual( wait_certificate.validator_address, copy_wait_certificate.validator_address) self.assertEqual( wait_certificate.nonce, copy_wait_certificate.nonce) self.assertEqual( wait_certificate.block_hash, copy_wait_certificate.block_hash) self.assertEqual( wait_certificate.signature, copy_wait_certificate.signature) self.assertEqual(serialized, copy_wait_certificate.serialize())
def __init__(self, rest_endpoint): context = create_context('secp256k1') private_key = context.new_random_private_key() self.priv_key = private_key.as_hex() self.pub_key = context.get_public_key(private_key).as_hex() self.signer = CryptoFactory(context).new_signer(private_key) self._namespace = hashlib.sha512('intkey'.encode()).hexdigest()[:6] self._factory = MessageFactory( 'intkey', '1.0', self._namespace, signer=self.signer) self._rest = RestClient(rest_endpoint)
def __init__(self, with_genesis=True): self.block_sender = MockBlockSender() self.batch_sender = MockBatchSender() self.dir = tempfile.mkdtemp() self.block_db = NativeLmdbDatabase( os.path.join(self.dir, 'block.lmdb'), BlockStore.create_index_configuration()) self.block_store = BlockStore(self.block_db) self.block_cache = BlockCache(self.block_store) self.state_db = NativeLmdbDatabase( os.path.join(self.dir, "merkle.lmdb"), MerkleDatabase.create_index_configuration()) self.state_view_factory = NativeStateViewFactory(self.state_db) self.block_manager = BlockManager() self.block_manager.add_commit_store(self.block_store) context = create_context('secp256k1') private_key = context.new_random_private_key() crypto_factory = CryptoFactory(context) self.signer = crypto_factory.new_signer(private_key) identity_private_key = context.new_random_private_key() self.identity_signer = crypto_factory.new_signer(identity_private_key) chain_head = None if with_genesis: self.genesis_block = self.generate_genesis_block() chain_head = self.genesis_block self.block_manager.put([chain_head.block]) self.block_manager.persist( chain_head.block.header_signature, "commit_store") self.block_publisher = BlockPublisher( block_manager=self.block_manager, transaction_executor=MockTransactionExecutor(), transaction_committed=self.block_store.has_transaction, batch_committed=self.block_store.has_batch, state_view_factory=self.state_view_factory, block_sender=self.block_sender, batch_sender=self.block_sender, chain_head=chain_head.block, identity_signer=self.identity_signer, data_dir=None, config_dir=None, permission_verifier=MockPermissionVerifier(), batch_observers=[])
def generate_signer(keyfile=None, pubkey_file=None): context = create_context('secp256k1') private_key = context.new_random_private_key() signer = None if keyfile: try: with open(keyfile, 'w') as fd: fd.write(private_key.as_hex()) with open(pubkey_file, 'w') as fd: signer = CryptoFactory(context).new_signer(private_key) fd.write(signer.get_public_key().as_hex()) except OSError as err: raise ClientException(f'Failed to write private key: {err}') if not signer: signer = CryptoFactory(context).new_signer(private_key) return CryptoFactory(context).new_signer(private_key)
def get_signer_priv_key_from_file(keyfile): try: with open(keyfile) as fd: private_key_str = fd.read().strip() except OSError as err: raise ClientException('Failed to read private key: {}'.format( str(err))) try: private_key = Secp256k1PrivateKey.from_hex(private_key_str) except ParseError as e: raise ClientException('Unable to load private key: {}'.format( str(e))) context = create_context('secp256k1') return CryptoFactory(context).new_signer(private_key)
def _create_batch_list(self, transactions): 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) # signature = signing.sign(header, self._private_key) batch = Batch(header=header, transactions=transactions, header_signature=signature) return BatchList(batches=[batch])
def do_generate(args): context = create_context('secp256k1') signer = CryptoFactory(context).new_signer( context.new_random_private_key()) words = generate_word_list(args.pool_size) batches = [] start = time.time() total_txn_count = 0 for i in range(0, args.count): txns = [] for _ in range(0, random.randint(1, args.batch_max_size)): txn = create_bgt_transaction( verb=random.choice(['inc', 'dec']), name=random.choice(words), value=1, signer=signer) total_txn_count += 1 txns.append(txn) batch = create_batch( transactions=txns, signer=signer) batches.append(batch) if i % 100 == 0 and i != 0: stop = time.time() txn_count = 0 for batch in batches[-100:]: txn_count += len(batch.transactions) fmt = 'batches {}, batch/sec: {:.2f}, txns: {}, txns/sec: {:.2f}' print(fmt.format( str(i), 100 / (stop - start), str(total_txn_count), txn_count / (stop - start))) start = stop batch_list = batch_pb2.BatchList(batches=batches) print("Writing to {}...".format(args.output)) with open(args.output, "wb") as fd: fd.write(batch_list.SerializeToString())
def do_generate(args): context = create_context('secp256k1') signer = CryptoFactory(context).new_signer( context.new_random_private_key()) words = generate_word_list(args.pool_size) batches = [] start = time.time() total_txn_count = 0 for i in range(0, args.count): txns = [] for _ in range(0, random.randint(1, args.batch_max_size)): txn = create_intkey_transaction( verb=random.choice(['inc', 'dec']), name=random.choice(words), value=1, signer=signer) total_txn_count += 1 txns.append(txn) batch = create_batch( transactions=txns, signer=signer) batches.append(batch) if i % 100 == 0 and i != 0: stop = time.time() txn_count = 0 for batch in batches[-100:]: txn_count += len(batch.transactions) fmt = 'batches {}, batch/sec: {:.2f}, txns: {}, txns/sec: {:.2f}' print(fmt.format( str(i), 100 / (stop - start), str(total_txn_count), txn_count / (stop - start))) start = stop batch_list = batch_pb2.BatchList(batches=batches) print("Writing to {}...".format(args.output)) with open(args.output, "wb") as fd: fd.write(batch_list.SerializeToString())
def __init__(self, with_genesis=True): self.block_sender = MockBlockSender() self.batch_sender = MockBatchSender() self.dir = tempfile.mkdtemp() self.block_db = NativeLmdbDatabase( os.path.join(self.dir, 'block.lmdb'), BlockStore.create_index_configuration()) self.block_store = BlockStore(self.block_db) self.block_cache = BlockCache(self.block_store) self.state_db = NativeLmdbDatabase( os.path.join(self.dir, "merkle.lmdb"), MerkleDatabase.create_index_configuration()) self.state_view_factory = NativeStateViewFactory(self.state_db) self.block_manager = BlockManager() self.block_manager.add_commit_store(self.block_store) context = create_context('secp256k1') private_key = context.new_random_private_key() crypto_factory = CryptoFactory(context) self.signer = crypto_factory.new_signer(private_key) identity_private_key = context.new_random_private_key() self.identity_signer = crypto_factory.new_signer(identity_private_key) chain_head = None if with_genesis: self.genesis_block = self.generate_genesis_block() chain_head = self.genesis_block self.block_manager.put([chain_head.block]) self.block_manager.persist(chain_head.block.header_signature, "commit_store") self.block_publisher = BlockPublisher( block_manager=self.block_manager, transaction_executor=MockTransactionExecutor(), transaction_committed=self.block_store.has_transaction, batch_committed=self.block_store.has_batch, state_view_factory=self.state_view_factory, block_sender=self.block_sender, batch_sender=self.block_sender, chain_head=chain_head.block, identity_signer=self.identity_signer, data_dir=None, config_dir=None, permission_verifier=MockPermissionVerifier(), batch_observers=[])
def __init__(self, loop, connection,timeout=DEFAULT_TIMEOUT, metrics_registry=None): super().__init__(loop,connection,timeout,metrics_registry) # Dashboard init self._context = create_context('secp256k1') self._private_key = Secp256k1PrivateKey.new_random() self._public_key = self._context.get_public_key(self._private_key) self._crypto_factory = CryptoFactory(self._context) self._signer = self._crypto_factory.new_signer(self._private_key) self._public_key_id = self._public_key.as_hex() LOGGER.debug('DashboardRouteHandler: _signer PUBLIC_KEY=%s',self._public_key_id[:8]) self._network = {} try: with open('./network.json') as file: self._network = json.load(file) except Exception as err: LOGGER.debug('DashboardRouteHandler: err=%s',err)
def test_many_key_signing(self): context = create_context("secp256k1") self.assertEqual(context.get_algorithm_name(), "secp256k1") priv_key1 = Secp256k1PrivateKey.from_hex(KEY1_PRIV_HEX) self.assertEqual(priv_key1.get_algorithm_name(), "secp256k1") self.assertEqual(priv_key1.as_hex(), KEY1_PRIV_HEX) priv_key2 = Secp256k1PrivateKey.from_hex(KEY2_PRIV_HEX) self.assertEqual(priv_key2.get_algorithm_name(), "secp256k1") self.assertEqual(priv_key2.as_hex(), KEY2_PRIV_HEX) signature = context.sign(MSG1.encode(), priv_key1) self.assertEqual(signature, MSG1_KEY1_SIG) signature = context.sign(MSG2.encode(), priv_key2) self.assertEqual(signature, MSG2_KEY2_SIG)
def do_deserialized_wait_timer(): wait_timer = \ EnclaveWaitTimer( validator_address='1600 Pennsylvania Avenue NW', duration=3.14159, previous_certificate_id='Bond. James Bond.', local_mean=2.71828) serialized = wait_timer.serialize() private_key = _create_random_key() wait_timer.signature = \ create_context('secp256k1').sign(serialized.encode(), private_key) copy_wait_timer = \ EnclaveWaitTimer.wait_timer_from_serialized( serialized, wait_timer.signature)
def setUp(self): self.block_store = BlockStore(DictDatabase( indexes=BlockStore.create_index_configuration())) self.gossip = MockGossip() self.completer = Completer(self.block_store, self.gossip) self.completer._on_block_received = self._on_block_received self.completer._on_batch_received = self._on_batch_received self.completer._has_block = self._has_block self._has_block_value = True context = create_context('secp256k1') private_key = context.new_random_private_key() crypto_factory = CryptoFactory(context) self.signer = crypto_factory.new_signer(private_key) self.blocks = [] self.batches = []
def test_priv_to_public_key(self): context = create_context("secp256k1") self.assertEqual(context.get_algorithm_name(), "secp256k1") priv_key1 = Secp256k1PrivateKey.from_hex(KEY1_PRIV_HEX) self.assertEqual(priv_key1.get_algorithm_name(), "secp256k1") self.assertEqual(priv_key1.as_hex(), KEY1_PRIV_HEX) public_key1 = context.get_public_key(priv_key1) self.assertEqual(public_key1.as_hex(), KEY1_PUB_HEX) priv_key2 = Secp256k1PrivateKey.from_hex(KEY2_PRIV_HEX) self.assertEqual(priv_key2.get_algorithm_name(), "secp256k1") self.assertEqual(priv_key2.as_hex(), KEY2_PRIV_HEX) public_key2 = context.get_public_key(priv_key2) self.assertEqual(public_key2.as_hex(), KEY2_PUB_HEX)
def __init__(self): self.block_store = BlockStore( DictDatabase(indexes=BlockStore.create_index_configuration())) self.gossip = MockGossip() self.completer = Completer(self.block_store, self.gossip) self.completer._on_block_received = self._on_block_received self.completer._on_batch_received = self._on_batch_received self.completer._has_block = self._has_block self._has_block_value = True context = create_context('secp256k1') private_key = context.new_random_private_key() crypto_factory = CryptoFactory(context) self.signer = crypto_factory.new_signer(private_key) self.blocks = [] self.batches = []
def __init__(self, with_genesis=True): self.block_sender = MockBlockSender() self.batch_sender = MockBatchSender() self.block_store = BlockStore(DictDatabase( indexes=BlockStore.create_index_configuration())) self.block_cache = BlockCache(self.block_store) self.state_db = {} # add the mock reference to the consensus consensus_setting_addr = SettingsView.setting_address( 'sawtooth.consensus.algorithm') self.state_db[consensus_setting_addr] = _setting_entry( 'sawtooth.consensus.algorithm', 'test_journal.mock_consensus') self.state_view_factory = MockStateViewFactory(self.state_db) context = create_context('secp256k1') private_key = context.new_random_private_key() crypto_factory = CryptoFactory(context) self.signer = crypto_factory.new_signer(private_key) identity_private_key = context.new_random_private_key() self.identity_signer = crypto_factory.new_signer(identity_private_key) chain_head = None if with_genesis: self.genesis_block = self.generate_genesis_block() self.set_chain_head(self.genesis_block) chain_head = self.genesis_block self.block_publisher = BlockPublisher( transaction_executor=MockTransactionExecutor(), block_cache=self.block_cache, state_view_factory=self.state_view_factory, settings_cache=SettingsCache( SettingsViewFactory(self.state_view_factory), ), block_sender=self.block_sender, batch_sender=self.block_sender, squash_handler=None, chain_head=chain_head, identity_signer=self.identity_signer, data_dir=None, config_dir=None, permission_verifier=MockPermissionVerifier(), check_publish_block_frequency=0.1, batch_observers=[])
def test_namespace_restriction(self): """ Tests that namespaces stored on-chain are enforced by the validators. According to the sawtooth_settings declared in the docker compose file, the transaciton families are expected to behave as follows: - block_info transactions are allowed - intkey transactions are banned - xo transactions are allowed """ context = create_context('secp256k1') signer = CryptoFactory(context).new_signer( context.new_random_private_key()) batches = make_batches(signer, 'abcde') send_xo_cmd('sawtooth keygen') xo_cmds = [ 'xo create game', 'xo take game 5', 'xo take game 9', 'xo create game2', 'xo take game2 4', ] # Assert all block info transactions are committed for i, batch in enumerate(batches): post_batch(batch) send_xo_cmd('{} --url {} --wait {}'.format(xo_cmds[i], 'http://rest-api:8008', WAIT)) block_info = get_block_info(i) self.assertEqual(block_info.block_num, i) # Assert block info batches are first in the block and # that any other batch is of the xo family for block in get_blocks()[:-1]: LOGGER.debug(block['header']['block_num']) family_name = \ block['batches'][0]['transactions'][0]['header']['family_name'] self.assertEqual(family_name, 'block_info') for batch in block['batches'][1:]: self.assertEqual( batch['transactions'][0]['header']['family_name'], 'xo')
def __init__(self, certificate, dsa, rsa): # We need this to generate the DSA-related information. self._context = create_context('secp256k1') self._crypto_factory = CryptoFactory(self._context) # DSA self._dsa_private = secp256k1.Secp256k1PrivateKey.from_hex(dsa) self._dsa_public = secp256k1.Secp256k1PublicKey( self._dsa_private.secp256k1_private_key.pubkey) self._transaction_signer = self._crypto_factory.new_signer( self._dsa_private) # RSA with open(rsa, 'r') as f: self._rsa = RSA.importKey(f.read()) # Certificate Data self._certificate_identifier = certificate
def interactive_loop(self): context = create_context("secp256k1") print("""Provisioning a random private key, this is valid and remembered until you exit the {}""".format(APP_NAME)) self.private_key = context.new_random_private_key() self.signer = CryptoFactory(context).new_signer(self.private_key) choice = "" while choice != CHOICE_EXIT: choice = inquirer.list_input("Please choose an action", choices=CHOICES) if choice == CHOICE_CREATE_GAME: self.interactive_loop_create_game() elif choice == CHOICE_DELETE_GAME: self.interactive_loop_delete_game() elif choice == CHOICE_MAKE_A_GUESS: self.interactive_loop_make_a_guess() elif choice == CHOICE_GET_LIST_OF_BLOCKS: self.interactive_loop_get_list_of_blocks()
def is_valid_block(block): # validate block signature header = BlockHeader() header.ParseFromString(block.header) context = create_context('secp256k1') public_key = Secp256k1PublicKey.from_hex(header.signer_public_key) if not context.verify(block.header_signature, block.header, public_key): LOGGER.debug("block failed signature validation: %s", block.header_signature) return False # validate all batches in block. These are not all batches in the # batch_ids stored in the block header, only those sent with the block. if not all(map(is_valid_batch, block.batches)): return False return True
def __init__(self, private_key=None, public_key=None): """ Key() -- generates a new key Key(private_key:str) -- Uses the private key passed """ self._context = create_context(ELLIPTIC_CURVE_ALGORITHM) if private_key is None and public_key is None: private_key = Secp256k1PrivateKey.new_random() if isinstance(private_key, str): private_key = Secp256k1PrivateKey.from_hex(private_key) if isinstance(public_key, str): public_key = Secp256k1PublicKey.from_hex(public_key) if public_key is None and private_key is not None: public_key = self._context.get_public_key(private_key) self._public_key = public_key self._private_key = private_key
def do_generate(args, batches, keys, value, bNeedSetDesp): context = create_context('secp256k1') private_key = context.new_random_private_key() crypto_factory = CryptoFactory(context) signer = crypto_factory.new_signer(private_key) start = time.time() total_txn_count = 0 for i in range(1): txns = [] for _ in range(1): name = random.choice(list(keys)) txn = create_intkey_transaction( # verb=random.choice(['inc', 'dec']), verb='inc', name=name, # value=random.randint(1, 10), value=value, # deps=[keys[name]], deps= [keys[name]] if bNeedSetDesp else [], signer=signer) total_txn_count += 1 txns.append(txn) batch = create_batch( transactions=txns, signer=signer) batches.append(batch) if i % 100 == 0 and i != 0: stop = time.time() txn_count = 0 for batch in batches[-100:]: txn_count += len(batch.transactions) fmt = 'batches {}, batch/sec: {:.2f}, txns: {}, txns/sec: {:.2f}' print(fmt.format( str(i), 100 / (stop - start), str(total_txn_count), txn_count / (stop - start))) start = stop
def send_category_transactions(self, category_id, category_name, description, action, private_key, public_key, prev, cur, timestamp): self._public_key = public_key self._private_key = private_key payload = { "category_id": str(category_id), "category_name": str(category_name), "description": str(description), "action": str(action), "prev_block": str(prev), "cur_block": str(cur), "timestamp": str(timestamp) } payload = json.dumps(payload).encode() # Form the address address = self._get_address(category_id) header = TransactionHeader( signer_public_key=self._public_key, family_name="category", family_version="1.0", inputs=[address], outputs=[address], dependencies=[], payload_sha512=_sha512(payload), batcher_public_key=self._public_key, nonce=time.time().hex().encode()).SerializeToString() signature = CryptoFactory(create_context("secp256k1")) \ .new_signer(Secp256k1PrivateKey.from_hex(self._private_key))\ .sign(header) transaction = Transaction(header=header, payload=payload, header_signature=signature) batch_list = self._create_batch_list([transaction]) return self._send_request("batches", batch_list.SerializeToString(), "application/octet-stream")
def create_part_transaction(self, pt_id,pt_name,checksum,version,alias,licensing,label,description, action,private_key,public_key, artifact_id,category_id,supplier_id ): self._public_key = public_key self._private_key = private_key payload = ",".join([pt_id,str(pt_name),str(checksum),str(version),str(alias),str(licensing),str(label),str(description), action,str(artifact_id),str(category_id),str(supplier_id)]).encode() # Construct the address address = self._get_address(pt_id) header = TransactionHeader( signer_public_key=self._public_key, family_name="pt", family_version="1.0", inputs=[address], outputs=[address], dependencies=[], # payload_encoding="csv-utf8", payload_sha512=_sha512(payload), batcher_public_key=self._public_key, nonce=time.time().hex().encode() ).SerializeToString() # signature = signing.sign(header, self._private_key signature = CryptoFactory(create_context('secp256k1')) \ .new_signer(Secp256k1PrivateKey.from_hex(self._private_key)).sign(header) transaction = Transaction( header=header, payload=payload, header_signature=signature ) batch_list = self._create_batch_list([transaction]) #print("Sending request") return self._send_request( "batches", batch_list.SerializeToString(), 'application/octet-stream' )
def __init__(self, base_url, key_file=None): self._base_url = base_url 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()
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 codeSmellException('Failed to read private key {}: {}'.format(keyfile, str(err))) try: private_key = Secp256k1PrivateKey.from_hex(private_key_str) except ParseError as e: raise codeSmellException('Unable to load private key: {}'.format(str(e))) self._signer = CryptoFactory(create_context('secp256k1')).new_signer(private_key)
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 IoTException('Failed to read private key: {}'.format( str(err))) try: private_key = Secp256k1PrivateKey.from_hex(private_key_str) except ParseError as e: raise IoTException('Unable to load private key: {}'.format( str(e))) self._signer = CryptoFactory( create_context('secp256k1')).new_signer(private_key)
def __init__(self, family_handler, keyfile=PRIV_KEY_FILE): self.url = REST_API_URL self._family_handler = family_handler try: with open(keyfile) as fd: private_key_str = fd.read().strip() fd.close() except OSError as err: raise ClientException('Failed to read private key: {}'.format( str(err))) try: private_key = Secp256k1PrivateKey.from_hex(private_key_str) except ParseError as e: raise ClientException('Unable to load private key: {}'.format( str(e))) self._signer = CryptoFactory( create_context('secp256k1')).new_signer(private_key)
def __init__(self, signer): self._factory = MessageFactory( family_name="sawtooth_validator_registry", family_version="1.0", namespace="6a4372", signer=signer) self.public_key_hash = hashlib.sha256( signer.get_public_key().as_hex().encode()).hexdigest() self._report_private_key = \ serialization.load_pem_private_key( self.__REPORT_PRIVATE_KEY_PEM__.encode(), password=None, backend=backends.default_backend()) # First we need to create a public/private key pair for the PoET # enclave to use. context = create_context('secp256k1') self._poet_private_key = Secp256k1PrivateKey.from_hex( "1f70fa2518077ad18483f48e77882d11983b537fa5f7cf158684d2c670fe4f1f") self.poet_public_key = context.get_public_key(self._poet_private_key)
def __init__(self, base_url, work_path, keyfile=None): self._base_url = base_url self._work_path = work_path if keyfile is None: self._signer = None return try: with open(keyfile) as file_ptr: private_key_str = file_ptr.read().strip() except OSError as err: raise HealthException('Failed to read private key {}: {}'.format(keyfile, str(err))) try: private_key = Secp256k1PrivateKey.from_hex(private_key_str) except ParseError as parser_error: raise HealthException('Unable to load private key: {}'.format(str(parser_error))) self._signer = CryptoFactory(create_context('secp256k1')).new_signer(private_key)
def __init__(self, baseUrl, private_key=None, vin=''): '''Initialize the client class. This is mainly getting the key pair and computing the address. ''' self._baseUrl = baseUrl try: privateKey = Secp256k1PrivateKey.from_hex(private_key) 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() self.VIN = vin self._address = _hash(FAMILY_NAME.encode('utf-8'))[0:6] + \ _hash(self.VIN.encode('utf-8'))[0:64]
def search(): keys = [] for file in glob(f'{KEY_DIR}/*.priv'): try: with open(file) as f: contents = f.read().strip() private_key = Secp256k1PrivateKey.from_hex(contents) context = create_context('secp256k1') signer = CryptoFactory(context).new_signer(private_key) keys.append({ 'name': os.path.splitext(os.path.basename(file))[0], 'pub_key': signer.get_public_key().as_hex() }) except OSError: return {'error': f'Cannot read private key file {file}'}, 400 except ParseError: return { 'error': f'Cannot parse contents of private key file {file}' }, 400 return {'keys': keys}
def gen_signer_key(key_file): from sawtooth_signing import create_context from sawtooth_signing import CryptoFactory from sawtooth_signing.secp256k1 import Secp256k1PrivateKey from sawtooth_signing import ParseError context = create_context('secp256k1') crypto_factory = CryptoFactory(context=context) if key_file is not None: try: with open(key_file, 'r') as infile: signing_key = infile.read().strip() private_key = Secp256k1PrivateKey.from_hex(signing_key) except ParseError as pe: raise CliException(str(pe)) except IOError as ioe: raise CliException(str(ioe)) else: private_key = context.new_random_private_key() return crypto_factory.new_signer(private_key)
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 test_deserialized_wait_certificate(self): wait_timer = \ EnclaveWaitTimer( validator_address='1600 Pennsylvania Avenue NW', duration=3.14159, previous_certificate_id='Smart, Maxwell Smart', local_mean=2.71828) wait_certificate = \ EnclaveWaitCertificate.wait_certificate_with_wait_timer( wait_timer=wait_timer, nonce='Eeny, meeny, miny, moe.', block_hash='Indigestion. Pepto Bismol.') serialized = wait_certificate.serialize() private_key = self._create_random_key() wait_certificate.signature = \ create_context('secp256k1').sign(serialized.encode(), private_key) copy_wait_certificate = \ EnclaveWaitCertificate.wait_certificate_from_serialized( serialized, wait_certificate.signature) self.assertAlmostEqual(wait_certificate.request_time, copy_wait_certificate.request_time) self.assertAlmostEqual(wait_certificate.duration, copy_wait_certificate.duration) self.assertEqual(wait_certificate.previous_certificate_id, copy_wait_certificate.previous_certificate_id) self.assertAlmostEqual(wait_certificate.local_mean, copy_wait_certificate.local_mean) self.assertEqual(wait_certificate.validator_address, copy_wait_certificate.validator_address) self.assertEqual(wait_certificate.nonce, copy_wait_certificate.nonce) self.assertEqual(wait_certificate.block_hash, copy_wait_certificate.block_hash) self.assertEqual(wait_certificate.signature, copy_wait_certificate.signature) self.assertEqual(serialized, copy_wait_certificate.serialize())
def do_generate(args, batches, keys): context = create_context('secp256k1') private_key = context.new_random_private_key() crypto_factory = CryptoFactory(context) signer = crypto_factory.new_signer(private_key) start = time.time() total_txn_count = 0 for i in range(0, args.count): txns = [] for _ in range(0, random.randint(1, args.max_batch_size)): name = random.choice(list(keys)) txn = create_intkey_transaction( verb=random.choice(['inc', 'dec']), name=name, value=random.randint(1, 10), deps=[keys[name]], signer=signer) total_txn_count += 1 txns.append(txn) batch = create_batch( transactions=txns, signer=signer) batches.append(batch) if i % 100 == 0 and i != 0: stop = time.time() txn_count = 0 for batch in batches[-100:]: txn_count += len(batch.transactions) fmt = 'batches {}, batch/sec: {:.2f}, txns: {}, txns/sec: {:.2f}' print(fmt.format( str(i), 100 / (stop - start), str(total_txn_count), txn_count / (stop - start))) start = stop
def send_user_transactions(self, user_public_key, user_name, email_address, authorized, role, action, adprivatekey, adpublickey): self._public_key = adpublickey self._private_key = adprivatekey payload = ",".join([ user_public_key, user_name, email_address, authorized, role, action ]).encode() # Form the address address = self._get_address(user_public_key) header = TransactionHeader( signer_public_key=self._public_key, family_name="user", family_version="1.0", inputs=[address], outputs=[address], dependencies=[], # payload_encoding="csv-utf8", payload_sha512=_sha512(payload), batcher_public_key=self._public_key, nonce=time.time().hex().encode()).SerializeToString() # signature = signing.sign(header, self._private_key) signature = CryptoFactory(create_context('secp256k1')) \ .new_signer(Secp256k1PrivateKey.from_hex(self._private_key)).sign(header) transaction = Transaction(header=header, payload=payload, header_signature=signature) batch_list = self._create_batch_list([transaction]) return self._send_request( "batches", batch_list.SerializeToString(), 'application/octet-stream', )
def __init__(self, file_name): """ Args: file_name (str): The yaml filename and path. scheduler (scheduler.Scheduler): Any Scheduler implementaion context_manager (context_manager.ContextManager): The context manager holding state for this scheduler. """ self._context = create_context('secp256k1') self._crypto_factory = CryptoFactory(self._context) self._yaml_file_name = file_name self._counter = itertools.count(0) self._referenced_txns_in_other_batches = {} self._batch_id_by_txn_id = {} self._txn_execution = {} self._batch_results = {} self._batches = [] self._create_batches()
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)
def do_init(args, config): username = args.username \ if args.username else config.get('DEFAULT', 'username') url = args.url if args.url else config.get('DEFAULT', 'url') config.set('DEFAULT', 'username', username) config.set('DEFAULT', 'url', url) print("set username: %s" % username) print("set url: %s" % url) save_config(config) priv_filename = config.get('DEFAULT', 'key_file') if priv_filename.endswith(".priv"): public_key_filename = priv_filename[0:-len(".priv")] + ".pub" else: public_key_filename = priv_filename + ".pub" if not os.path.exists(priv_filename): try: if not os.path.exists(os.path.dirname(priv_filename)): os.makedirs(os.path.dirname(priv_filename)) context = create_context('secp256k1') private_key = context.new_random_private_key() public_key = context.get_public_key(private_key) with open(priv_filename, "w") as priv_fd: print("writing file: {}".format(priv_filename)) priv_fd.write(private_key.as_hex()) priv_fd.write("\n") with open(public_key_filename, "w") as public_key_fd: print("writing file: {}".format(public_key_filename)) public_key_fd.write(public_key.as_hex()) public_key_fd.write("\n") except IOError as ioe: raise BattleshipException("IOError: {}".format(str(ioe)))
def is_valid_transaction(txn): # validate transactions signature header = TransactionHeader() header.ParseFromString(txn.header) context = create_context('secp256k1') public_key = Secp256k1PublicKey.from_hex(header.signer_public_key) if not context.verify(txn.header_signature, txn.header, public_key): LOGGER.debug("transaction signature invalid for txn: %s", txn.header_signature) return False # verify the payload field matches the header txn_payload_sha512 = hashlib.sha512(txn.payload).hexdigest() if txn_payload_sha512 != header.payload_sha512: LOGGER.debug("payload doesn't match payload_sha512 of the header" "for txn: %s", txn.header_signature) return False return True
def test_authorization_challenge_submit_bad_signature(self): """ Test the AuthorizationChallengeSubmitHandler returns an AuthorizationViolation and closes the connection if the signature is not verified. """ context = create_context('secp256k1') private_key = context.new_random_private_key() crypto_factory = CryptoFactory(context) signer = crypto_factory.new_signer(private_key) payload = os.urandom(10) signature = signer.sign(payload) auth_challenge_submit = AuthorizationChallengeSubmit( public_key="other", signature=signature, roles=[RoleType.Value("NETWORK")]) roles = {"network": AuthorizationType.TRUST} network = MockNetwork( roles, connection_status={ "connection_id": ConnectionStatus.AUTH_CHALLENGE_REQUEST }) permission_verifer = MockPermissionVerifier() gossip = MockGossip() handler = AuthorizationChallengeSubmitHandler( network, permission_verifer, gossip, {"connection_id": payload}) handler_status = handler.handle( "connection_id", auth_challenge_submit.SerializeToString()) self.assertEqual(handler_status.status, HandlerStatus.RETURN_AND_CLOSE) self.assertEqual( handler_status.message_type, validator_pb2.Message.AUTHORIZATION_VIOLATION)
def test_deserialized_wait_timer(self): wait_timer = \ EnclaveWaitTimer( validator_address='1600 Pennsylvania Avenue NW', duration=3.14159, previous_certificate_id='Bond. James Bond.', local_mean=2.71828) serialized = wait_timer.serialize() private_key = self._create_random_key() wait_timer.signature = \ create_context('secp256k1').sign(serialized.encode(), private_key) copy_wait_timer = \ EnclaveWaitTimer.wait_timer_from_serialized( serialized, wait_timer.signature) self.assertEqual( wait_timer.validator_address, copy_wait_timer.validator_address) self.assertAlmostEqual( wait_timer.request_time, copy_wait_timer.request_time) self.assertAlmostEqual( wait_timer.duration, copy_wait_timer.duration) self.assertEqual( wait_timer.previous_certificate_id, copy_wait_timer.previous_certificate_id) self.assertAlmostEqual( wait_timer.local_mean, copy_wait_timer.local_mean) self.assertEqual( wait_timer.signature, copy_wait_timer.signature) self.assertEqual(serialized, copy_wait_timer.serialize())
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)
def create_chain(num=10): context = create_context('secp256k1') private_key = context.new_random_private_key() crypto_factory = CryptoFactory(context) signer = crypto_factory.new_signer(private_key) counter = 1 previous_block_id = "0000000000000000" blocks = [] while counter <= num: current_block_id = uuid4().hex txns = [ t[0] for t in [ create_transaction( payload=uuid4().hex.encode(), signer=signer) for _ in range(20) ] ] txn_ids = [t.header_signature for t in txns] batch = create_batch( transactions=txns, signer=signer) blk_w = create_block( counter, previous_block_id, current_block_id, batches=[batch]) blocks.append((current_block_id, blk_w, txn_ids)) counter += 1 previous_block_id = current_block_id return blocks