chainsyncer/chainsyncer/client/evm/websocket.py

91 lines
2.2 KiB
Python
Raw Normal View History

# standard imports
2021-02-03 21:57:26 +01:00
import logging
2021-02-03 20:55:39 +01:00
import uuid
import json
# third-party imports
2021-02-03 20:55:39 +01:00
import websocket
from hexathon import add_0x
2021-02-03 20:55:39 +01:00
# local imports
2021-02-03 20:55:39 +01:00
from .response import EVMResponse
2021-02-11 09:02:17 +01:00
from chainsyncer.error import RequestError
from chainsyncer.client.evm.response import EVMBlock
2021-02-03 20:55:39 +01:00
2021-02-03 21:57:26 +01:00
logg = logging.getLogger()
2021-02-03 20:55:39 +01:00
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()
2021-02-03 21:57:26 +01:00
2021-02-11 09:02:17 +01:00
def block_by_integer(self, n):
2021-02-03 21:57:26 +01:00
req_id = str(uuid.uuid4())
nhx = '0x' + n.to_bytes(8, 'big').hex()
req = {
'jsonrpc': '2.0',
'method': 'eth_getBlockByNumber',
'id': str(req_id),
'params': [nhx, False],
}
self.conn.send(json.dumps(req))
r = self.conn.recv()
res = EVMResponse('get_block', json.loads(r))
err = res.get_error()
if err != None:
raise RequestError(err)
2021-02-03 23:03:39 +01:00
j = res.get_result()
if j == None:
return None
o = json.loads(j)
return EVMBlock(o['hash'], o)
2021-02-11 09:02:17 +01:00
def block_by_hash(self, hx_in):
2021-02-03 23:03:39 +01:00
req_id = str(uuid.uuid4())
hx = add_0x(hx_in)
2021-02-03 23:03:39 +01:00
req ={
'jsonrpc': '2.0',
'method': 'eth_getBlockByHash',
'id': str(req_id),
'params': [hx, False],
}
self.conn.send(json.dumps(req))
r = self.conn.recv()
res = EVMResponse('get_block', json.loads(r))
err = res.get_error()
if err != None:
raise RequestError(err)
2021-02-03 21:57:26 +01:00
2021-02-03 23:03:39 +01:00
j = res.get_result()
if j == None:
return None
o = json.loads(j)
return EVMBlock(o['hash'], o)