Rename package

This commit is contained in:
nolash
2021-02-11 08:45:26 +01:00
parent 52426078be
commit 62123850c8
21 changed files with 31 additions and 268 deletions

27
chainlib/eth/address.py Normal file
View File

@@ -0,0 +1,27 @@
# third-party imports
import sha3
from hexathon import (
strip_0x,
uniform,
)
def to_checksum(address_hex):
address_hex = strip_0x(address_hex)
address_hex = uniform(address_hex)
h = sha3.keccak_256()
h.update(address_hex.encode('utf-8'))
z = h.digest()
checksum_address_hex = '0x'
for (i, c) in enumerate(address_hex):
if c in '1234567890':
checksum_address_hex += c
elif c in 'abcdef':
if z[int(i / 2)] & (0x80 >> ((i % 2) * 4)) > 1:
checksum_address_hex += c.upper()
else:
checksum_address_hex += c
return checksum_address_hex

21
chainlib/eth/block.py Normal file
View File

@@ -0,0 +1,21 @@
from cic_tools.eth.rpc import jsonrpc_template
def block(self):
o = jsonrpc_template()
o['method'] = 'eth_blockNumber'
return o
def block_by_hash(self, hsh):
o = jsonrpc_template()
o['method'] = 'eth_getBlock'
o['params'].append(hsh)
return o
def block_by_number(self, n):
o = jsonrpc_template()
o['method'] = 'eth_getBlock'
o['params'].append(n)
return o

View File

@@ -0,0 +1,80 @@
# standard imports
import logging
import json
import datetime
import time
from urllib.request import (
Request,
urlopen,
)
# third-party imports
from hexathon import (
add_0x,
strip_0x,
)
# local imports
from .error import (
DefaultErrorParser,
RevertEthException,
)
from .rpc import (
jsonrpc_template,
jsonrpc_result,
)
error_parser = DefaultErrorParser()
logg = logging.getLogger(__name__)
class HTTPConnection:
def __init__(self, url):
self.url = url
def do(self, o, error_parser=error_parser):
req = Request(
self.url,
method='POST',
)
req.add_header('Content-Type', 'application/json')
data = json.dumps(o)
logg.debug('(HTTP) send {}'.format(data))
res = urlopen(req, data=data.encode('utf-8'))
o = json.load(res)
return jsonrpc_result(o, error_parser)
def wait(self, tx_hash_hex, delay=0.5, timeout=0.0):
t = datetime.datetime.utcnow()
i = 0
while True:
o = jsonrpc_template()
o['method'] ='eth_getTransactionReceipt'
o['params'].append(add_0x(tx_hash_hex))
req = Request(
self.url,
method='POST',
)
req.add_header('Content-Type', 'application/json')
data = json.dumps(o)
logg.debug('(HTTP) receipt attempt {} {}'.format(i, data))
res = urlopen(req, data=data.encode('utf-8'))
r = json.load(res)
e = jsonrpc_result(r, error_parser)
if e != None:
logg.debug('e {}'.format(strip_0x(e['status'])))
if strip_0x(e['status']) == '00':
raise RevertEthException(tx_hash_hex)
return e
if timeout > 0.0:
delta = (datetime.datetime.utcnow() - t) + datetime.timedelta(seconds=delay)
if delta.total_seconds() >= timeout:
raise TimeoutError(tx_hash)
time.sleep(delay)
i += 1

4
chainlib/eth/constant.py Normal file
View File

@@ -0,0 +1,4 @@
ZERO_ADDRESS = '0x{:040x}'.format(0)
ZERO_CONTENT = '0x{:064x}'.format(0)
MINIMUM_FEE_UNITS = 21000
MINIMUM_FEE_PRICE = 1000000000

70
chainlib/eth/erc20.py Normal file
View File

@@ -0,0 +1,70 @@
# third-party imports
import sha3
from hexathon import add_0x
from eth_abi import encode_single
from crypto_dev_signer.eth.transaction import EIP155Transaction
# local imports
from .hash import (
keccak256_hex_to_hex,
keccak256_string_to_hex,
)
from .constant import ZERO_ADDRESS
from .rpc import jsonrpc_template
from .tx import TxFactory
# TODO: move to cic-contracts
erc20_balance_signature = keccak256_string_to_hex('balanceOf(address)')[:8]
erc20_decimals_signature = keccak256_string_to_hex('decimals()')[:8]
erc20_transfer_signature = keccak256_string_to_hex('transfer(address,uint256)')[:8]
class ERC20TxFactory(TxFactory):
def build(self, tx):
txe = EIP155Transaction(tx, tx['nonce'], tx['chainId'])
self.signer.signTransaction(txe)
tx_raw = txe.rlp_serialize()
tx_raw_hex = add_0x(tx_raw.hex())
tx_hash_hex = add_0x(keccak256_hex_to_hex(tx_raw_hex))
o = jsonrpc_template()
o['method'] = 'eth_sendRawTransaction'
o['params'].append(tx_raw_hex)
return (tx_hash_hex, o)
def erc20_balance(self, contract_address, address, sender_address=ZERO_ADDRESS):
o = jsonrpc_template()
o['method'] = 'eth_call'
data = erc20_balance_signature
data += encode_single('address', address).hex()
data = add_0x(data)
tx = self.template(sender_address, contract_address)
tx = self.set_code(tx, data)
o['params'].append(self.normalize(tx))
o['params'].append('latest')
return o
def erc20_decimals(self, contract_address, sender_address=ZERO_ADDRESS):
o = jsonrpc_template()
o['method'] = 'eth_call'
data = add_0x(erc20_decimals_signature)
tx = self.template(sender_address, contract_address)
tx = self.set_code(tx, data)
o['params'].append(self.normalize(tx))
o['params'].append('latest')
return o
def erc20_transfer(self, contract_address, sender_address, recipient_address, value):
data = erc20_transfer_signature
data += encode_single('address', recipient_address).hex()
data += encode_single('uint256', value).hex()
data = add_0x(data)
tx = self.template(sender_address, contract_address)
tx = self.set_code(tx, data)
return self.build(tx)

12
chainlib/eth/error.py Normal file
View File

@@ -0,0 +1,12 @@
class EthException(Exception):
pass
class RevertEthException(EthException):
pass
class DefaultErrorParser:
def translate(self, error):
return EthException('default parser code {}'.format(error))

55
chainlib/eth/gas.py Normal file
View File

@@ -0,0 +1,55 @@
# third-party imports
from hexathon import (
add_0x,
strip_0x,
)
from crypto_dev_signer.eth.transaction import EIP155Transaction
# local imports
from cic_tools.eth.rpc import jsonrpc_template
from cic_tools.eth.tx import TxFactory
from cic_tools.eth.hash import keccak256_hex_to_hex
def price():
o = jsonrpc_template()
o['method'] = 'eth_gasPrice'
return o
def balance(address):
o = jsonrpc_template()
o['method'] = 'eth_getBalance'
o['params'].append(address)
return o
class GasTxFactory(TxFactory):
def create(self, sender, recipient, value):
tx = self.template(sender, recipient)
tx['value'] = value
txe = EIP155Transaction(tx, tx['nonce'], tx['chainId'])
self.signer.signTransaction(txe)
tx_raw = txe.rlp_serialize()
tx_raw_hex = add_0x(tx_raw.hex())
tx_hash_hex = add_0x(keccak256_hex_to_hex(tx_raw_hex))
o = jsonrpc_template()
o['method'] = 'eth_sendRawTransaction'
o['params'].append(tx_raw_hex)
return (tx_hash_hex, o)
class DefaultGasOracle:
def __init__(self, conn):
self.conn = conn
def get(self):
o = price()
r = self.conn.do(o)
n = strip_0x(r)
return int(n, 16)

29
chainlib/eth/hash.py Normal file
View File

@@ -0,0 +1,29 @@
# third-party imports
import sha3
from hexathon import (
add_0x,
strip_0x,
)
def keccak256_hex(s):
h = sha3.keccak_256()
h.update(s.encode('utf-8'))
return h.digest().hex()
def keccak256_string_to_hex(s):
return keccak256_hex(s)
def keecak256_bytes_to_hex(b):
h = sha3.keccak_256()
h.update(b)
return h.digest().hex()
def keccak256_hex_to_hex(hx):
h = sha3.keccak_256()
b = bytes.fromhex(strip_0x(hx))
h.update(b)
return h.digest().hex()

30
chainlib/eth/nonce.py Normal file
View File

@@ -0,0 +1,30 @@
# third-party imports
from hexathon import (
add_0x,
strip_0x,
)
# local imports
from cic_tools.eth.rpc import jsonrpc_template
def nonce(address):
o = jsonrpc_template()
o['method'] = 'eth_getTransactionCount'
o['params'].append(address)
o['params'].append('pending')
return o
class DefaultNonceOracle:
def __init__(self, address, conn):
self.address = address
self.conn = conn
def next(self):
o = nonce(self.address)
r = self.conn.do(o)
n = strip_0x(r)
return int(n, 16)

17
chainlib/eth/rpc.py Normal file
View File

@@ -0,0 +1,17 @@
# standard imports
import uuid
def jsonrpc_template():
return {
'jsonrpc': '2.0',
'id': str(uuid.uuid4()),
'method': None,
'params': [],
}
def jsonrpc_result(o, ep):
if o.get('error') != None:
raise ep.translate(o)
return o['result']

View File

View File

@@ -0,0 +1,99 @@
#!python3
"""Token balance query script
.. moduleauthor:: Louis Holbrook <dev@holbrook.no>
.. pgp:: 0826EDA1702D1E87C6E2875121D2E7BB88C2A746
"""
# SPDX-License-Identifier: GPL-3.0-or-later
# standard imports
import os
import json
import argparse
import logging
# third-party imports
from hexathon import (
add_0x,
strip_0x,
even,
)
import sha3
from eth_abi import encode_single
# local imports
from cic_tools.eth.address import to_checksum
from cic_tools.eth.rpc import (
jsonrpc_template,
jsonrpc_result,
)
from cic_tools.eth.erc20 import ERC20TxFactory
from cic_tools.eth.connection import HTTPConnection
from cic_tools.eth.nonce import DefaultNonceOracle
from cic_tools.eth.gas import DefaultGasOracle
logging.basicConfig(level=logging.WARNING)
logg = logging.getLogger()
default_abi_dir = os.environ.get('ETH_ABI_DIR', '/usr/share/local/cic/solidity/abi')
default_eth_provider = os.environ.get('ETH_PROVIDER', 'http://localhost:8545')
argparser = argparse.ArgumentParser()
argparser.add_argument('-p', '--provider', dest='p', default=default_eth_provider, type=str, help='Web3 provider url (http only)')
argparser.add_argument('-t', '--token-address', dest='t', type=str, help='Token address. If not set, will return gas balance')
argparser.add_argument('-u', '--unsafe', dest='u', action='store_true', help='Auto-convert address to checksum adddress')
argparser.add_argument('--abi-dir', dest='abi_dir', type=str, default=default_abi_dir, help='Directory containing bytecode and abi (default {})'.format(default_abi_dir))
argparser.add_argument('-v', action='store_true', help='Be verbose')
argparser.add_argument('account', type=str, help='Account address')
args = argparser.parse_args()
if args.v:
logg.setLevel(logging.DEBUG)
conn = HTTPConnection(args.p)
gas_oracle = DefaultGasOracle(conn)
def main():
account = to_checksum(args.account)
if not args.u and account != add_0x(args.account):
raise ValueError('invalid checksum address')
r = None
decimals = 18
if args.t != None:
g = ERC20TxFactory(gas_oracle=gas_oracle)
# determine decimals
decimals_o = g.erc20_decimals(args.t)
r = conn.do(decimals_o)
decimals = int(strip_0x(r), 16)
# get balance
balance_o = g.erc20_balance(args.t, account)
r = conn.do(balance_o)
else:
o = jsonrpc_template()
o['method'] = 'eth_getBalance'
o['params'].append(account)
r = conn.do(o)
hx = strip_0x(r)
balance = int(hx, 16)
logg.debug('balance {} = {} decimals {}'.format(even(hx), balance, decimals))
balance_str = str(balance)
balance_len = len(balance_str)
if balance_len < 19:
print('0.{}'.format(balance_str.zfill(decimals)))
else:
offset = balance_len-decimals
print('{}.{}'.format(balance_str[:offset],balance_str[offset:]))
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,8 @@
# standard imports
import sys
# local imports
from cic_tools.eth.address import to_checksum
print(to_checksum(sys.argv[1]))

View File

@@ -0,0 +1,51 @@
#!python3
"""Decode raw transaction
.. moduleauthor:: Louis Holbrook <dev@holbrook.no>
.. pgp:: 0826EDA1702D1E87C6E2875121D2E7BB88C2A746
"""
# SPDX-License-Identifier: GPL-3.0-or-later
# standard imports
import os
import json
import argparse
import logging
# third-party imports
from cic_tools.eth.tx import unpack_signed
logging.basicConfig(level=logging.WARNING)
logg = logging.getLogger()
default_abi_dir = os.environ.get('ETH_ABI_DIR', '/usr/share/local/cic/solidity/abi')
default_eth_provider = os.environ.get('ETH_PROVIDER', 'http://localhost:8545')
argparser = argparse.ArgumentParser()
argparser.add_argument('-v', action='store_true', help='Be verbose')
argparser.add_argument('-i', '--chain-id', dest='i', type=str, help='Numeric network id')
argparser.add_argument('tx', type=str, help='hex-encoded signed raw transaction')
args = argparser.parse_args()
if args.v:
logg.setLevel(logging.DEBUG)
(chain_name, chain_id) = args.i.split(':')
def main():
tx_raw = args.tx
if tx_raw[:2] == '0x':
tx_raw = tx_raw[2:]
tx_raw_bytes = bytes.fromhex(tx_raw)
tx = unpack_signed(tx_raw_bytes, int(chain_id))
for k in tx.keys():
print('{}: {}'.format(k, tx[k]))
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,117 @@
#!python3
"""Gas transfer script
.. moduleauthor:: Louis Holbrook <dev@holbrook.no>
.. pgp:: 0826EDA1702D1E87C6E2875121D2E7BB88C2A746
"""
# SPDX-License-Identifier: GPL-3.0-or-later
# standard imports
import sys
import os
import json
import argparse
import logging
# third-party imports
from crypto_dev_signer.eth.signer import ReferenceSigner as EIP155Signer
from crypto_dev_signer.keystore import DictKeystore
from hexathon import (
add_0x,
strip_0x,
)
# local imports
from cic_tools.eth.address import to_checksum
from cic_tools.eth.connection import HTTPConnection
from cic_tools.eth.rpc import jsonrpc_template
from cic_tools.eth.nonce import DefaultNonceOracle
from cic_tools.eth.gas import (
DefaultGasOracle,
GasTxFactory,
)
from cic_tools.eth.gas import balance as gas_balance
logging.basicConfig(level=logging.WARNING)
logg = logging.getLogger()
default_abi_dir = '/usr/share/local/cic/solidity/abi'
default_eth_provider = os.environ.get('ETH_PROVIDER', 'http://localhost:8545')
argparser = argparse.ArgumentParser()
argparser.add_argument('-p', '--provider', dest='p', default='http://localhost:8545', type=str, help='Web3 provider url (http only)')
argparser.add_argument('-w', action='store_true', help='Wait for the last transaction to be confirmed')
argparser.add_argument('-ww', action='store_true', help='Wait for every transaction to be confirmed')
argparser.add_argument('-i', '--chain-spec', dest='i', type=str, default='Ethereum:1', help='Chain specification string')
argparser.add_argument('-a', '--signer-address', dest='a', type=str, help='Signing address')
argparser.add_argument('-y', '--key-file', dest='y', type=str, help='Ethereum keystore file to use for signing')
argparser.add_argument('-u', '--unsafe', dest='u', action='store_true', help='Auto-convert address to checksum adddress')
argparser.add_argument('-v', action='store_true', help='Be verbose')
argparser.add_argument('-vv', action='store_true', help='Be more verbose')
argparser.add_argument('recipient', type=str, help='Ethereum address of recipient')
argparser.add_argument('amount', type=int, help='Amount of tokens to mint and gift')
args = argparser.parse_args()
if args.vv:
logg.setLevel(logging.DEBUG)
elif args.v:
logg.setLevel(logging.INFO)
block_all = args.ww
block_last = args.w or block_all
signer_address = None
keystore = DictKeystore()
if args.y != None:
logg.debug('loading keystore file {}'.format(args.y))
signer_address = keystore.import_keystore_file(args.y)
logg.debug('now have key for signer address {}'.format(signer_address))
signer = EIP155Signer(keystore)
conn = HTTPConnection(args.p)
nonce_oracle = DefaultNonceOracle(signer_address, conn)
gas_oracle = DefaultGasOracle(conn)
chain_pair = args.i.split(':')
chain_id = int(chain_pair[1])
value = args.amount
g = GasTxFactory(signer=signer, gas_oracle=gas_oracle, nonce_oracle=nonce_oracle, chain_id=chain_id)
def balance(address):
o = gas_balance(address)
r = conn.do(o)
hx = strip_0x(r)
return int(hx, 16)
def main():
recipient = to_checksum(args.recipient)
if not args.u and recipient != add_0x(args.recipient):
raise ValueError('invalid checksum address')
logg.info('gas transfer from {} to {} value {}'.format(signer_address, recipient, value))
logg.debug('sender {} balance before: {}'.format(signer_address, balance(signer_address)))
logg.debug('recipient {} balance before: {}'.format(recipient, balance(recipient)))
(tx_hash_hex, o) = g.create(signer_address, recipient, value)
conn.do(o)
if block_last:
conn.wait(tx_hash_hex)
logg.debug('sender {} balance after: {}'.format(signer_address, balance(signer_address)))
logg.debug('recipient {} balance after: {}'.format(recipient, balance(recipient)))
print(tx_hash_hex)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,21 @@
import json
import websocket
ws = websocket.create_connection('ws://localhost:8545')
o = {
"jsonrpc": "2.0",
"method": "eth_subscribe",
"params": [
"newHeads",
],
"id": 0,
}
ws.send(json.dumps(o).encode('utf-8'))
while True:
print(ws.recv())
ws.close()

View File

@@ -0,0 +1,115 @@
#!python3
"""Token transfer script
.. moduleauthor:: Louis Holbrook <dev@holbrook.no>
.. pgp:: 0826EDA1702D1E87C6E2875121D2E7BB88C2A746
"""
# SPDX-License-Identifier: GPL-3.0-or-later
# standard imports
import os
import json
import argparse
import logging
# third-party imports
from crypto_dev_signer.eth.signer import ReferenceSigner as EIP155Signer
from crypto_dev_signer.keystore import DictKeystore
from crypto_dev_signer.eth.helper import EthTxExecutor
from hexathon import (
add_0x,
strip_0x,
)
# local imports
from cic_tools.eth.address import to_checksum
from cic_tools.eth.connection import HTTPConnection
from cic_tools.eth.rpc import jsonrpc_template
from cic_tools.eth.nonce import DefaultNonceOracle
from cic_tools.eth.gas import DefaultGasOracle
from cic_tools.eth.erc20 import ERC20TxFactory
logging.basicConfig(level=logging.WARNING)
logg = logging.getLogger()
logging.getLogger('web3').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING)
default_abi_dir = '/usr/local/share/cic/solidity/abi'
argparser = argparse.ArgumentParser()
argparser.add_argument('-p', '--provider', dest='p', default='http://localhost:8545', type=str, help='Web3 provider url (http only)')
argparser.add_argument('-w', action='store_true', help='Wait for the last transaction to be confirmed')
argparser.add_argument('-ww', action='store_true', help='Wait for every transaction to be confirmed')
argparser.add_argument('-i', '--chain-spec', dest='i', type=str, default='Ethereum:1', help='Chain specification string')
argparser.add_argument('--token-address', required='True', dest='t', type=str, help='Token address')
argparser.add_argument('-a', '--sender-address', dest='s', type=str, help='Sender account address')
argparser.add_argument('-y', '--key-file', dest='y', type=str, help='Ethereum keystore file to use for signing')
argparser.add_argument('--abi-dir', dest='abi_dir', type=str, default=default_abi_dir, help='Directory containing bytecode and abi (default {})'.format(default_abi_dir))
argparser.add_argument('-u', '--unsafe', dest='u', action='store_true', help='Auto-convert address to checksum adddress')
argparser.add_argument('-v', action='store_true', help='Be verbose')
argparser.add_argument('-vv', action='store_true', help='Be more verbose')
argparser.add_argument('recipient', type=str, help='Recipient account address')
argparser.add_argument('amount', type=int, help='Amount of tokens to mint and gift')
args = argparser.parse_args()
if args.vv:
logg.setLevel(logging.DEBUG)
elif args.v:
logg.setLevel(logging.INFO)
block_all = args.ww
block_last = args.w or block_all
signer_address = None
keystore = DictKeystore()
if args.y != None:
logg.debug('loading keystore file {}'.format(args.y))
signer_address = keystore.import_keystore_file(args.y)
logg.debug('now have key for signer address {}'.format(signer_address))
signer = EIP155Signer(keystore)
conn = HTTPConnection(args.p)
nonce_oracle = DefaultNonceOracle(signer_address, conn)
gas_oracle = DefaultGasOracle(conn)
chain_pair = args.i.split(':')
chain_id = int(chain_pair[1])
value = args.amount
g = ERC20TxFactory(signer=signer, gas_oracle=gas_oracle, nonce_oracle=nonce_oracle, chain_id=chain_id)
def balance(token_address, address):
o = g.erc20_balance(token_address, address)
r = conn.do(o)
hx = strip_0x(r)
return int(hx, 16)
def main():
recipient = args.recipient
if not args.u and recipient != add_0x(args.recipient):
raise ValueError('invalid checksum address')
logg.debug('sender {} balance before: {}'.format(signer_address, balance(args.t, signer_address)))
logg.debug('recipient {} balance before: {}'.format(recipient, balance(args.t, recipient)))
(tx_hash_hex, o) = g.erc20_transfer(args.t, signer_address, recipient, value)
conn.do(o)
if block_last:
conn.wait(tx_hash_hex)
logg.debug('sender {} balance after: {}'.format(signer_address, balance(args.t, signer_address)))
logg.debug('recipient {} balance after: {}'.format(recipient, balance(args.t, recipient)))
print(tx_hash_hex)
if __name__ == '__main__':
main()

137
chainlib/eth/tx.py Normal file
View File

@@ -0,0 +1,137 @@
# standard imports
import logging
# third-party imports
import sha3
from eth_keys import KeyAPI
from eth_keys.backends import NativeECCBackend
from rlp import decode as rlp_decode
from rlp import encode as rlp_encode
from crypto_dev_signer.eth.transaction import EIP155Transaction
# local imports
from .address import to_checksum
from .constant import (
MINIMUM_FEE_UNITS,
MINIMUM_FEE_PRICE,
)
logg = logging.getLogger(__name__)
field_debugs = [
'nonce',
'gasPrice',
'gas',
'to',
'value',
'data',
'v',
'r',
's',
]
def unpack_signed(tx_raw_bytes, chain_id=1):
d = rlp_decode(tx_raw_bytes)
logg.debug('decoding using chain id {}'.format(chain_id))
j = 0
for i in d:
logg.debug('decoded {}: {}'.format(field_debugs[j], i.hex()))
j += 1
vb = chain_id
if chain_id != 0:
v = int.from_bytes(d[6], 'big')
vb = v - (chain_id * 2) - 35
s = b''.join([d[7], d[8], bytes([vb])])
so = KeyAPI.Signature(signature_bytes=s)
h = sha3.keccak_256()
h.update(rlp_encode(d))
signed_hash = h.digest()
d[6] = chain_id
d[7] = b''
d[8] = b''
h = sha3.keccak_256()
h.update(rlp_encode(d))
unsigned_hash = h.digest()
p = so.recover_public_key_from_msg_hash(unsigned_hash)
a = p.to_checksum_address()
logg.debug('decoded recovery byte {}'.format(vb))
logg.debug('decoded address {}'.format(a))
logg.debug('decoded signed hash {}'.format(signed_hash.hex()))
logg.debug('decoded unsigned hash {}'.format(unsigned_hash.hex()))
to = d[3].hex() or None
if to != None:
to = to_checksum(to)
return {
'from': a,
'nonce': int.from_bytes(d[0], 'big'),
'gasPrice': int.from_bytes(d[1], 'big'),
'gas': int.from_bytes(d[2], 'big'),
'to': to,
'value': int.from_bytes(d[4], 'big'),
'data': '0x' + d[5].hex(),
'v': chain_id,
'r': '0x' + s[:32].hex(),
's': '0x' + s[32:64].hex(),
'chainId': chain_id,
'hash': '0x' + signed_hash.hex(),
'hash_unsigned': '0x' + unsigned_hash.hex(),
}
class TxFactory:
def __init__(self, signer=None, gas_oracle=None, nonce_oracle=None, chain_id=1):
self.gas_oracle = gas_oracle
self.nonce_oracle = nonce_oracle
self.chain_id = chain_id
self.signer = signer
def template(self, sender, recipient):
gas_price = MINIMUM_FEE_PRICE
if self.gas_oracle != None:
gas_price = self.gas_oracle.get()
logg.debug('using gas price {}'.format(gas_price))
nonce = 0
if self.nonce_oracle != None:
nonce = self.nonce_oracle.next()
logg.debug('using nonce {} for address {}'.format(nonce, sender))
return {
'from': sender,
'to': recipient,
'value': 0,
'data': '0x',
'nonce': nonce,
'gasPrice': gas_price,
'gas': MINIMUM_FEE_UNITS,
'chainId': self.chain_id,
}
def normalize(self, tx):
txe = EIP155Transaction(tx, tx['nonce'], tx['chainId'])
txes = txe.serialize()
print(txes)
return {
'from': tx['from'],
'to': txes['to'],
'gasPrice': txes['gasPrice'],
'gas': txes['gas'],
'data': txes['data'],
}
def set_code(self, tx, data, update_fee=True):
tx['data'] = data
if update_fee:
logg.debug('using hardcoded gas limit of 8000000 until we have reliable vm executor')
tx['gas'] = 8000000
return tx