def _do_config_set(args): """Executes the 'set' subcommand. Given a key file, and a series of key/value pairs, it generates batches of sawtooth_config transactions in a BatchList instance, and stores it in a file. """ settings = [s.split('=', 1) for s in args.setting] with open(args.key, 'r') as key_file: wif_key = key_file.read().strip() signing_key = signing.encode_privkey( signing.decode_privkey(wif_key, 'wif'), 'hex') pubkey = signing.encode_pubkey( signing.generate_pubkey(signing_key), 'hex') txns = [_create_config_txn(pubkey, signing_key, setting) for setting in settings] txn_ids = [txn.header_signature for txn in txns] batch_header = BatchHeader(signer_pubkey=pubkey, transaction_ids=txn_ids).SerializeToString() batch = Batch( header=batch_header, header_signature=signing.sign(batch_header, signing_key), transactions=txns ) batch_list = BatchList(batches=[batch]).SerializeToString() try: with open(args.output, 'wb') as batch_file: batch_file.write(batch_list) except: raise CliException('Unable to write to {}'.format(args.output))
def test_register_validator_re_register(self): key = signed_object.generate_signing_key() public_key_hash = \ hashlib.sha256( signing.encode_pubkey( signing.generate_pubkey(key), 'hex').encode()).hexdigest() validator_id = signed_object.generate_identifier(key) name = 'DasValidator' signup_info = \ SignupInfo.create_signup_info( validator_address='1660 Pennsylvania Avenue NW', originator_public_key_hash=public_key_hash, most_recent_wait_certificate_id='0' * 16) store = ObjectStore() transaction = \ ValidatorRegistryTransaction.register_validator( name, validator_id, signup_info) transaction.sign_object(key) try: transaction.check_valid(store) transaction.apply(store) except InvalidTransactionError as e: self.fail('Failed valid transaction: {}'.format(e)) try: # check if valid to register again transaction.check_valid(store) except InvalidTransactionError as e: self.fail('Failure: Double registered validator: {}'.format(e))
def _do_config_set(args): """Executes the 'set' subcommand. Given a key file, and a series of key/value pairs, it generates batches of sawtooth_config transactions in a BatchList instance, and stores it in a file. """ settings = [s.split('=', 1) for s in args.setting] with open(args.key, 'r') as key_file: wif_key = key_file.read().strip() signing_key = signing.encode_privkey( signing.decode_privkey(wif_key, 'wif'), 'hex') pubkey = signing.encode_pubkey(signing.generate_pubkey(signing_key), 'hex') txns = [ _create_config_txn(pubkey, signing_key, setting) for setting in settings ] txn_ids = [txn.header_signature for txn in txns] batch_header = BatchHeader(signer_pubkey=pubkey, transaction_ids=txn_ids).SerializeToString() batch = Batch(header=batch_header, header_signature=signing.sign(batch_header, signing_key), transactions=txns) batch_list = BatchList(batches=[batch]).SerializeToString() try: with open(args.output, 'wb') as batch_file: batch_file.write(batch_list) except: raise CliException('Unable to write to {}'.format(args.output))
def test_register_validator_key_mismatch(self): key = signed_object.generate_signing_key() public_key_hash = \ hashlib.sha256( signing.encode_pubkey( signing.generate_pubkey(key), 'hex').encode()).hexdigest() key2 = signed_object.generate_signing_key() validator_id = signed_object.generate_identifier(key) name = 'DasValidator' signup_info = \ SignupInfo.create_signup_info( validator_address='1660 Pennsylvania Avenue NW', originator_public_key_hash=public_key_hash, most_recent_wait_certificate_id='0' * 16) store = ObjectStore() transaction = \ ValidatorRegistryTransaction.register_validator( name, validator_id, signup_info) transaction.sign_object(key2) with self.assertRaises(InvalidTransactionError): transaction.check_valid(store) self.fail("Failure: Verified an invalid transaction")
def __init__(self, test_name, tester): super().__init__(test_name) self.tester = tester self.private_key = signing.generate_privkey() self.public_key = signing.encode_pubkey( signing.generate_pubkey(self.private_key), "hex") self.factory = ValidatorRegistryMessageFactory( private=self.private_key, public=self.public_key) self._report_private_key = \ signing.encode_privkey( signing.decode_privkey( '5Jz5Kaiy3kCiHE537uXcQnJuiNJshf2bZZn43CrALMGoCd3zRuo', 'wif'), 'hex')
def _sign_block(self, block): """ The block should be complete and the final signature from the publishing validator (this validator) needs to be added. """ public_key = signing.encode_pubkey( signing.generate_pubkey(self._identity_priv_key), "hex") block.block_header.signer_pubkey = public_key block_header = block.block_header header_bytes = block_header.SerializeToString() signature = signing.sign( header_bytes, self._identity_priv_key) block.set_signature(signature) return block
def register_signup_information(self, journal): wait_certificate_id = journal.most_recent_committed_block_id public_key_hash = \ hashlib.sha256( signing.encode_pubkey(journal.local_node.public_key(), 'hex')).hexdigest() signup_info = \ SignupInfo.create_signup_info( validator_address=journal.local_node.signing_address(), originator_public_key_hash=public_key_hash, most_recent_wait_certificate_id=wait_certificate_id) # Save off the sealed signup data and cache the PoET public key journal.local_store.set( 'sealed_signup_data', signup_info.sealed_signup_data) journal.local_store.sync() self.poet_public_key = signup_info.poet_public_key LOGGER.debug( 'Register %s (%s)', journal.local_node.Name, journal.local_node.Identifier) # Create a validator register transaction and sign it. Wrap # the transaction in a message. Broadcast it to out. transaction = \ val_reg.ValidatorRegistryTransaction.register_validator( journal.local_node.Name, journal.local_node.Identifier, signup_info) transaction.sign_from_node(journal.local_node) message = \ val_reg.ValidatorRegistryTransactionMessage() message.Transaction = transaction LOGGER.info( 'Advertise PoET 1 validator %s (ID = %s) has PoET public key ' '%s', journal.local_node.Name, journal.local_node.Identifier, signup_info.poet_public_key) journal.gossip.broadcast_message(message)
def _sign_block(block): """ The block should be complete and the final signature from the publishing validator (this validator) needs to be added. """ temp_key = signing.generate_privkey() public_key = signing.encode_pubkey( signing.generate_pubkey(temp_key), "hex") block.block_header.signer_pubkey = public_key block_header = block.block_header header_bytes = block_header.SerializeToString() signature = signing.sign( header_bytes, temp_key) block.set_signature(signature) return block
def __init__(self): self.block_sender = MockBlockSender() self.block_store = BlockStoreAdapter({}) self.block_cache = BlockCache(self.block_store) self.signing_key = signing.generate_privkey() self.public_key = signing.encode_pubkey( signing.generate_pubkey(self.signing_key), "hex") self.genesis_block = self._generate_genesis_block() self.block_store[self.genesis_block.identifier] = self.genesis_block self.set_chain_head(self.genesis_block) self.block_publisher = BlockPublisher( consensus=TestModePublisher(), transaction_executor=MockTransactionExecutor(), block_sender=self.block_sender, squash_handler=None, chain_head=self.genesis_block)
def check_valid(self, store, txn): """Determines if the update is valid. Check policy on each element of validator_name, validator_id, and signup_info Args: store (Store): Transaction store. txn (Transaction): Transaction encompassing this update. """ LOGGER.debug('check update %s from %s', str(self), self.validator_id) # Check name if not self.is_valid_name(): raise InvalidTransactionError( 'Illegal validator name {}'.format(self.validator_name[:64])) # Check registering validator matches transaction signer. if self.validator_id != txn.OriginatorID: raise InvalidTransactionError( 'Signature mismatch on validator registration with validator' ' {} signed by {}'.format(self.validator_id, txn.OriginatorID)) # Nothing to check for anti_sybil_id # Apply will invalidate any previous entries for this anti_sybil_id # and create a new entry. try: public_key_hash = \ hashlib.sha256( signing.encode_pubkey( txn.originator_public_key, 'hex').encode()).hexdigest() self.signup_info.check_valid( originator_public_key_hash=public_key_hash, most_recent_wait_certificate_id='0' * 16) except ValueError as error: raise InvalidTransactionError( 'Invalid Signup Info: {0}, Reason: {1}'.format( self.signup_info, error)) return True
def test_is_valid_pub_key(self): pubkey = signing.generate_pubkey("5KQ4iQQGgbQX9MmfiPUwwHBL1R" "GPa86NwFbqrWoodjuzruqFVDd") pub = signing.encode_pubkey(pubkey, "hex") minfo = {'Nonce': 100, 'PublicKey': pub, 'TransactionType': '/Transaction', 'Dependencies': []} sig = signing.sign( signed_object.dict2cbor(minfo), "5KQ4iQQGgbQX9MmfiPUwwHBL1RGPa86NwFbqrWoodjuzruqFVDd" ) # Create valid transaction minfo["Signature"] = sig temp = Transaction(minfo) self.assertTrue(temp.is_valid("unused")) # Change transaction after it was signed minfo["Nonce"] = time.time() temp = Transaction(minfo) self.assertFalse(temp.is_valid("unused"))
def register_signup_information(self, journal): wait_certificate_id = journal.most_recent_committed_block_id public_key_hash = \ hashlib.sha256( signing.encode_pubkey(journal.local_node.public_key(), 'hex')).hexdigest() signup_info = \ SignupInfo.create_signup_info( validator_address=journal.local_node.signing_address(), originator_public_key_hash=public_key_hash, most_recent_wait_certificate_id=wait_certificate_id) # Save off the sealed signup data and cache the PoET public key journal.local_store.set('sealed_signup_data', signup_info.sealed_signup_data) journal.local_store.sync() self.poet_public_key = signup_info.poet_public_key LOGGER.debug('Register %s (%s)', journal.local_node.Name, journal.local_node.Identifier) # Create a validator register transaction and sign it. Wrap # the transaction in a message. Broadcast it to out. transaction = \ val_reg.ValidatorRegistryTransaction.register_validator( journal.local_node.Name, journal.local_node.Identifier, signup_info) transaction.sign_from_node(journal.local_node) message = \ val_reg.ValidatorRegistryTransactionMessage() message.Transaction = transaction LOGGER.info( 'Advertise PoET 1 validator %s (ID = %s) has PoET public key ' '%s', journal.local_node.Name, journal.local_node.Identifier, signup_info.poet_public_key) journal.gossip.broadcast_message(message)
def test_is_valid_pub_key(self): pubkey = signing.generate_pubkey("5KQ4iQQGgbQX9MmfiPUwwHBL1R" "GPa86NwFbqrWoodjuzruqFVDd") pub = signing.encode_pubkey(pubkey, "hex") minfo = { 'Nonce': 100, 'PublicKey': pub, 'TransactionType': '/Transaction', 'Dependencies': [] } sig = signing.sign( signed_object.dict2cbor(minfo), "5KQ4iQQGgbQX9MmfiPUwwHBL1RGPa86NwFbqrWoodjuzruqFVDd") # Create valid transaction minfo["Signature"] = sig temp = Transaction(minfo) self.assertTrue(temp.is_valid("unused")) # Change transaction after it was signed minfo["Nonce"] = time.time() temp = Transaction(minfo) self.assertFalse(temp.is_valid("unused"))
def _sign_message_with_transaction(transaction, message_type, key): """ Signs a transaction message or transaction :param transaction (dict): :param key (str): A signing key returns message, txnid (tuple): The first 16 characters of a sha256 hexdigest. """ transaction['Nonce'] = time.time() pub = signing.encode_pubkey(signing.generate_pubkey(key), "hex") transaction["PublicKey"] = pub sig = signing.sign(_dict2cbor(transaction), key) transaction['Signature'] = sig txnid = hashlib.sha256(transaction['Signature'].encode()).hexdigest()[:16] message = { 'Transaction': transaction, '__TYPE__': message_type, '__NONCE__': time.time(), } cbor_serialized_message = _dict2cbor(message) signature = signing.sign(cbor_serialized_message, key) message['__SIGNATURE__'] = signature return message, txnid
def create_signup_info(self, originator_public_key_hash, most_recent_wait_certificate_id): # First we need to create a public/private key pair for the PoET # enclave to use. _poet_private_key = \ "1f70fa2518077ad18483f48e77882d11983b537fa5f7cf158684d2c670fe4f1f" _poet_public_key = \ signing.generate_pubkey(_poet_private_key) # currently not used # _active_wait_timer = None _report_private_key = \ signing.encode_privkey( signing.decode_privkey( '5Jz5Kaiy3kCiHE537uXcQnJuiNJshf2bZZn43CrALMGoCd3zRuo', 'wif'), 'hex') # We are going to fake out the sealing the signup data. signup_data = { 'poet_public_key': signing.encode_pubkey(_poet_public_key, 'hex'), 'poet_private_key': signing.encode_privkey(_poet_private_key, 'hex') } # Create a fake report report_data = '{0}{1}'.format( originator_public_key_hash.upper(), signing.encode_pubkey(_poet_public_key, 'hex').upper()) quote = { 'report_body': hashlib.sha256(json.dumps(report_data).encode()).hexdigest() } # Fake our "proof" data. verification_report = { 'id': base64.b64encode( bytes( hashlib.sha256(b'2017-02-16T15:21:24.437048').hexdigest(). encode())).decode(), 'isvEnclaveQuoteStatus': 'OK', 'isvEnclaveQuoteBody': base64.b64encode(json.dumps(quote).encode()).decode(), 'pseManifestStatus': 'OK', 'pseManifestHash': base64.b64encode( hashlib.sha256( bytes( b'Do you believe in ' b'manifest destiny?')).hexdigest().encode()).decode(), 'nonce': most_recent_wait_certificate_id } proof_data_dict = { 'verification_report': json.dumps(verification_report), 'signature': signing.sign(json.dumps(verification_report), _report_private_key) } proof_data = json.dumps(proof_data_dict) return \ SignUpInfo( poet_public_key=signup_data['poet_public_key'], proof_data=proof_data, anti_sybil_id=originator_public_key_hash)
def setUp(self): self.private_key = signing.generate_privkey() self.public_key = signing.encode_pubkey( signing.generate_pubkey(self.private_key), "hex")
def create_random_public_key_hash(): return \ hashlib.sha256( signing.encode_pubkey( create_random_public_key(), 'hex')).hexdigest()
def create_signup_info(cls, originator_public_key_hash, most_recent_wait_certificate_id): with cls._lock: # First we need to create a public/private key pair for the PoET # enclave to use. cls._poet_private_key = signing.generate_privkey() cls._poet_public_key = \ signing.generate_pubkey(cls._poet_private_key) cls._active_wait_timer = None # We are going to fake out the sealing the signup data. signup_data = { 'poet_public_key': signing.encode_pubkey(cls._poet_public_key, 'hex'), 'poet_private_key': signing.encode_privkey( cls._poet_private_key, 'hex') } sealed_signup_data = \ base64.b64encode(bytes(dict2json(signup_data).encode())) # Create a fake report report_data = '{0}{1}'.format( originator_public_key_hash.upper(), signing.encode_pubkey( cls._poet_public_key, 'hex').upper() ) quote = { 'report_body': hashlib.sha256( dict2json(report_data).encode()).hexdigest() } # Fake our "proof" data. verification_report = { 'id': base64.b64encode( bytes(hashlib.sha256( datetime.datetime.now().isoformat().encode()) .hexdigest().encode())).decode(), 'isvEnclaveQuoteStatus': 'OK', 'isvEnclaveQuoteBody': base64.b64encode( dict2json(quote).encode()).decode(), 'pseManifestStatus': 'OK', 'pseManifestHash': base64.b64encode( hashlib.sha256( bytes(b'Do you believe in ' b'manifest destiny?')).hexdigest() .encode()).decode(), 'nonce': most_recent_wait_certificate_id } proof_data_dict = { 'verification_report': dict2json(verification_report), 'signature': signing.sign( dict2json(verification_report), cls._report_private_key) } proof_data = dict2json(proof_data_dict) return \ EnclaveSignupInfo( poet_public_key=signup_data['poet_public_key'], proof_data=proof_data, anti_sybil_id=originator_public_key_hash, sealed_signup_data=sealed_signup_data)
def create_signup_info(cls, originator_public_key_hash, most_recent_wait_certificate_id): with cls._lock: # First we need to create a public/private key pair for the PoET # enclave to use. cls._poet_private_key = signing.generate_privkey() cls._poet_public_key = \ signing.generate_pubkey(cls._poet_private_key) cls._active_wait_timer = None # We are going to fake out the sealing the signup data. signup_data = { 'poet_public_key': signing.encode_pubkey(cls._poet_public_key, 'hex'), 'poet_private_key': signing.encode_privkey(cls._poet_private_key, 'hex') } sealed_signup_data = \ base64.b64encode(bytes(dict2json(signup_data).encode())) # Create a fake report report_data = '{0}{1}'.format( originator_public_key_hash.upper(), signing.encode_pubkey(cls._poet_public_key, 'hex').upper()) quote = { 'report_body': hashlib.sha256(dict2json(report_data).encode()).hexdigest() } # Fake our "proof" data. verification_report = { 'id': base64.b64encode( bytes( hashlib.sha256(datetime.datetime.now().isoformat( ).encode()).hexdigest().encode())).decode(), 'isvEnclaveQuoteStatus': 'OK', 'isvEnclaveQuoteBody': base64.b64encode(dict2json(quote).encode()).decode(), 'pseManifestStatus': 'OK', 'pseManifestHash': base64.b64encode( hashlib.sha256( bytes(b'Do you believe in ' b'manifest destiny?')).hexdigest().encode()). decode(), 'nonce': most_recent_wait_certificate_id } proof_data_dict = { 'verification_report': dict2json(verification_report), 'signature': signing.sign(dict2json(verification_report), cls._report_private_key) } proof_data = dict2json(proof_data_dict) return \ EnclaveSignupInfo( poet_public_key=signup_data['poet_public_key'], proof_data=proof_data, anti_sybil_id=originator_public_key_hash, sealed_signup_data=sealed_signup_data)