21 Commits

Author SHA1 Message Date
lash
8d0a1f589b Update chain interface, add chainqueue settings to cli 2022-04-28 12:49:50 +00:00
lash
24a71b6c7f Make sure syncer doesnt croak on invalidstate 2022-04-27 09:01:46 +00:00
lash
b893aaa7b1 Correct paths between syncer and queuer 2022-04-27 06:36:01 +00:00
lash
ab1977b802 Apply queue-specific settings to tasker cli 2022-04-26 21:30:13 +00:00
lash
3d39fea7f8 WIP implement tasker daemon on new settings setup 2022-04-26 19:40:58 +00:00
lash
b19b948be3 implement settings renderer 2022-04-26 17:24:57 +00:00
lash
f961345652 Add socket send option to send script 2022-04-26 15:43:24 +00:00
lash
58d801aa86 Remove stale code, correct systemd syncer args 2022-04-26 10:10:04 +00:00
lash
c1f236769f Add conn to execution in chaind loop 2022-04-10 21:42:56 +00:00
lash
e33fefe4b3 Remove spam log 2022-04-10 21:27:36 +00:00
lash
07dc4a002f Remove unimplemented backends from setup 2022-04-10 19:13:46 +00:00
lash
dd10379936 Remove irrelevant eth-token-index 2022-04-10 19:13:24 +00:00
lash
274534831f Upgrade to chainlib release version 2022-04-10 19:10:25 +00:00
lash
2a7fd70f4e Add send cli tool, make token resolver pluggable 2022-04-10 19:03:23 +00:00
lash
dab50dadd1 Add response on socket 2022-04-10 17:13:49 +00:00
lash
9cd89f4a83 Handle duplicate tx exception 2022-04-10 16:45:58 +00:00
lash
b875386845 Avoid duplicate txs, start store before sync 2022-04-10 16:22:25 +00:00
lash
8167d84419 WIP implement chaind sync with shep chainsyncer 2022-04-10 13:58:24 +00:00
lash
9c325d416a WIP implement tasker (replacement for server.py) 2022-04-10 09:33:10 +00:00
lash
441cb00404 Add dispatch, test 2022-03-15 09:32:20 +00:00
lash
b96542715d Code purge, start over with cache and test 2022-03-15 09:13:20 +00:00
46 changed files with 894 additions and 826 deletions

View File

@@ -1 +1 @@
include *requirements.txt LICENSE chaind_eth/data/config/* chaind_eth/data/config/syncer/*
include *requirements.txt LICENSE chaind/eth/data/config/* chaind/eth/data/config/syncer/*

0
chaind/eth/__init__.py Normal file
View File

42
chaind/eth/cache.py Normal file
View File

@@ -0,0 +1,42 @@
# external imports
from hexathon import strip_0x
from chainqueue.cache import (
CacheTx,
NoopNormalizer,
)
from chainlib.eth.tx import unpack
from chainlib.encode import TxHexNormalizer
class Normalizer(TxHexNormalizer, NoopNormalizer):
def __init__(self):
super(Normalizer, self).__init__()
self.address = self.wallet_address
self.hash = self.tx_hash
#self.value = self.noop
def value(self, v):
hexathon.to_int(v)
eth_normalizer = Normalizer()
class EthCacheTx(CacheTx):
def __init__(self, chain_spec):
super(EthCacheTx, self).__init__(chain_spec)
def deserialize(self, signed_tx):
signed_tx_bytes = bytes.fromhex(strip_0x(signed_tx))
tx = unpack(signed_tx_bytes, self.chain_spec)
self.hash = eth_normalizer.hash(tx['hash'])
self.sender = eth_normalizer.address(tx['from'])
self.recipient = eth_normalizer.address(tx['to'])
self.nonce = eth_normalizer.value(tx['nonce'])
self.value = eth_normalizer.value(tx['value'])
self.src = signed_tx

View File

@@ -2,6 +2,7 @@
from chainlib.interface import ChainInterface
from chainlib.eth.block import (
block_by_number,
block_latest,
Block,
)
from chainlib.eth.tx import (
@@ -9,7 +10,6 @@ from chainlib.eth.tx import (
Tx,
)
class EthChainInterface(ChainInterface):
def __init__(self):
@@ -17,3 +17,4 @@ class EthChainInterface(ChainInterface):
self._block_from_src = Block.from_src
self._tx_receipt = receipt
self._src_normalize = Tx.src_normalize
self._block_latest = block_latest

View File

@@ -0,0 +1,6 @@
[session]
socket_path =
runtime_dir =
id =
data_dir =
dispatch_delay = 0.01

13
chaind/eth/dispatch.py Normal file
View File

@@ -0,0 +1,13 @@
# external imports
from chainlib.eth.tx import raw
class EthDispatcher:
def __init__(self, conn):
self.conn = conn
def send(self, payload):
o = raw(payload)
self.conn.do(o)

View File

@@ -0,0 +1,113 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# standard imports
import os
import logging
import sys
import datetime
# external imports
from hexathon import (
add_0x,
strip_0x,
)
from chaind import Environment
import chainlib.eth.cli
from chainlib.chain import ChainSpec
from chainqueue.db import dsn_from_config
from chainqueue.sql.backend import SQLBackend
from chainqueue.enum import StatusBits
from chaind.sql.session import SessionIndex
from chainqueue.adapters.eth import EthAdapter
from chainlib.eth.gas import price
from chainlib.eth.connection import EthHTTPConnection
from crypto_dev_signer.eth.transaction import EIP155Transaction
DEFAULT_GAS_FACTOR = 1.1
logging.basicConfig(level=logging.WARNING)
logg = logging.getLogger()
script_dir = os.path.dirname(os.path.realpath(__file__))
config_dir = os.path.join(script_dir, '..', 'data', 'config')
arg_flags = chainlib.eth.cli.argflag_std_write
argparser = chainlib.eth.cli.ArgumentParser(arg_flags)
argparser.add_argument('--backend', type=str, default='sql', help='Backend to use (currently only "sql")')
argparser.add_positional('session_id', required=False, type=str, help='Ethereum address of recipient')
args = argparser.parse_args()
extra_args = {
'backend': None,
'session_id': 'SESSION_ID',
}
env = Environment(domain='eth', env=os.environ)
config = chainlib.eth.cli.Config.from_args(args, arg_flags, extra_args=extra_args, base_config_dir=config_dir)
if config.get('SESSION_DATA_DIR') == None:
config.add(env.data_dir, 'SESSION_DATA_DIR', exists_ok=True)
chain_spec = ChainSpec.from_chain_str(config.get('CHAIN_SPEC'))
tx_getter = None
session_method = None
if config.get('_BACKEND') == 'sql':
from chainqueue.sql.query import get_tx_cache as tx_getter
from chainqueue.runnable.sql import setup_backend
from chainqueue.db.models.base import SessionBase
setup_backend(config, debug=config.true('DATABASE_DEBUG'))
session_method = SessionBase.create_session
else:
raise NotImplementedError('backend {} not implemented'.format(config.get('_BACKEND')))
if config.get('DATABASE_ENGINE') == 'sqlite':
config.add(os.path.join(config.get('SESSION_DATA_DIR'), config.get('DATABASE_NAME') + '.sqlite'), 'DATABASE_NAME', exists_ok=True)
wallet = chainlib.eth.cli.Wallet()
wallet.from_config(config)
rpc = chainlib.eth.cli.Rpc(wallet=wallet)
conn = rpc.connect_by_config(config)
dsn = dsn_from_config(config)
backend = SQLBackend(dsn, debug=config.true('DATABASE_DEBUG'), error_parser=rpc.error_parser)
session_index_backend = SessionIndex(config.get('SESSION_ID'))
adapter = EthAdapter(backend, session_index_backend=session_index_backend)
def main():
before = datetime.datetime.utcnow() - adapter.pending_retry_threshold
txs = session_index_backend.get(chain_spec, adapter, status=StatusBits.IN_NETWORK, not_status=StatusBits.FINAL | StatusBits.OBSOLETE, before=before)
o = price()
r = conn.do(o, error_parser=rpc.error_parser)
gas_price = strip_0x(r)
try:
gas_price = int(gas_price, 16)
except ValueError:
gas_price = int(gas_price)
logg.info('got current gas price {}'.format(gas_price))
signer = rpc.get_signer()
db_session = adapter.create_session()
for tx_hash in txs:
tx_bytes = bytes.fromhex(strip_0x(txs[tx_hash]))
tx = adapter.translate(tx_bytes, chain_spec)
tx_gas_price = int(tx['gasPrice'])
if tx_gas_price < gas_price:
tx['gasPrice'] = gas_price
else:
tx['gasPrice'] = int(tx['gasPrice'] * DEFAULT_GAS_FACTOR)
tx_obj = EIP155Transaction(tx, tx['nonce'], chain_spec.chain_id())
new_tx_bytes = signer.sign_transaction_to_wire(tx_obj)
logg.debug('add tx {} with gas price changed from {} to {}: {}'.format(tx_hash, tx_gas_price, tx['gasPrice'], new_tx_bytes.hex()))
adapter.add(new_tx_bytes, chain_spec, session=db_session)
db_session.close()
if __name__ == '__main__':
main()

View File

@@ -120,7 +120,6 @@ chain_spec = ChainSpec.from_chain_str(config.get('CHAIN_SPEC'))
rpc = chainlib.eth.cli.Rpc()
conn = rpc.connect_by_config(config)
logg.debug('error {}'.format(rpc.error_parser))
dsn = dsn_from_config(config)
backend = SQLBackend(dsn, error_parser=rpc.error_parser, debug=config.true('DATABASE_DEBUG'))
session_index_backend = SessionIndex(config.get('SESSION_ID'))
@@ -136,7 +135,6 @@ def process_outgoing(chain_spec, adapter, rpc, limit=100):
def main():
havesends = 0
while True:
srvs = None
try:

View File

@@ -75,7 +75,7 @@ chain_spec = ChainSpec.from_chain_str(config.get('CHAIN_SPEC'))
dsn = dsn_from_config(config)
logg.debug('dns {}'.format(dsn))
SQLBackend.setup(dsn, debug=config.true('DATABASE_DEBUG'))
rpc = EthHTTPConnection(url=config.get('RPC_HTTP_PROVIDER'), chain_spec=chain_spec)
rpc = EthHTTPConnection(url=config.get('RPC_PROVIDER'), chain_spec=chain_spec)
def register_filter_tags(filters, session):
for f in filters:

View File

@@ -0,0 +1,139 @@
# standard imports
import os
import logging
import signal
# external imports
import chainlib.eth.cli
import chaind.cli
import chainqueue.cli
from chaind.session import SessionController
from chaind.setup import Environment
from chaind.error import (
NothingToDoError,
ClientGoneError,
ClientBlockError,
ClientInputError,
)
from chainqueue import (
Store,
Status,
)
from chainqueue.error import DuplicateTxError
from chainqueue.store.fs import (
IndexStore,
CounterStore,
)
from chainqueue.cache import CacheTokenTx
from chainlib.encode import TxHexNormalizer
from chainlib.chain import ChainSpec
from chaind.adapters.fs import ChaindFsAdapter
# local imports
from chaind.eth.dispatch import EthDispatcher
from chaind.eth.cache import EthCacheTx
from chaind.eth.settings import ChaindEthSettings
logging.basicConfig(level=logging.WARNING)
logg = logging.getLogger()
script_dir = os.path.dirname(os.path.realpath(__file__))
config_dir = os.path.join(script_dir, '..', 'data', 'config')
env = Environment(domain='eth', env=os.environ)
arg_flags = chainlib.eth.cli.argflag_std_read
argparser = chainlib.eth.cli.ArgumentParser(arg_flags)
queue_arg_flags = 0
chainqueue.cli.process_flags(argparser, queue_arg_flags)
local_arg_flags = chaind.cli.argflag_local_base | chaind.cli.ChaindFlag.DISPATCH | chaind.cli.ChaindFlag.SOCKET
chaind.cli.process_flags(argparser, local_arg_flags)
args = argparser.parse_args()
base_config_dir = [chainqueue.cli.config_dir, chaind.cli.config_dir]
config = chainlib.eth.cli.Config.from_args(args, arg_flags, base_config_dir=base_config_dir)
config = chaind.cli.process_config(config, args, local_arg_flags)
config = chainqueue.cli.process_config(config, args, queue_arg_flags)
config.add('eth', 'CHAIND_ENGINE', False)
config.add('queue', 'CHAIND_COMPONENT', False)
logg.debug('config loaded:\n{}'.format(config))
settings = ChaindEthSettings(include_queue=True)
settings.process(config)
logg.debug('settings:\n{}'.format(settings))
def process_outgoing(chain_spec, adapter, rpc, limit=100):
upcoming = adapter.upcoming()
logg.info('process {} {} {}'.format(chain_spec, adapter, rpc))
logg.info('upcoming {}'.format(upcoming))
i = 0
for tx_hash in upcoming:
if adapter.dispatch(tx_hash):
i += 1
return i
chain_spec = ChainSpec.from_chain_str(config.get('CHAIN_SPEC'))
rpc = chainlib.eth.cli.Rpc()
conn = rpc.connect_by_config(config)
tx_normalizer = TxHexNormalizer().tx_hash
token_cache_store = CacheTokenTx(chain_spec, normalizer=tx_normalizer)
dispatcher = EthDispatcher(conn)
queue_adapter = ChaindFsAdapter(
settings.get('CHAIN_SPEC'),
settings.dir_for('queue'),
EthCacheTx,
dispatcher,
)
ctrl = SessionController(settings, queue_adapter, process_outgoing)
signal.signal(signal.SIGINT, ctrl.shutdown)
signal.signal(signal.SIGTERM, ctrl.shutdown)
logg.info('session id is ' + settings.get('SESSION_ID'))
logg.info('session socket path is ' + settings.get('SESSION_SOCKET_PATH'))
def main():
while True:
v = None
client_socket = None
try:
(client_socket, v) = ctrl.get()
except ClientGoneError:
break
except ClientBlockError:
continue
except ClientInputError:
continue
except NothingToDoError:
pass
if v == None:
ctrl.process(conn)
continue
result_data = None
r = 0 # no error
try:
result_data = queue_adapter.put(v.hex())
except DuplicateTxError as e:
logg.error('tx already exists: {}'.format(e))
r = 1
except ValueError as e:
logg.error('adapter rejected input {}: "{}"'.format(v.hex(), e))
continue
if r == 0:
queue_adapter.enqueue(result_data)
ctrl.respond_put(client_socket, r, extra_data=result_data)
if __name__ == '__main__':
main()

152
chaind/eth/runnable/send.py Normal file
View File

@@ -0,0 +1,152 @@
# standard imports
import os
import logging
import sys
import datetime
import enum
import re
import stat
import socket
# external imports
import chainlib.eth.cli
import chainqueue.cli
import chaind.cli
from chaind.setup import Environment
from chainlib.eth.gas import price
from chainlib.chain import ChainSpec
from hexathon import strip_0x
# local imports
from chaind.error import TxSourceError
from chaind.eth.token.process import Processor
from chaind.eth.token.gas import GasTokenResolver
from chaind.eth.cli.csv import CSVProcessor
from chaind.eth.cli.output import (
Outputter,
OpMode,
)
from chaind.eth.settings import ChaindEthSettings
logging.basicConfig(level=logging.WARNING)
logg = logging.getLogger()
arg_flags = chainlib.eth.cli.argflag_std_write
argparser = chainlib.eth.cli.ArgumentParser(arg_flags, arg_long={'-s': '--send-rpc'})
argparser.add_positional('source', required=False, type=str, help='Transaction source file')
local_arg_flags = chaind.cli.argflag_local_socket_client | chaind.cli.ChaindFlag.TOKEN
chaind.cli.process_flags(argparser, local_arg_flags)
chainqueue.cli.process_flags(argparser, 0)
args = argparser.parse_args()
env = Environment(domain='eth', env=os.environ)
base_config_dir = [chaind.cli.config_dir, chainqueue.cli.config_dir]
config = chainlib.eth.cli.Config.from_args(args, arg_flags, base_config_dir=base_config_dir)
config = chainqueue.cli.process_config(config, args, 0)
config = chaind.cli.process_config(config, args, local_arg_flags)
config.add(args.source, '_SOURCE', False)
config.add('eth', 'CHAIND_ENGINE', False)
config.add('queue', 'CHAIND_COMPONENT', False)
logg.debug('config loaded:\n{}'.format(config))
wallet = chainlib.eth.cli.Wallet()
wallet.from_config(config)
settings = ChaindEthSettings(include_queue=True)
settings.process(config)
logg.debug('settings:\n{}'.format(settings))
rpc = chainlib.eth.cli.Rpc(wallet=wallet)
conn = rpc.connect_by_config(config)
chain_spec = ChainSpec.from_chain_str(config.get('CHAIN_SPEC'))
mode = OpMode.STDOUT
re_unix = r'^ipc://(/.+)'
m = re.match(re_unix, config.get('SESSION_SOCKET_PATH', ''))
if m != None:
config.add(m.group(1), 'SESSION_SOCKET_PATH', exists_ok=True)
r = 0
try:
stat_info = os.stat(config.get('SESSION_SOCKET_PATH'))
if not stat.S_ISSOCK(stat_info.st_mode):
r = 1
except FileNotFoundError:
r = 1
if r > 0:
sys.stderr.write('{} is not a socket\n'.format(config.get('SESSION_SOCKET_PATH')))
sys.exit(1)
mode = OpMode.UNIX
logg.info('using mode {}'.format(mode.value))
if config.get('_SOURCE') == None:
sys.stderr.write('source data missing\n')
sys.exit(1)
class SocketSender:
def __init__(self, settings):
self.path = settings.get('SESSION_SOCKET_PATH')
def send(self, tx):
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(self.path)
s.sendall(tx.encode('utf-8'))
r = s.recv(68)
s.close()
return r
def main():
token_resolver = None
if settings.get('TOKEN_MODULE') != None:
import importlib
m = importlib.import_module(settings.get('TOKEN_MODULE'))
m = m.TokenResolver
else:
from chaind.eth.token.gas import GasTokenResolver
m = GasTokenResolver
token_resolver = m(chain_spec, rpc.get_sender_address(), rpc.get_signer(), rpc.get_gas_oracle(), rpc.get_nonce_oracle())
processor = Processor(token_resolver, config.get('_SOURCE'))
processor.add_processor(CSVProcessor())
sends = None
try:
sends = processor.load(conn)
except TxSourceError as e:
sys.stderr.write('processing error: {}. processors: {}\n'.format(str(e), str(processor)))
sys.exit(1)
sender = None
if config.true('_SOCKET_SEND'):
if settings.get('SESSION_SOCKET_PATH') != None:
sender = SocketSender(settings)
tx_iter = iter(processor)
out = Outputter(mode)
while True:
tx = None
try:
tx_bytes = next(tx_iter)
except StopIteration:
break
tx_hex = tx_bytes.hex()
if sender != None:
r = sender.send(tx_hex)
logg.info('sent {} result {}'.format(tx_hex, r))
print(out.do(tx_hex))
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,82 @@
# standard imports
import os
import logging
# external imports
import chainlib.cli
import chainsyncer.cli
import chaind.cli
from chaind.setup import Environment
from chaind.filter import StateFilter
from chaind.adapters.fs import ChaindFsAdapter
from chainlib.eth.block import block_latest
from hexathon import strip_0x
from chainsyncer.store.fs import SyncFsStore
from chainsyncer.driver.chain_interface import ChainInterfaceDriver
from chainsyncer.error import SyncDone
# local imports
from chaind.eth.settings import ChaindEthSettings
# local imports
from chaind.eth.cache import EthCacheTx
logging.basicConfig(level=logging.WARNING)
logg = logging.getLogger()
script_dir = os.path.dirname(os.path.realpath(__file__))
config_dir = os.path.join(script_dir, '..', 'data', 'config')
env = Environment(domain='eth', env=os.environ)
arg_flags = chainlib.cli.argflag_std_base | chainlib.cli.Flag.CHAIN_SPEC
argparser = chainlib.cli.ArgumentParser(arg_flags)
local_arg_flags = chaind.cli.argflag_local_base
chaind.cli.process_flags(argparser, local_arg_flags)
sync_flags = chainsyncer.cli.SyncFlag.RANGE | chainsyncer.cli.SyncFlag.HEAD
chainsyncer.cli.process_flags(argparser, sync_flags)
args = argparser.parse_args()
base_config_dir = [
chainsyncer.cli.config_dir,
chaind.cli.config_dir,
]
config = chainlib.cli.Config.from_args(args, arg_flags, base_config_dir=base_config_dir)
config = chainsyncer.cli.process_config(config, args, sync_flags)
config = chaind.cli.process_config(config, args, local_arg_flags)
config.add('eth', 'CHAIND_ENGINE', False)
config.add('sync', 'CHAIND_COMPONENT', False)
logg.debug('config loaded:\n{}'.format(config))
settings = ChaindEthSettings(include_sync=True)
settings.process(config)
logg.debug('settings:\n{}'.format(settings))
def main():
queue_adapter = ChaindFsAdapter(
settings.get('CHAIN_SPEC'),
settings.dir_for('queue'),
EthCacheTx,
None,
)
fltr = StateFilter(queue_adapter)
sync_store = SyncFsStore(settings.get('SESSION_DATA_DIR'), session_id=settings.get('SESSION_ID'))
sync_store.register(fltr)
logg.debug('session block offset {}'.format(settings.get('SYNCER_OFFSET')))
drv = ChainInterfaceDriver(sync_store, settings.get('SYNCER_INTERFACE'), offset=settings.get('SYNCER_OFFSET'), target=settings.get('SYNCER_LIMIT'))
try:
drv.run(settings.get('RPC'))
except SyncDone as e:
logg.info('sync done: {}'.format(e))
if __name__ == '__main__':
main()

18
chaind/eth/settings.py Normal file
View File

@@ -0,0 +1,18 @@
# external imports
from chainlib.eth.connection import EthHTTPConnection
from chaind.settings import ChaindSettings
from chaind.eth.chain import EthChainInterface
class ChaindEthSettings(ChaindSettings):
def process_sync_interface(self, config):
self.o['SYNCER_INTERFACE'] = EthChainInterface()
def process_common(self, config):
super(ChaindEthSettings, self).process_common(config)
rpc_provider = config.get('RPC_PROVIDER')
if rpc_provider == None:
rpc_provider = 'http://localhost:8545'
self.o['RPC'] = EthHTTPConnection(url=rpc_provider, chain_spec=self.o['CHAIN_SPEC'])

View File

@@ -0,0 +1 @@
from .base import *

52
chaind/eth/token/base.py Normal file
View File

@@ -0,0 +1,52 @@
# standard imports
import logging
# external imports
from funga.eth.transaction import EIP155Transaction
from hexathon import strip_0x
logg = logging.getLogger(__name__)
class BaseTokenResolver:
def __init__(self, chain_spec, sender, signer, gas_oracle, nonce_oracle):
self.chain_spec = chain_spec
self.chain_id = chain_spec.chain_id()
self.signer = signer
self.sender = sender
self.gas_oracle = gas_oracle
self.nonce_oracle = nonce_oracle
self.factory = None
self.gas_limit_start = None
self.gas_price_start = None
def reset(self):
gas_data = self.gas_oracle.get_gas()
self.gas_price_start = gas_data[0]
self.gas_limit_start = gas_data[1]
def get_values(self, gas_value, value, executable_address=None):
nonce = self.nonce_oracle.get_nonce()
if executable_address == None:
return (value, 0, nonce)
try:
value = int(value)
except ValueError:
value = int(strip_0x(value), 16)
try:
gas_value = int(gas_value)
except ValueError:
gas_value = int(strip_0x(gas_value), 16)
return (gas_value, value, nonce,)
def sign(self, tx):
tx_o = EIP155Transaction(tx, tx['nonce'], self.chain_id)
tx_bytes = self.signer.sign_transaction_to_wire(tx_o)
return tx_bytes

26
chaind/eth/token/erc20.py Normal file
View File

@@ -0,0 +1,26 @@
# external imports
from eth_erc20 import ERC20
from chainlib.eth.tx import TxFormat
# local imports
from chaind.eth.token import BaseTokenResolver
class TokenResolver(BaseTokenResolver):
def __init__(self, chain_spec, sender, signer, gas_oracle, nonce_oracle):
super(TokenResolver, self).__init__(chain_spec, sender, signer, gas_oracle, nonce_oracle)
self.factory = ERC20(self.chain_spec, signer=self.signer, gas_oracle=self.gas_oracle, nonce_oracle=self.nonce_oracle)
def create(self, conn, recipient, gas_value, data=None, token_value=0, executable_address=None, passphrase=None):
if executable_address == None:
raise ValueError('executable address required')
(gas_value, token_value, nonce) = self.get_values(gas_value, token_value, executable_address=executable_address)
tx = self.factory.transfer(executable_address, self.sender, recipient, token_value, tx_format=TxFormat.DICT)
tx['value'] = gas_value
return tx

30
chaind/eth/token/gas.py Normal file
View File

@@ -0,0 +1,30 @@
# external imports
from chainlib.eth.gas import Gas
from hexathon import strip_0x
# local imports
from chaind.eth.token import BaseTokenResolver
class GasTokenResolver(BaseTokenResolver):
def __init__(self, chain_spec, sender, signer, gas_oracle, nonce_oracle):
super(GasTokenResolver, self).__init__(chain_spec, sender, signer, gas_oracle, nonce_oracle)
self.factory = Gas(self.chain_spec, signer=self.signer, gas_oracle=self.gas_oracle, nonce_oracle=self.nonce_oracle)
def create(self, conn, recipient, gas_value, data=None, token_value=0, executable_address=None, passphrase=None):
(gas_value, token_value, nonce) = self.get_values(gas_value, token_value, executable_address=executable_address)
tx = {
'from': self.sender,
'to': recipient,
'value': gas_value,
'data': data,
'nonce': nonce,
'gasPrice': self.gas_price_start,
'gas': self.gas_limit_start,
}
return tx

105
chaind/eth/token/process.py Normal file
View File

@@ -0,0 +1,105 @@
# standard imports
import logging
# external imports
from chaind.error import TxSourceError
from chainlib.eth.address import is_checksum_address
from chainlib.eth.tx import unpack
from chainlib.eth.gas import Gas
from hexathon import (
add_0x,
strip_0x,
)
from funga.eth.transaction import EIP155Transaction
logg = logging.getLogger(__name__)
class Processor:
def __init__(self, resolver, source):
self.resolver = resolver
self.source = source
self.processor = []
self.conn = None
def add_processor(self, processor):
self.processor.append(processor)
def load(self, conn, process=True):
self.conn = conn
for processor in self.processor:
self.content = processor.load(self.source)
if self.content != None:
if process:
try:
self.process()
except Exception as e:
raise TxSourceError('invalid source contents: {}'.format(str(e)))
return self.content
raise TxSourceError('unparseable source')
# 0: recipient
# 1: amount
# 2: token identifier (optional, when not specified network gas token will be used)
# 3: gas amount (optional)
def process(self):
txs = []
for i, r in enumerate(self.content):
logg.debug('processing {}'.format(r))
if not is_checksum_address(r[0]):
raise ValueError('invalid checksum address {} in record {}'.format(r[0], i))
self.content[i][0] = add_0x(r[0])
try:
self.content[i][1] = int(r[1])
except ValueError:
self.content[i][1] = int(strip_0x(r[1]), 16)
native_token_value = 0
if len(self.content[i]) == 3:
self.content[i].append(native_token_value)
def __iter__(self):
self.resolver.reset()
self.cursor = 0
return self
def __next__(self):
if self.cursor == len(self.content):
raise StopIteration()
r = self.content[self.cursor]
value = r[1]
gas_value = 0
try:
gas_value = r[3]
except IndexError:
pass
logg.debug('gasvalue {}'.format(gas_value))
data = '0x'
executable_address = None
try:
executable_address = r[2]
except IndexError:
pass
tx = self.resolver.create(self.conn, r[0], gas_value, data=data, token_value=value, executable_address=executable_address)
v = self.resolver.sign(tx)
self.cursor += 1
return v
def __str__(self):
names = []
for s in self.processor:
names.append(str(s))
return ','.join(names)

View File

@@ -1,162 +0,0 @@
# standard imports
import logging
# external imports
from chaind.error import TxSourceError
from chainlib.eth.address import is_checksum_address
from chainlib.eth.tx import unpack
from chainlib.eth.gas import Gas
from hexathon import (
add_0x,
strip_0x,
)
from crypto_dev_signer.eth.transaction import EIP155Transaction
from eth_erc20 import ERC20
logg = logging.getLogger(__name__)
class Processor:
def __init__(self, sender, signer, source, chain_spec, gas_oracle, nonce_oracle, resolver=None):
self.sender = sender
self.signer = signer
self.source = source
self.processor = []
self.content = []
self.token = []
self.token_resolver = resolver
self.cursor = 0
self.gas_oracle = gas_oracle
self.nonce_oracle = nonce_oracle
self.nonce_start = None
self.gas_limit_start = None
self.gas_price_start = None
self.chain_spec = chain_spec
self.chain_id = chain_spec.chain_id()
def add_processor(self, processor):
self.processor.append(processor)
def load(self, process=True):
for processor in self.processor:
self.content = processor.load(self.source)
if self.content != None:
if process:
try:
self.process()
except Exception as e:
raise TxSourceError('invalid source contents: {}'.format(str(e)))
return self.content
raise TxSourceError('unparseable source')
# 0: recipient
# 1: amount
# 2: token identifier (optional, when not specified network gas token will be used)
# 3: gas amount (optional)
def process(self):
txs = []
for i, r in enumerate(self.content):
logg.debug('processing {}'.format(r))
if not is_checksum_address(r[0]):
raise ValueError('invalid checksum address {} in record {}'.format(r[0], i))
self.content[i][0] = add_0x(r[0])
try:
self.content[i][1] = int(r[1])
except ValueError:
self.content[i][1] = int(strip_0x(r[1]), 16)
native_token_value = 0
if self.token_resolver == None:
self.token.append(None)
else:
#self.content[i][2] = self.token_resolver.lookup(k)
token = self.token_resolver.lookup(r[2])
self.token.append(token)
if len(self.content[i]) == 3:
self.content[i].append(native_token_value)
def __iter__(self):
gas_data = self.gas_oracle.get_gas()
self.gas_price_start = gas_data[0]
self.gas_limit_start = gas_data[1]
self.cursor = 0
return self
def __next__(self):
if self.cursor == len(self.content):
raise StopIteration()
nonce = self.nonce_oracle.next_nonce()
token_factory = None
r = self.content[self.cursor]
token = self.token[self.cursor]
if token == None:
token_factory = Gas(self.chain_spec, signer=self.signer, gas_oracle=self.gas_oracle, nonce_oracle=self.nonce_oracle)
else:
token_factory = ERC20(self.chain_spec, signer=self.signer, gas_oracle=self.gas_oracle, nonce_oracle=self.nonce_oracle)
value = 0
gas_value = 0
data = '0x'
debug_destination = (r[2], token)
if debug_destination[1] == None:
debug_destination = (None, 'network gas token')
if isinstance(token_factory, ERC20):
(tx_hash_hex, o) = token_factory.transfer(token, self.sender, r[0], r[1])
logg.debug('tx {}'.format(o))
# TODO: allow chainlib to return data args only (TxFormat)
tx = unpack(bytes.fromhex(strip_0x(o['params'][0])), self.chain_spec)
data = tx['data']
try:
value = int(r[1])
except ValueError:
value = int(strip_0x(r[1]), 16)
try:
gas_value = int(r[3])
except:
gas_value = int(strip_0x(r[3]), 16)
else:
try:
value = int(r[1])
except ValueError:
value = int(strip_0x(r[1]), 16)
gas_value = value
logg.debug('token factory {} resolved sender {} recipient {} gas value {} token value {} token {}'.format(
str(token_factory),
self.sender,
r[0],
gas_value,
value,
debug_destination,
)
)
tx = {
'from': self.sender,
'to': r[0],
'value': gas_value,
'data': data,
'nonce': nonce,
'gasPrice': self.gas_price_start,
'gas': self.gas_limit_start,
}
tx_o = EIP155Transaction(tx, nonce, self.chain_id)
tx_bytes = self.signer.sign_transaction_to_wire(tx_o)
self.cursor += 1
return tx_bytes
def __str__(self):
names = []
for s in self.processor:
names.append(str(s))
return ','.join(names)

View File

@@ -1,86 +0,0 @@
# standard imports
import logging
# external imports
from chainlib.eth.constant import ZERO_ADDRESS
from chainlib.eth.address import is_checksum_address
from hexathon import strip_0x
from eth_token_index.index import TokenUniqueSymbolIndex
logg = logging.getLogger(__name__)
class LookNoop:
def __init__(self, check=True):
self.check = check
def get(self, k, rpc=None):
if not self.check:
address_bytes = bytes.fromhex(strip_0x(k))
if len(address_bytes) != 20:
raise ValueError('{} is not a valid address'.format(k))
else:
try:
if not is_checksum_address(k):
raise ValueError('not valid checksum address {}'.format(k))
except ValueError:
raise ValueError('not valid checksum address {}'.format(k))
return strip_0x(k)
def __str__(self):
return 'checksum address shortcircuit'
class TokenIndexLookup(TokenUniqueSymbolIndex):
def __init__(self, chain_spec, signer, gas_oracle, nonce_oracle, address, sender_address=ZERO_ADDRESS):
super(TokenIndexLookup, self).__init__(chain_spec, signer=signer, gas_oracle=gas_oracle, nonce_oracle=nonce_oracle)
self.local_address = address
self.sender_address = sender_address
def get(self, k, rpc=None):
o = self.address_of(self.local_address, k, sender_address=self.sender_address)
r = rpc.do(o)
address = self.parse_address_of(r)
if address != ZERO_ADDRESS:
return address
raise FileNotFoundError(address)
def __str__(self):
return 'token symbol index'
class DefaultResolver:
def __init__(self, chain_spec, rpc, sender_address=ZERO_ADDRESS):
self.chain_spec = chain_spec
self.rpc = rpc
self.lookups = []
self.lookup_pointers = []
self.cursor = 0
self.sender_address = sender_address
def add_lookup(self, lookup, reverse):
self.lookups.append(lookup)
self.lookup_pointers.append(reverse)
def lookup(self, k):
if k == '' or k == None:
return None
for lookup in self.lookups:
try:
address = lookup.get(k, rpc=self.rpc)
logg.debug('resolved token {} to {} with lookup {}'.format(k, address, lookup))
return address
except Exception as e:
logg.debug('lookup {} failed for {}: {}'.format(lookup, k, e))
raise FileNotFoundError(k)

View File

@@ -1,81 +0,0 @@
# standard imports
import logging
# external imports
from chainlib.eth.gas import price
from chainlib.eth.tx import unpack
from chaind.error import TxSourceError
from crypto_dev_signer.eth.transaction import EIP155Transaction
from chainlib.eth.gas import Gas
from hexathon import (
add_0x,
strip_0x,
)
# local imports
from chaind_eth.cli.tx import TxProcessor
logg = logging.getLogger(__name__)
DEFAULT_GAS_FACTOR = 1.1
class Retrier:
def __init__(self, sender, signer, source, chain_spec, gas_oracle, gas_factor=DEFAULT_GAS_FACTOR):
self.sender = sender
self.signer = signer
self.source = source
self.raw_content = []
self.content = []
self.cursor = 0
self.gas_oracle = gas_oracle
self.gas_factor = gas_factor
self.chain_spec = chain_spec
self.chain_id = chain_spec.chain_id()
self.processor = [TxProcessor()]
def load(self, process=True):
for processor in self.processor:
self.raw_content = processor.load(self.source)
if self.raw_content != None:
if process:
#try:
self.process()
#except Exception as e:
# raise TxSourceError('invalid source contents: {}'.format(str(e)))
return self.content
raise TxSourceError('unparseable source')
def process(self):
gas_data = self.gas_oracle.get_gas()
gas_price = gas_data[0]
for tx in self.raw_content:
tx_bytes = bytes.fromhex(strip_0x(tx))
tx = unpack(tx_bytes, self.chain_spec)
tx_gas_price_old = int(tx['gasPrice'])
if tx_gas_price_old < gas_price:
tx['gasPrice'] = gas_price
else:
tx['gasPrice'] = int(tx_gas_price_old * self.gas_factor)
if tx_gas_price_old == tx['gasPrice']:
tx['gasPrice'] += 1
tx_obj = EIP155Transaction(tx, tx['nonce'], self.chain_id)
new_tx_bytes = self.signer.sign_transaction_to_wire(tx_obj)
logg.debug('add tx {} with gas price changed from {} to {}: {}'.format(tx['hash'], tx_gas_price_old, tx['gasPrice'], new_tx_bytes.hex()))
self.content.append(new_tx_bytes)
def __iter__(self):
self.cursor = 0
return self
def __next__(self):
if self.cursor == len(self.content):
raise StopIteration()
tx = self.content[self.cursor]
self.cursor += 1
return tx

View File

@@ -1,23 +0,0 @@
# standard imports
import logging
logg = logging.getLogger(__name__)
class TxProcessor:
def load(self, s):
contents = []
f = None
try:
f = open(s, 'r')
except FileNotFoundError:
return None
contents = f.readlines()
f.close()
for i in range(len(contents)):
contents[i] = contents[i].rstrip()
return contents
def __str__(self):
return 'tx processor'

View File

@@ -1,16 +0,0 @@
[session]
socket_path =
runtime_dir =
id =
data_dir =
dispatch_delay = 4.0
[database]
engine =
name = chaind
driver =
user =
password =
host =
port =
debug = 0

View File

@@ -1,4 +0,0 @@
[syncer]
history_start = 0
skip_history = 0
loop_interval = 1

View File

@@ -1,72 +0,0 @@
# standard imports
import logging
# external imports
from chainlib.eth.address import to_checksum_address
from chainlib.eth.tx import unpack
from chainlib.error import JSONRPCException
from chainqueue.enum import StatusBits
from chainqueue.sql.query import count_tx
from hexathon import strip_0x
from chainqueue.encode import TxNormalizer
#logg = logging.getLogger(__name__)
logg = logging.getLogger()
class Dispatcher:
status_inflight_mask = StatusBits.IN_NETWORK | StatusBits.FINAL
status_inflight_mask_match = StatusBits.IN_NETWORK
def __init__(self, chain_spec, adapter, limit=100):
self.address_counts = {}
self.chain_spec = chain_spec
self.adapter = adapter
self.limit = limit
self.tx_normalizer = TxNormalizer()
def __init_count(self, address, session):
c = self.address_counts.get(address)
if c == None:
c = self.limit - count_tx(self.chain_spec, address, self.status_inflight_mask, self.status_inflight_mask_match, session=session)
if c < 0:
c = 0
self.address_counts[address] = c
return c
def get_count(self, address, session):
address = self.tx_normalizer.wallet_address(address)
return self.__init_count(address, session)
def inc_count(self, address, session):
address = self.tx_normalizer.wallet_address(address)
self.__init_count(address, session)
self.address_counts[address] -= 1
def process(self, rpc, session):
c = 0
txs = self.adapter.upcoming(self.chain_spec, session=session)
for k in txs.keys():
signed_tx_bytes = bytes.fromhex(strip_0x(txs[k]))
tx_obj = unpack(signed_tx_bytes, self.chain_spec)
sender = to_checksum_address(tx_obj['from'])
address_count = self.get_count(sender, session)
if address_count == 0:
logg.debug('too many inflight txs for {}, skipping {}'.format(sender, k))
continue
logg.debug('processing tx {} {}'.format(k, txs[k]))
r = 0
try:
r = self.adapter.dispatch(self.chain_spec, rpc, k, txs[k], session)
except JSONRPCException as e:
logg.error('dispatch failed for {}: {}'.format(k, e))
continue
if r == 0:
self.inc_count(sender, session)
c += 1
return c

View File

@@ -1,27 +0,0 @@
# standard imports
import logging
# external imports
from chainlib.status import Status
from chainqueue.sql.query import get_tx
from chainqueue.error import NotLocalTxError
from chainqueue.sql.state import set_final
logg = logging.getLogger(__name__)
class StateFilter:
def __init__(self, chain_spec):
self.chain_spec = chain_spec
def filter(self, conn, block, tx, session=None):
otx = None
try:
otx = get_tx(self.chain_spec, tx.hash, session=session)
except NotLocalTxError:
return False
logg.info('finalizing local tx {} with status {}'.format(tx.hash, tx.status))
status = tx.status != Status.SUCCESS
set_final(self.chain_spec, tx.hash, block=block.number, tx_index=tx.index, fail=status, session=session)

View File

@@ -1,44 +0,0 @@
# standard imports
import logging
# external imports
from chainlib.eth.constant import ZERO_ADDRESS
from chainlib.eth.tx import (
unpack,
raw,
)
from hexathon import (
add_0x,
strip_0x,
)
# local imports
from chainqueue.adapters.sessionindex import SessionIndexAdapter
logg = logging.getLogger(__name__)
class EthAdapter(SessionIndexAdapter):
def translate(self, bytecode, chain_spec):
logg.debug('bytecode {}'.format(bytecode))
tx = unpack(bytecode, chain_spec)
tx['source_token'] = ZERO_ADDRESS
tx['destination_token'] = ZERO_ADDRESS
tx['from_value'] = tx['value']
tx['to_value'] = tx['value']
return tx
def dispatch(self, chain_spec, rpc, tx_hash, signed_tx, session=None):
o = raw(signed_tx)
r = self.backend.dispatch(chain_spec, rpc, tx_hash, o)
return r
# def cache(self, chain_spec):
# session = self.backend.create_session()
# r = self.backend.create(chain_spec, tx['nonce'], tx['from'], tx['hash'], add_0x(bytecode.hex()), session=session)
# session.close()

1
erc20_requirements.txt Normal file
View File

@@ -0,0 +1 @@
eth-erc20~=0.3.0

View File

@@ -1,4 +1,6 @@
chaind<=0.0.3,>=0.0.3a6
hexathon~=0.0.1a8
chainlib-eth<=0.1.0,>=0.0.10a10
eth-token-index<=0.3.0,>=0.2.4a1
chaind~=0.1.1
hexathon~=0.1.5
chainlib-eth~=0.1.1
pyxdg~=0.27
shep~=0.2.3
funga-eth~=0.6.0

View File

@@ -3,7 +3,7 @@
set -e
set -x
set -a
export PYTHONPATH=${PYTHONPATH:.}
export PYTHONPATH=${PYTHONPATH:-.}
for f in `ls tests/*.py`; do
python $f
done

View File

@@ -1,10 +1,10 @@
[metadata]
name = chaind-eth
version = 0.0.3a5
version = 0.1.4
description = Queue server for ethereum
author = Louis Holbrook
author_email = dev@holbrook.no
url = https://gitlab.com/chaintools/chainqueue
url = https://gitlab.com/chaintool/chaind-eth
keywords =
cic
cryptocurrency
@@ -22,20 +22,20 @@ classifiers =
# Topic :: Blockchain :: EVM
license = GPL3
licence_files =
LICENSE.txt
LICENSE
[options]
python_requires = >= 3.6
python_requires = >= 3.7
include_package_data = True
packages =
chaind_eth
chaind_eth.runnable
chaind_eth.cli
chainqueue.adapters
chaind.eth
chaind.eth.runnable
chaind.eth.cli
chaind.eth.token
[options.entry_points]
console_scripts =
chaind-eth-server = chaind_eth.runnable.server:main
chaind-eth-syncer = chaind_eth.runnable.syncer:main
chaind-eth-send = chaind_eth.runnable.send:main
chaind-eth-resend = chaind_eth.runnable.resend:main
chaind-eth-queuer = chaind.eth.runnable.queuer:main
chaind-eth-syncer = chaind.eth.runnable.syncer:main
chaind-eth-send = chaind.eth.runnable.send:main
#chaind-eth-resend = chaind_eth.runnable.resend:main

View File

@@ -21,6 +21,16 @@ while True:
test_requirements.append(l.rstrip())
f.close()
erc20_requirements = []
f = open('erc20_requirements.txt', 'r')
while True:
l = f.readline()
if l == '':
break
test_requirements.append(l.rstrip())
f.close()
postgres_requirements = [
'psycopg2==2.8.6',
] + requirements
@@ -30,7 +40,8 @@ setup(
install_requires=requirements,
tests_require=test_requirements,
extras_require={
'postgres': postgres_requirements,
'sqlite': sqlite_requirements,
#'postgres': postgres_requirements,
#'sqlite': sqlite_requirements,
'erc20': erc20_requirements,
}
)

View File

@@ -1,10 +1,10 @@
[Unit]
Description=Chainqueue transaction dispatch interface
Requires=chaind-eth-sync@.service
After=chaind-eth-sync@.service
#Requires=chaind-eth-sync@.service
#After=chaind-eth-sync@.service
[Service]
Environment="SESSION_ID=%i"
Environment="SESSION_RUNTIME_DIR=/run/user/%U/chaind/eth"
ExecStart=%h/.local/bin/chaind-eth-server -v --session-id %i
ExecStart=%h/.local/bin/chaind-eth-tasker -v --session-id %i
Restart=on-failure

View File

@@ -4,5 +4,5 @@ Description=Ethereum chaind syncer
[Service]
Environment="SESSION_ID=%i"
Environment="SESSION_RUNTIME_DIR=/run/user/%U/chaind/eth"
ExecStart=%h/.local/bin/chaind-eth-syncer -v --session-id %i --skip-history
ExecStart=%h/.local/bin/chaind-eth-syncer -v --session-id %i --head
Restart=on-failure

View File

@@ -2,3 +2,4 @@ eth_tester==0.5.0b3
py-evm==0.3.0a20
rlp==2.0.1
coverage==5.5
jsonrpc_std~=0.1.0

View File

@@ -1,51 +0,0 @@
# standard imports
import os
import unittest
# external imports
from chainsyncer.unittest.db import ChainSyncerDb
from chainqueue.unittest.db import ChainQueueDb
from chainlib.eth.unittest.ethtester import EthTesterCase
from chainqueue.adapters.eth import EthAdapter
from chainqueue.unittest.db import (
db_config,
dsn_from_config,
)
from chainqueue.sql.backend import SQLBackend
from chainlib.eth.address import to_checksum_address
from hexathon import add_0x
# local imports
from chaind_eth.chain import EthChainInterface
class TestBase(EthTesterCase):
def setUp(self):
super(TestBase, self).setUp()
self.db_chainsyncer = ChainSyncerDb(debug=bool(os.environ.get('DATABASE_DEBUG')))
self.session_chainsyncer = self.db_chainsyncer.bind_session()
self.db_chainqueue = ChainQueueDb(debug=bool(os.environ.get('DATABASE_DEBUG')))
self.session_chainqueue = self.db_chainqueue.bind_session()
self.interface = EthChainInterface()
def tearDown(self):
self.session_chainsyncer.commit()
self.db_chainsyncer.release_session(self.session_chainsyncer)
self.session_chainqueue.commit()
self.db_chainqueue.release_session(self.session_chainqueue)
super(TestBase, self).tearDown()
class TestSQLBase(TestBase):
example_tx_hex = 'f8650d8405f5e10082520894ee38d3a40e177608d41978778206831f60dd0fa88204008077a040adee2ad0a0e566bced4b76a8899549e86719eb8866b87674b6fdc88479c201a030b3ca061bb330f4d78bc9cb8144c8e570339496f56b7809387de2ffeaa585d5'
example_tx = bytes.fromhex(example_tx_hex)
example_tx_sender = add_0x(to_checksum_address('eb3907ecad74a0013c259d5874ae7f22dcbcc95c'))
dsn = dsn_from_config(db_config)
def setUp(self):
super(TestSQLBase, self).setUp()
self.backend = SQLBackend(self.dsn, debug=bool(os.environ.get('DATABASE_DEBUG')))
self.adapter = EthAdapter(self.backend)

View File

@@ -1,26 +0,0 @@
# stanndard imports
import logging
import unittest
# external imports
from chainlib.chain import ChainSpec
# test imports
from tests.chaind_eth_base import TestSQLBase
logging.basicConfig(level=logging.DEBUG)
class TestAdapter(TestSQLBase):
def test_eth_adapter_translate(self):
self.adapter.translate(self.example_tx, self.chain_spec)
# succesful decode means translate is working, no further checks needed
def test_eth_adapter_add(self):
self.adapter.add(self.example_tx_hex, self.chain_spec, session=self.session_chainqueue)
if __name__ == '__main__':
unittest.main()

View File

@@ -1,38 +0,0 @@
# standard imports
import unittest
# external imports
from chainlib.eth.gas import (
RPCGasOracle,
Gas,
)
from chainlib.eth.nonce import (
RPCNonceOracle,
)
from chainlib.eth.tx import (
TxFormat,
unpack,
)
from hexathon import (
strip_0x,
)
# test imports
from tests.chaind_eth_base import TestBase
class TestChain(TestBase):
def test_chain_interface(self):
gas_oracle = RPCGasOracle(conn=self.rpc)
nonce_oracle = RPCNonceOracle(self.accounts[0], conn=self.rpc)
c = Gas(self.chain_spec, signer=self.signer, gas_oracle=gas_oracle, nonce_oracle=nonce_oracle)
(tx_hash, tx_raw_rlp_signed) = c.create(self.accounts[0], self.accounts[1], 1024, tx_format=TxFormat.RLP_SIGNED)
tx_raw_rlp_signed_bytes = bytes.fromhex(strip_0x(tx_raw_rlp_signed))
tx_src = unpack(tx_raw_rlp_signed_bytes, self.chain_spec)
tx_src = self.interface.src_normalize(tx_src)
assert tx_src['gas_price'] == tx_src['gasPrice']
if __name__ == '__main__':
unittest.main()

View File

@@ -1,52 +0,0 @@
# stanndard imports
import logging
import unittest
# external imports
from hexathon import strip_0x
from chainlib.eth.tx import (
unpack,
TxFormat,
)
from chainqueue.sql.query import get_tx
from chainqueue.enum import StatusBits
from chainlib.eth.gas import (
RPCGasOracle,
Gas,
)
from chainlib.eth.nonce import (
RPCNonceOracle,
)
# local imports
from chaind_eth.dispatch import Dispatcher
# test imports
from tests.chaind_eth_base import TestSQLBase
logging.basicConfig(level=logging.DEBUG)
class TestDispatcher(TestSQLBase):
def test_dispatch_process(self):
gas_oracle = RPCGasOracle(conn=self.rpc)
nonce_oracle = RPCNonceOracle(self.accounts[0], conn=self.rpc)
c = Gas(self.chain_spec, signer=self.signer, gas_oracle=gas_oracle, nonce_oracle=nonce_oracle)
(tx_hash, tx_raw_rlp_signed) = c.create(self.accounts[0], self.accounts[1], 1024, tx_format=TxFormat.RLP_SIGNED)
tx_raw_rlp_signed_bytes = bytes.fromhex(strip_0x(tx_raw_rlp_signed))
dispatcher = Dispatcher(self.chain_spec, self.adapter, 1)
self.adapter.add(tx_raw_rlp_signed, self.chain_spec, session=self.session_chainqueue)
#self.assertEqual(dispatcher.get_count(self.example_tx_sender, self.session_chainqueue), 1)
self.assertEqual(dispatcher.get_count(self.accounts[0], self.session_chainqueue), 1)
dispatcher.process(self.rpc, self.session_chainqueue)
tx_obj = unpack(tx_raw_rlp_signed_bytes, self.chain_spec)
o = get_tx(self.chain_spec, tx_obj['hash'], session=self.session_chainqueue)
self.assertGreater(o['status'] & StatusBits.IN_NETWORK, 0)
self.assertEqual(dispatcher.get_count(self.accounts[0], self.session_chainqueue), 0)
if __name__ == '__main__':
unittest.main()

View File

@@ -1,101 +0,0 @@
# standard imports
import unittest
import logging
import os
# external imports
from potaahto.symbols import snake_and_camel
from hexathon import (
strip_0x,
)
from chainqueue.adapters.eth import EthAdapter
from chainqueue.unittest.db import (
db_config,
dsn_from_config,
)
from chainqueue.sql.backend import SQLBackend
from chainqueue.enum import is_alive
from chainqueue.sql.query import get_tx
from chainlib.eth.gas import (
RPCGasOracle,
Gas,
)
from chainlib.eth.nonce import (
RPCNonceOracle,
)
from chainlib.eth.tx import (
TxFormat,
raw,
unpack,
receipt,
Tx,
)
from chainlib.eth.block import (
block_by_hash,
Block,
)
from chainqueue.sql.state import (
set_sent,
set_reserved,
set_ready,
)
# local imports
from chaind_eth.filter import StateFilter
from chaind_eth.chain import EthChainInterface
# test imports
from tests.chaind_eth_base import TestBase
logging.basicConfig(level=logging.DEBUG)
logg = logging.getLogger()
class TestFilter(TestBase):
def test_filter(self):
gas_oracle = RPCGasOracle(conn=self.rpc)
nonce_oracle = RPCNonceOracle(self.accounts[0], conn=self.rpc)
c = Gas(self.chain_spec, signer=self.signer, gas_oracle=gas_oracle, nonce_oracle=nonce_oracle)
(tx_hash, tx_raw_rlp_signed) = c.create(self.accounts[0], self.accounts[1], 1024, tx_format=TxFormat.RLP_SIGNED)
o = raw(tx_raw_rlp_signed)
self.rpc.do(o)
#o = receipt(tx_hash)
o = self.interface.tx_receipt(tx_hash)
rcpt = self.rpc.do(o)
#o = block_by_hash(rcpt['block_hash'])
o = self.interface.block_by_number(rcpt['block_number'])
block_src = self.rpc.do(o)
#block = Block(block_src)
block = self.interface.block_from_src(block_src)
dsn = dsn_from_config(db_config)
backend = SQLBackend(dsn, debug=bool(os.environ.get('DATABASE_DEBUG')))
adapter = EthAdapter(backend)
tx_raw_rlp_signed_bytes = bytes.fromhex(strip_0x(tx_raw_rlp_signed))
#adapter.add(tx_raw_rlp_signed_bytes, self.chain_spec, session=self.session_chainqueue)
adapter.add(tx_raw_rlp_signed, self.chain_spec, session=self.session_chainqueue)
set_ready(self.chain_spec, tx_hash, session=self.session_chainqueue)
set_reserved(self.chain_spec, tx_hash, session=self.session_chainqueue)
set_sent(self.chain_spec, tx_hash, session=self.session_chainqueue)
tx_src = unpack(tx_raw_rlp_signed_bytes, self.chain_spec)
tx_src = self.interface.src_normalize(tx_src)
tx = Tx(tx_src, block=block, rcpt=rcpt)
tx_repr = get_tx(self.chain_spec, tx_hash, session=self.session_chainqueue)
assert is_alive(tx_repr['status'])
fltr = StateFilter(self.chain_spec)
fltr.filter(self.rpc, block, tx, session=self.session_chainqueue)
tx_repr = get_tx(self.chain_spec, tx_hash, session=self.session_chainqueue)
assert not is_alive(tx_repr['status'])
if __name__ == '__main__':
unittest.main()

View File

@@ -1,15 +0,0 @@
# standard imports
import unittest
# test imports
from tests.chaind_eth_base import TestBase
class TestHelo(TestBase):
def test_helo(self):
pass
if __name__ == '__main__':
unittest.main()

73
tests/test_tx.py Normal file
View File

@@ -0,0 +1,73 @@
# standard imports
import os
import tempfile
import unittest
import shutil
import logging
import hashlib
# external imports
from chainlib.chain import ChainSpec
from chainqueue.cache import CacheTokenTx
from chainlib.error import RPCException
from chainlib.status import Status as TxStatus
from chaind.unittest.common import TestChaindFsBase
from chaind.driver import QueueDriver
from chaind.filter import StateFilter
from chainlib.eth.gas import Gas
from jsonrpc_std.parse import jsonrpc_validate_dict
from hexathon import strip_0x
# local imports
from chaind.eth.cache import EthCacheTx
from chaind.eth.dispatch import EthDispatcher
logging.basicConfig(level=logging.DEBUG)
logg = logging.getLogger()
class MockConn:
def __init__(self):
self.fails = []
self.last = None
def add_fail(self, v):
self.fails.append(v)
def do(self, v):
if v in self.fails:
raise RuntimeError(v)
v = jsonrpc_validate_dict(v)
if v['method'] != 'eth_sendRawTransaction':
raise ValueError('unsupported method {}'.format(v['method']))
self.last = v['params'][0]
class TestEthChaindFs(TestChaindFsBase):
def setUp(self):
self.cache_adapter = EthCacheTx
self.conn = MockConn()
self.dispatcher = EthDispatcher(self.conn)
super(TestEthChaindFs, self).setUp()
def test_deserialize(self):
data = "f8610d2a82520894eb3907ecad74a0013c259d5874ae7f22dcbcc95c8204008078a0ddbebd76701f6531e5ea42599f890268716e2bb38e3e125874f47595c2338049a00f5648d17b20efac8cb7ff275a510ebef6815e1599e29067821372b83eb1d28c" # valid RLP example data
hsh = self.adapter.put(data)
v = self.adapter.get(hsh)
self.assertEqual(data, v)
def test_dispatch(self):
data = "f8610d2a82520894eb3907ecad74a0013c259d5874ae7f22dcbcc95c8204008078a0ddbebd76701f6531e5ea42599f890268716e2bb38e3e125874f47595c2338049a00f5648d17b20efac8cb7ff275a510ebef6815e1599e29067821372b83eb1d28c" # valid RLP example data
hsh = self.adapter.put(data)
self.adapter.dispatch(hsh)
self.assertEqual(strip_0x(self.conn.last), strip_0x(data))
if __name__ == '__main__':
unittest.main()