Skip to content

Instantly share code, notes, and snippets.

@kdembler
Created June 9, 2020 21:44
Show Gist options
  • Save kdembler/6d1d6c2990ed1d4a89f8654e81f64adf to your computer and use it in GitHub Desktop.
Save kdembler/6d1d6c2990ed1d4a89f8654e81f64adf to your computer and use it in GitHub Desktop.
import blocksec2go
import ecdsa
from eth_account._utils.transactions import serializable_unsigned_transaction_from_dict, encode_transaction
from web3 import Web3
from utils import get_reader, public_key_to_address, get_web3, find_recovery_key_id
key_id = 1
# initialize blocksec2go and web3
reader = get_reader()
blocksec2go.select_app(reader)
web3 = get_web3()
# read the public key and generate the account address
_, _, public_key = blocksec2go.get_key_info(reader, key_id)
address = public_key_to_address(public_key)
# prepare the transaction
transaction = {
'to': Web3.toChecksumAddress('0x4d6bb4ed029b33cf25d0810b029bd8b1a6bcab7b'),
'gas': 21000,
'gasPrice': 10000000000,
'value': 1,
'nonce': web3.eth.getTransactionCount(address),
'chainId': 42,
}
serializable_transaction = serializable_unsigned_transaction_from_dict(transaction)
transaction_hash = serializable_transaction.hash()
# sign the transaction hash and calculate v value
_, _, signature = blocksec2go.generate_signature(reader, key_id, transaction_hash)
r, s = ecdsa.util.sigdecode_der(signature, ecdsa.SECP256k1.generator.order())
recovery_key_id = find_recovery_key_id(r, s, transaction_hash, public_key)
v = 35 + recovery_key_id + (web3.eth.chainId * 2)
# encode the transaction along with the full signature and send it
encoded_transaction = encode_transaction(serializable_transaction, vrs=(v, r, s))
web3.eth.sendRawTransaction(encoded_transaction)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment