def test_sign_message(): generated_key = sgx.generate_key() key = generated_key.name account = sgx.get_account(key).address txn['nonce'] = w3.eth.getTransactionCount(account) unsigned_transaction = transactions.serializable_unsigned_transaction_from_dict( txn) transaction_hash = unsigned_transaction.hash() message = HexBytes(transaction_hash).hex() signed_message = sgx.sign_hash(message, key, None) assert signed_message.messageHash == HexBytes(message) assert len(signed_message.signature) > 2 assert type(signed_message.signature) == HexBytes recover_account = w3.eth.account.recoverHash( signed_message.messageHash, signature=signed_message.signature) assert recover_account == account encoded_transaction = transactions.encode_transaction( unsigned_transaction, vrs=(signed_message.v, signed_message.r, signed_message.s)) tx_hash = w3.eth.sendRawTransaction(encoded_transaction) assert isinstance(tx_hash, HexBytes) assert tx_hash != HexBytes('0x')
def save_hash_ethereum(file_id, file_hash): # Prepare transaction data raw_unsigned_transaction = notary.functions.setFileHash( file_id, file_hash).buildTransaction() nonce = w3.eth.getTransactionCount(card_address) logger.debug(f"Got nonce: {nonce}") raw_unsigned_transaction['nonce'] = nonce raw_unsigned_transaction['to'] = notary.address # Serialize the transaction unsigned_transaction = serializable_unsigned_transaction_from_dict( raw_unsigned_transaction) unsigned_transaction_hash = unsigned_transaction.hash() logger.debug( f"unsigned transaction hash: {unsigned_transaction_hash.hex()}") # Sign the transaction signature = card.generate_signature_der(unsigned_transaction_hash) logger.debug(f"signature: {signature.hex()}") v = web3_utils.get_v(signature, unsigned_transaction_hash, public_key, CHAIN_ID) r, s = web3_utils.sigdecode_der(signature) # logger.debug(f"r: {r}\ns: {s}") # logger.debug(f"v: {v}") encoded_transaction = encode_transaction(unsigned_transaction, vrs=(v, r, s)) tx_hash = w3.eth.sendRawTransaction(encoded_transaction) logger.debug(f"tx hash: {tx_hash.hex()}") return tx_hash.hex()
def pack_transaction(trx): global g_chain_id trx = dissoc(trx, 'from') trx = serializable_unsigned_transaction_from_dict(trx) trx = encode_transaction(trx, vrs=(g_chain_id, 0, 0)) trx = trx.hex() return trx
def serialize_and_send_tx(self, w3, transaction_dict, vrs=()): unsigned_transaction = serializable_unsigned_transaction_from_dict( transaction_dict) encoded_transaction = encode_transaction(unsigned_transaction, vrs=vrs) tx_hash = w3.eth.sendRawTransaction(HexBytes(encoded_transaction)) return tx_hash
def sign_transaction(self, raw_tx: TxParams) -> HexStr: raw_tx.pop('from', None) raw_tx['chainId'] = self._chain_id tx = serializable_unsigned_transaction_from_dict(raw_tx) tx_hash = tx.hash() self._logger.debug(f'Signing transaction hash {tx_hash.hex()}') sig = self._generate_signature(tx_hash) signed_tx = encode_transaction(tx, vrs=sig) return HexStr(signed_tx.hex())
def sign_transaction(self, raw_transaction, chain_id): transaction = serializable_unsigned_transaction_from_dict( raw_transaction) transaction_hash = transaction.hash() self.logger.debug( f'Signing transaction with hash {transaction_hash.hex()}') signature = self._generate_signature_der(transaction_hash) r, s = web3_utils.sigdecode_der(signature) v = web3_utils.get_v(r, s, transaction_hash, self.pub_key, chain_id) encoded_transaction = encode_transaction(transaction, vrs=(v, r, s)) return encoded_transaction
def parse_sign_result(cls, tx, exchange_result): sign_v = exchange_result[0] sign_r = int((exchange_result[1:1 + 32]).hex(), 16) sign_s = int((exchange_result[1 + 32:1 + 32 + 32]).hex(), 16) enctx = encode_transaction(tx, (sign_v, sign_r, sign_s)) transaction_hash = keccak(enctx) signed_txn = AttributeDict({ 'rawTransaction': HexBytes(enctx), 'hash': HexBytes(transaction_hash), 'v': sign_v, 'r': sign_r, 's': sign_s, }) return signed_txn
def _sign_transaction_dict(self, eth_key, transaction_dict): # generate RLP-serializable transaction, with defaults filled unsigned_transaction = transactions.serializable_unsigned_transaction_from_dict( transaction_dict) transaction_hash = unsigned_transaction.hash() # detect chain if isinstance(unsigned_transaction, transactions.UnsignedTransaction): chain_id = None else: chain_id = unsigned_transaction.v (v, r, s) = self._sign_hash(eth_key, transaction_hash, chain_id) # serialize transaction with rlp encoded_transaction = transactions.encode_transaction( unsigned_transaction, vrs=(v, r, s)) return v, r, s, encoded_transaction
def make_transactions_for_data(args): filepath = Path(args.deposit_data) nonce = args.start_nonce gas_price = int(args.gas_price * 10 ** 9) w3 = Web3(Web3.HTTPProvider(args.eth_rpc_endpoint)) address, abi = get_eth2_deposit_data() deposit_contract = w3.eth.contract(address=address, abi=abi) with filepath.open(mode='r') as f: deposit_data = json.loads(f.read()) v_vals = r_vals = s_vals = None if args.v is not None: v_vals = [int(x, 16) for x in args.v.split(',')] r_vals = [int(x, 16) for x in args.r.split(',')] s_vals = [int(x, 16) for x in args.s.split(',')] assert len(v_vals) == len(r_vals) == len(s_vals) transactions = [] for idx, entry in enumerate(deposit_data): tx_dict = deposit_contract.functions.deposit( entry['pubkey'], entry['withdrawal_credentials'], entry['signature'], entry['deposit_data_root'], ).buildTransaction( {'gasPrice': gas_price, 'nonce': nonce, 'value': 32000000000000000000}, ) unsigned_tx = serializable_unsigned_transaction_from_dict(tx_dict) unsigned_tx.hash() # needed to generate the rlp serialized_tx = '0x' + unsigned_tx._cached_rlp.hex() transactions.append(serialized_tx) print(f' --- Deposit {idx} - Transaction object --- ') print(tx_dict) print(f' --- Deposit {idx} - RLP encoded transaction --- ') print(serialized_tx) if v_vals and len(v_vals) >= idx + 1: signed_tx = encode_transaction(unsigned_tx, (v_vals[idx], r_vals[idx], s_vals[idx])) print(f' --- Deposit {idx} - signed transaction --- ') print('0x' + signed_tx.hex()) print('\n') nonce += 1
def sign_transaction_dict_with_eos_key(transaction_dict, chain_id, eos_pub_key): # generate RLP-serializable transaction, with defaults filled unsigned_transaction = serializable_unsigned_transaction_from_dict( transaction_dict) transaction_hash = unsigned_transaction.hash() print('transaction hash:', transaction_hash) sign = wallet.sign_digest(transaction_hash, eos_pub_key) sign = base58.b58decode(sign[7:]) print(sign) v = to_eth_v(0, chain_id + (sign[0] << 24) + 0x800000) sign = sign[1:-4] # v = chain_id + (sign[0]<<24)+0x800000 print('+++v:', v) r = int.from_bytes(sign[:32], 'big') s = int.from_bytes(sign[32:32 + 32], 'big') # serialize transaction with rlp encoded_transaction = encode_transaction(unsigned_transaction, vrs=(v, r, s)) print("++++v, r, s:", v, r, s) return encoded_transaction
def encode_signed_transaction(self, unsigned_transaction, vrs): return encode_transaction(unsigned_transaction, vrs)
def publish_evm_code(transaction, eos_pub_key=None): global g_chain_id global g_current_account global g_last_trx_ret global g_public_key # transaction['chainId'] = chain_id #Ethereum mainnet # print(transaction) sender = transaction['from'] if sender[:2] == '0x': sender = sender[2:] sender = sender.lower() logger.info(sender) a = EthAccount('helloworld11', sender) logger.info(('+++++++++sender:', sender)) nonce = a.get_nonce() assert nonce >= 0 transaction['nonce'] = nonce transaction['gasPrice'] = 0 transaction['gas'] = 20000000 if sender in keys: priv_key = key_maps[sender] encoded_transaction = Account.sign_transaction(transaction, priv_key) encoded_transaction = encoded_transaction.rawTransaction.hex()[2:] elif g_public_key: transaction = dissoc(transaction, 'from') encoded_transaction = sign_transaction_dict_with_eos_key( transaction, g_chain_id, g_public_key) # logger.info(encoded_transaction) encoded_transaction = encoded_transaction.hex() else: transaction = dissoc(transaction, 'from') unsigned_transaction = serializable_unsigned_transaction_from_dict( transaction) encoded_transaction = encode_transaction(unsigned_transaction, vrs=(g_chain_id, 0, 0)) encoded_transaction = encoded_transaction.hex() if g_current_account: account_name = g_current_account else: account_name = 'helloworld11' if g_contract_name: contract_name = g_contract_name else: contract_name = 'helloworld11' args = {'trx': encoded_transaction, 'sender': sender} ret = eosapi.push_action(contract_name, 'raw', args, {account_name: 'active'}) g_last_trx_ret = ret logs = ret['processed']['action_traces'][0]['console'] # logger.info(logs) logger.info(('++++elapsed:', ret['processed']['elapsed'])) try: logs = bytes.fromhex(logs) logs = rlp.decode(logs) # logger.info(logs) except Exception as e: logger.error(logs) raise e return logs
global_counter, counter, signature = blocksec2go.generate_signature( reader, key_id, bytes( unsigned_encoded_transaction.hash() ) ) print( "Remaining signatures with card:", global_counter ) print( f"Remaining signatures with key {key_id}:", counter ) print( "Signature (hex):" + signature.hex() ) print() # Extract r and s from the signature try: r, s = get_signature_components( signature ) except: print( "Invalid signature components!" ) raise SystemExit() # determine the signature prefix value v = get_signature_prefix( ( r, s ), inf_card_addr, bytes( unsigned_encoded_transaction.hash() ), w3.eth.chainId ) # add the signature to the encoded transaction signed_encoded_transaction = encode_transaction( unsigned_encoded_transaction, vrs=( v, r, s ) ) # send the signed, serialized transaction tx_hash = w3.eth.sendRawTransaction( signed_encoded_transaction ) print( "Sending 1 ether from Infineon card account to full node account..." ) # wait for transaction to be included on a block tx_receipt = w3.eth.waitForTransactionReceipt( tx_hash ) print() # print account balances print( f'Balance of account 0 on full node: { w3.fromWei( w3.eth.getBalance( w3.eth.accounts[0] ), "ether" ) }' ) print( f'Balance of account {key_id} on Infineon card: { w3.fromWei( w3.eth.getBalance( inf_card_addr ), "ether" ) }' ) print()