Add evm connector

This commit is contained in:
nolash
2021-02-03 20:55:39 +01:00
parent e8370de015
commit 66c0fd0b51
19 changed files with 650 additions and 29 deletions

View File

View File

@@ -0,0 +1,21 @@
from cic_syncer.client import translate
translations = {
'block_number': 'hex_to_int',
}
class EVMResponse:
def __init__(self, item, response_object):
self.response_object = response_object
self.item = item
self.fn = getattr(translate, translations[self.item])
def get_error(self):
return self.response_object.get('error')
def get_result(self):
return self.fn(self.response_object.get('result'))

View File

@@ -0,0 +1,37 @@
import uuid
import json
import websocket
from .response import EVMResponse
from cic_syncer.error import RequestError
class EVMWebsocketClient:
def __init__(self, url):
self.url = url
self.conn = websocket.create_connection(url)
def __del__(self):
self.conn.close()
def block_number(self):
req_id = str(uuid.uuid4())
req = {
'jsonrpc': '2.0',
'method': 'eth_blockNumber',
'id': str(req_id),
'params': [],
}
self.conn.send(json.dumps(req))
r = self.conn.recv()
res = EVMResponse('block_number', json.loads(r))
err = res.get_error()
if err != None:
raise RequestError(err)
return res.get_result()

View File

@@ -0,0 +1,21 @@
import re
re_hex = r'^[0-9a-fA-Z]+$'
def is_hex(hx):
m = re.match(re_hex, hx)
if m == None:
raise ValueError('not valid hex {}'.format(hx))
return hx
def strip_0x(hx):
if len(hx) >= 2 and hx[:2] == '0x':
hx = hx[2:]
return is_hex(hx)
def hex_to_int(hx, endianness='big'):
hx = strip_0x(hx)
b = bytes.fromhex(hx)
return int.from_bytes(b, endianness)