def send_obj_transaction(obj, data, to_address, pri_key, transaction_cfg: dict): transaction_dict = {} if transaction_cfg is None: transaction_cfg = {} if transaction_cfg.get("gasPrice", None) is None: transaction_dict["gasPrice"] = obj.web3.platon.gasPrice else: transaction_dict["gasPrice"] = transaction_cfg["gasPrice"] if transaction_cfg.get("nonce", None) is None: raw_from_address = PrivateKey(bytes.fromhex(pri_key)).public_key.to_address() from_address = obj.web3.toChecksumAddress(raw_from_address) transaction_dict["nonce"] = obj.web3.platon.getTransactionCount(from_address) else: transaction_dict["nonce"] = transaction_cfg["nonce"] if transaction_cfg.get("gas", None) is None: raw_from_address = PrivateKey(bytes.fromhex(pri_key)).public_key.to_address() from_address = obj.web3.toChecksumAddress(raw_from_address) transaction_data = {"to": to_address, "data": data, "from": from_address} transaction_dict["gas"] = obj.web3.platon.estimateGas(transaction_data) else: transaction_dict["gas"] = transaction_cfg["gas"] transaction_dict["chainId"] = obj.web3.chainId transaction_dict["to"] = to_address transaction_dict["data"] = data if transaction_cfg.get("value", 0) > 0: transaction_dict["value"] = int(transaction_cfg.get("value", 0)) signed_transaction_dict = obj.web3.platon.account.signTransaction( transaction_dict, pri_key ) signed_data = signed_transaction_dict.rawTransaction tx_hash = HexBytes(obj.web3.platon.sendRawTransaction(signed_data)).hex() if obj.need_analyze: return obj.web3.platon.analyzeReceiptByHash(tx_hash) return tx_hash
def test_session_key_derivation(initiator_private_key, recipient_private_key, id_nonce): initiator_private_key_object = PrivateKey(initiator_private_key) recipient_private_key_object = PrivateKey(recipient_private_key) initiator_public_key = initiator_private_key_object.public_key.to_compressed_bytes() recipient_public_key = recipient_private_key_object.public_key.to_compressed_bytes() initiator_node_id = keccak(initiator_private_key_object.public_key.to_bytes()) recipient_node_id = keccak(recipient_private_key_object.public_key.to_bytes()) initiator_session_keys = V4IdentityScheme.compute_session_keys( local_private_key=initiator_private_key, remote_public_key=recipient_public_key, local_node_id=initiator_node_id, remote_node_id=recipient_node_id, id_nonce=id_nonce, is_locally_initiated=True, ) recipient_session_keys = V4IdentityScheme.compute_session_keys( local_private_key=recipient_private_key, remote_public_key=initiator_public_key, local_node_id=recipient_node_id, remote_node_id=initiator_node_id, id_nonce=id_nonce, is_locally_initiated=False, ) assert initiator_session_keys.auth_response_key == recipient_session_keys.auth_response_key assert initiator_session_keys.encryption_key == recipient_session_keys.decryption_key assert initiator_session_keys.decryption_key == recipient_session_keys.encryption_key
def test_valid_id_nonce_signature_validation( private_key, iv, header, who_are_you, ephemeral_key, recipient_node_id, ): ephemeral_public_key = PrivateKey(ephemeral_key).public_key.to_bytes() signature = V4HandshakeScheme.create_id_nonce_signature( signature_inputs=SignatureInputs( iv=iv, header=header, who_are_you=who_are_you, ephemeral_public_key=ephemeral_public_key, recipient_node_id=recipient_node_id, ), private_key=private_key, ) public_key = PrivateKey(private_key).public_key.to_compressed_bytes() V4HandshakeScheme.validate_id_nonce_signature( signature_inputs=SignatureInputs(iv, header, who_are_you, ephemeral_public_key, recipient_node_id), signature=signature, public_key=public_key, )
def test_invalid_id_nonce_signature_validation(): id_nonce = b"\xff" * 10 private_key = b"\x11" * 32 signature = V4IdentityScheme.create_id_nonce_signature( id_nonce=id_nonce, private_key=private_key, ) public_key = PrivateKey(private_key).public_key.to_compressed_bytes() different_public_key = PrivateKey(b"\x22" * 32).public_key.to_compressed_bytes() different_id_nonce = b"\x00" * 10 assert different_public_key != public_key assert different_id_nonce != id_nonce with pytest.raises(ValidationError): V4IdentityScheme.validate_id_nonce_signature( id_nonce=id_nonce, signature=signature, public_key=different_public_key, ) with pytest.raises(ValidationError): V4IdentityScheme.validate_id_nonce_signature( id_nonce=different_id_nonce, signature=signature, public_key=public_key, )
async def get_local_enr(boot_info: BootInfo, node_db: NodeDBAPI, local_private_key: PrivateKey) -> ENR: minimal_enr = UnsignedENR( sequence_number=1, kv_pairs={ b"id": b"v4", b"secp256k1": local_private_key.public_key.to_compressed_bytes(), b"udp": boot_info.args.discovery_port, }, identity_scheme_registry=default_identity_scheme_registry, ).to_signed_enr(local_private_key.to_bytes()) node_id = minimal_enr.node_id try: base_enr = node_db.get_enr(node_id) except KeyError: logger.info( f"No Node for {encode_hex(node_id)} found, creating new one") return minimal_enr else: if any(base_enr[key] != value for key, value in minimal_enr.items()): logger.debug(f"Updating local ENR") return UnsignedENR( sequence_number=base_enr.sequence_number + 1, kv_pairs=merge(dict(base_enr), dict(minimal_enr)), identity_scheme_registry=default_identity_scheme_registry, ).to_signed_enr(local_private_key.to_bytes()) else: return base_enr
def create_id_nonce_signature( cls, *, id_nonce: IDNonce, private_key: bytes, ) -> bytes: private_key_object = PrivateKey(private_key) signature = private_key_object.sign_msg_non_recoverable(id_nonce) return bytes(signature)
def create_id_nonce_signature(cls, *, id_nonce: IDNonce, ephemeral_public_key: bytes, private_key: bytes) -> bytes: private_key_object = PrivateKey(private_key) signature_input = cls.create_id_nonce_signature_input( id_nonce=id_nonce, ephemeral_public_key=ephemeral_public_key) signature = private_key_object.sign_msg_hash_non_recoverable( signature_input) return bytes(signature)
def test_id_nonce_signing(private_key, id_nonce, ephemeral_key): ephemeral_public_key = PrivateKey(ephemeral_key).public_key.to_bytes() signature = V4IdentityScheme.create_id_nonce_signature( id_nonce=id_nonce, private_key=private_key, ephemeral_public_key=ephemeral_public_key, ) signature_object = NonRecoverableSignature(signature) message_hash = sha256(ID_NONCE_SIGNATURE_PREFIX + id_nonce + ephemeral_public_key).digest() assert signature_object.verify_msg_hash(message_hash, PrivateKey(private_key).public_key)
def sign(data: bytes, private_key_seed_ascii: str, hash_function=sha256_msg): """Sign data using Ethereum private key. :param private_key_seed_ascii: Private key seed as ASCII string """ priv_key = PrivateKey(Web3.sha3(text=private_key_seed_ascii)) msghash = hash_function(data) signature = priv_key.sign_msg_hash(msghash) v, r, s = signature.vrs # assuming chainID is 1 i.e the main net # TODO: take in chainID as a param, so that v is set appropriately # currently there's no good way to determine chainID v = to_eth_v(v) r_bytes = to_bytes(r) s_bytes = to_bytes(s) # Make sure we use bytes data and zero padding stays # good across different systems r_hex = binascii.hexlify(r_bytes).decode("ascii") s_hex = binascii.hexlify(s_bytes).decode("ascii") # Convert to Etheruem address format pub_key = priv_key.public_key addr = pub_key.to_checksum_address() pub = pub_key.to_bytes() # # Return various bits about signing so it's easier to debug return { "signature": signature, "v": v, "r": r, "s": s, "r_bytes": r_bytes, "s_bytes": s_bytes, "r_hex": "0x" + r_hex, "s_hex": "0x" + s_hex, "address_bitcoin": addr, "address_ethereum": get_ethereum_address_from_private_key(private_key_seed_ascii), "public_key": pub, "hash": msghash, "payload": binascii.hexlify(bytes([v] + list(r_bytes) + list(s_bytes, ))) }
def test_enr_signing(): private_key = PrivateKey(b"\x11" * 32) unsigned_enr = UnsignedENR(0, { b"id": b"v4", b"secp256k1": private_key.public_key.to_compressed_bytes(), b"key1": b"value1", }) signature = V4IdentityScheme.create_enr_signature(unsigned_enr, private_key.to_bytes()) message_hash = keccak(unsigned_enr.get_signing_message()) assert private_key.public_key.verify_msg_hash(message_hash, NonRecoverableSignature(signature))
def test_enr_node_id(): private_key = PrivateKey(b"\x11" * 32) unsigned_enr = UnsignedENR(0, { b"id": b"v4", b"secp256k1": private_key.public_key.to_compressed_bytes(), b"key1": b"value1", }) enr = unsigned_enr.to_signed_enr(private_key.to_bytes()) node_id = V4IdentityScheme.extract_node_id(enr) assert node_id == keccak(private_key.public_key.to_bytes())
def sign(self, key_bytes): key = PrivateKey(key_bytes) content = self.build_message(key.public_key) result = { 'author': key.public_key.to_checksum_address(), 'raw_transaction': content, 'signature': key.sign_msg_hash(Web3.keccak(text=content)), } # very confused where this data goes, but trying this for now result.update(self.content) return result
def test_enr_public_key(): private_key = PrivateKey(b"\x11" * 32) public_key = private_key.public_key.to_compressed_bytes() unsigned_enr = UnsignedENR(0, { b"id": b"v4", b"secp256k1": public_key, b"key1": b"value1", }) enr = unsigned_enr.to_signed_enr(private_key.to_bytes()) assert V4IdentityScheme.extract_public_key(unsigned_enr) == public_key assert V4IdentityScheme.extract_public_key(enr) == public_key
def create_id_nonce_signature( cls, *, signature_inputs: SignatureInputs, private_key: bytes, ) -> bytes: private_key_object = PrivateKey(private_key) signature_input = cls.create_id_nonce_signature_input( signature_inputs=signature_inputs) signature = private_key_object.sign_msg_hash_non_recoverable( signature_input) return bytes(signature)
def _resolve_node_key(trinity_config: TrinityConfig, nodekey_seed: Optional[str]) -> PrivateKey: if nodekey_seed: private_key_bytes = hashlib.sha256(nodekey_seed.encode()).digest() nodekey = PrivateKey(private_key_bytes) trinity_config.nodekey = nodekey return if trinity_config.nodekey is None: nodekey = ecies.generate_privkey() with open(trinity_config.nodekey_path, 'wb') as nodekey_file: nodekey_file.write(nodekey.to_bytes()) trinity_config.nodekey = nodekey
def test_valid_id_nonce_signature_validation(private_key, id_nonce, ephemeral_key): ephemeral_public_key = PrivateKey(ephemeral_key).public_key.to_bytes() signature = V4HandshakeScheme.create_id_nonce_signature( signature_inputs=SignatureInputs(id_nonce, ephemeral_public_key), private_key=private_key, ) public_key = PrivateKey(private_key).public_key.to_compressed_bytes() V4HandshakeScheme.validate_id_nonce_signature( signature_inputs=SignatureInputs(id_nonce, ephemeral_public_key), signature=signature, public_key=public_key, )
def init(): if os.path.exists('key'): try: with open('key', 'rb') as f: eth_k = PrivateKey(f.read()) return eth_k except Exception as e: print('55', e) pass eth_k = generate_eth_key() with open('key', 'wb') as f: f.write(eth_k.to_bytes()) return eth_k
def test_valid_id_nonce_signature_validation(private_key, id_nonce, ephemeral_key): ephemeral_public_key = PrivateKey(ephemeral_key).public_key.to_bytes() signature = V4IdentityScheme.create_id_nonce_signature( id_nonce=id_nonce, private_key=private_key, ephemeral_public_key=ephemeral_public_key, ) public_key = PrivateKey(private_key).public_key.to_compressed_bytes() V4IdentityScheme.validate_id_nonce_signature( id_nonce=id_nonce, ephemeral_public_key=ephemeral_public_key, signature=signature, public_key=public_key, )
def test_enr_signature_validation(): private_key = PrivateKey(b"\x11" * 32) unsigned_enr = UnsignedENR(0, { b"id": b"v4", b"secp256k1": private_key.public_key.to_compressed_bytes(), b"key1": b"value1", }) enr = unsigned_enr.to_signed_enr(private_key.to_bytes()) V4IdentityScheme.validate_enr_signature(enr) forged_enr = ENR(enr.sequence_number, dict(enr), b"\x00" * 64) with pytest.raises(ValidationError): V4IdentityScheme.validate_enr_signature(forged_enr)
def test_id_nonce_signing(private_key, iv, header, who_are_you, ephemeral_key, recipient_node_id): ephemeral_public_key = PrivateKey(ephemeral_key).public_key.to_bytes() signature = V4HandshakeScheme.create_id_nonce_signature( signature_inputs=SignatureInputs(iv, header, who_are_you, ephemeral_public_key, recipient_node_id), private_key=private_key, ) signature_object = NonRecoverableSignature(signature) message_hash = sha256(ID_NONCE_SIGNATURE_PREFIX + iv + header.to_wire_bytes() + who_are_you.to_wire_bytes() + ephemeral_public_key + recipient_node_id).digest() assert signature_object.verify_msg_hash(message_hash, PrivateKey(private_key).public_key)
def get_local_private_key(boot_info: BootInfo) -> PrivateKey: if boot_info.args.discovery_private_key: local_private_key_bytes = decode_hex( boot_info.args.discovery_private_key) return PrivateKey(local_private_key_bytes) else: return boot_info.trinity_config.nodekey
def get_local_private_key(boot_info: BootInfo) -> PrivateKey: if boot_info.args.discovery_private_key: local_private_key_bytes = decode_hex(boot_info.args.discovery_private_key) else: logger.debug("No private key given, using random one") local_private_key_bytes = secrets.token_bytes(32) return PrivateKey(local_private_key_bytes)
def accounts(): _accounts = [] for i in range(1, 11): pk = PrivateKey(i.to_bytes(32, byteorder='big')) _accounts.append( EthereumAccount(pk.public_key.to_checksum_address(), pk)) return _accounts
def __init__( self, transfer_event_queue: Queue, home_bridge_contract: Contract, private_key: bytes, gas_price: int, max_reorg_depth: int, ): self.logger = logging.getLogger( "bridge.confirmation_sender.ConfirmationSender") self.private_key = private_key self.address = PrivateKey( self.private_key).public_key.to_canonical_address() if not is_bridge_validator(home_bridge_contract, self.address): self.logger.warning( f"The address {self.address} is not a bridge validator to confirm " f"transfers on the home bridge contract!") self.transfer_event_queue = transfer_event_queue self.home_bridge_contract = home_bridge_contract self.gas_price = gas_price self.max_reorg_depth = max_reorg_depth self.w3 = self.home_bridge_contract.web3 self.pending_transaction_queue: Queue[Dict[str, Any]] = Queue()
def test_id_nonce_signing(private_key, id_nonce): signature = V4IdentityScheme.create_id_nonce_signature( id_nonce=id_nonce, private_key=private_key, ) signature_object = NonRecoverableSignature(signature) assert signature_object.verify_msg(id_nonce, PrivateKey(private_key).public_key)
def _pack_v5(cmd_id: int, payload: Tuple[Any, ...], privkey: datatypes.PrivateKey) -> bytes: """Create and sign a discovery v5 UDP message to be sent to a remote node.""" cmd_id = to_bytes(cmd_id) encoded_data = cmd_id + rlp.encode(payload) signature = privkey.sign_msg(encoded_data) return signature.to_bytes() + encoded_data
def test_recover_when_computed(ethereum_accounts): # Must be a string exact match data = { 'name': 'polyswarmtransaction.transaction:Transaction', 'from': '0x3f17f1962B36e491b30A40b2405849e597Ba5FB5', 'data': {} } signed = Transaction().sign(ethereum_accounts[0].key) assert signed.signature == PrivateKey(ethereum_accounts[0].key).sign_msg_hash(Web3.keccak(text=json.dumps(data)))
def enr(): return ENR(sequence_number=1, signature=b"", kv_pairs={ b"id": b"v4", b"secp256k1": PrivateKey(b"\x01" * 32).public_key.to_compressed_bytes(), })
def ecdsa_sign(self, msg_hash: bytes, private_key: PrivateKey) -> Signature: private_key_bytes = private_key.to_bytes() signature_bytes = self.keys.PrivateKey( private_key_bytes).sign_recoverable( msg_hash, hasher=None, ) signature = Signature(signature_bytes, backend=self) return signature
def load_key(private_key: Union[HexBytes, PrivateKey]) -> PrivateKey: if isinstance(private_key, PrivateKey): # Lifts the need to convert to bytes and back to PrivateKey return private_key try: return PrivateKey(private_key) except ValidationError: raise exceptions.InvalidKeyError( f'{private_key} is not a valid ethereum private key')