rpc.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2021 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. rpc.py: Cryptocoin RPC library for the MMGen suite
  20. """
  21. import base64,json,asyncio
  22. from decimal import Decimal
  23. from .common import *
  24. from .obj import AsyncInit
  25. rpc_credentials_msg = '\n'+fmt("""
  26. Error: no {proto_name} RPC authentication method found
  27. RPC credentials must be supplied using one of the following methods:
  28. A) If daemon is local and running as same user as you:
  29. - no credentials required, or matching rpcuser/rpcpassword and
  30. rpc_user/rpc_password values in {cf_name}.conf and mmgen.cfg
  31. B) If daemon is running remotely or as different user:
  32. - matching credentials in {cf_name}.conf and mmgen.cfg as described above
  33. The --rpc-user/--rpc-password options may be supplied on the MMGen command line.
  34. They override the corresponding values in mmgen.cfg. Set them to an empty string
  35. to use cookie authentication with a local server when the options are set
  36. in mmgen.cfg.
  37. For better security, rpcauth should be used in {cf_name}.conf instead of
  38. rpcuser/rpcpassword.
  39. """,strip_char='\t')
  40. def dmsg_rpc(fs,data=None,is_json=False):
  41. if g.debug_rpc:
  42. msg(fs if data == None else fs.format(pp_fmt(json.loads(data) if is_json else data)))
  43. class json_encoder(json.JSONEncoder):
  44. def default(self,obj):
  45. if isinstance(obj,Decimal):
  46. return str(obj)
  47. else:
  48. return json.JSONEncoder.default(self,obj)
  49. class RPCBackends:
  50. class base:
  51. def __init__(self,caller):
  52. self.host = caller.host
  53. self.port = caller.port
  54. self.proxy = caller.proxy
  55. self.url = caller.url
  56. self.timeout = caller.timeout
  57. self.http_hdrs = caller.http_hdrs
  58. self.make_host_path = caller.make_host_path
  59. class aiohttp(base):
  60. def __init__(self,caller):
  61. super().__init__(caller)
  62. self.session = g.session
  63. if caller.auth_type == 'basic':
  64. import aiohttp
  65. self.auth = aiohttp.BasicAuth(*caller.auth,encoding='UTF-8')
  66. else:
  67. self.auth = None
  68. async def run(self,payload,timeout,wallet):
  69. dmsg_rpc('\n RPC PAYLOAD data (aiohttp) ==>\n{}\n',payload)
  70. async with self.session.post(
  71. url = self.url + self.make_host_path(wallet),
  72. auth = self.auth,
  73. data = json.dumps(payload,cls=json_encoder),
  74. timeout = timeout or self.timeout,
  75. ) as res:
  76. return (await res.text(),res.status)
  77. class requests(base):
  78. def __init__(self,caller):
  79. super().__init__(caller)
  80. import requests,urllib3
  81. urllib3.disable_warnings()
  82. self.session = requests.Session()
  83. self.session.headers = caller.http_hdrs
  84. if caller.auth_type:
  85. auth = 'HTTP' + caller.auth_type.capitalize() + 'Auth'
  86. self.session.auth = getattr(requests.auth,auth)(*caller.auth)
  87. if self.proxy:
  88. self.session.proxies.update({
  89. 'http': f'socks5h://{self.proxy}',
  90. 'https': f'socks5h://{self.proxy}'
  91. })
  92. async def run(self,payload,timeout,wallet):
  93. dmsg_rpc('\n RPC PAYLOAD data (requests) ==>\n{}\n',payload)
  94. res = self.session.post(
  95. url = self.url + self.make_host_path(wallet),
  96. data = json.dumps(payload,cls=json_encoder),
  97. timeout = timeout or self.timeout,
  98. verify = False )
  99. return (res.content,res.status_code)
  100. class httplib(base):
  101. def __init__(self,caller):
  102. super().__init__(caller)
  103. import http.client
  104. self.session = http.client.HTTPConnection(caller.host,caller.port,caller.timeout)
  105. if caller.auth_type == 'basic':
  106. auth_str = f'{caller.auth.user}:{caller.auth.passwd}'
  107. auth_str_b64 = 'Basic ' + base64.b64encode(auth_str.encode()).decode()
  108. self.http_hdrs.update({ 'Host': self.host, 'Authorization': auth_str_b64 })
  109. fs = ' RPC AUTHORIZATION data ==> raw: [{}]\n{:>31}enc: [{}]\n'
  110. dmsg_rpc(fs.format(auth_str,'',auth_str_b64))
  111. async def run(self,payload,timeout,wallet):
  112. dmsg_rpc('\n RPC PAYLOAD data (httplib) ==>\n{}\n',payload)
  113. if timeout:
  114. import http.client
  115. s = http.client.HTTPConnection(self.host,self.port,timeout)
  116. else:
  117. s = self.session
  118. try:
  119. s.request(
  120. method = 'POST',
  121. url = self.make_host_path(wallet),
  122. body = json.dumps(payload,cls=json_encoder),
  123. headers = self.http_hdrs )
  124. r = s.getresponse() # => http.client.HTTPResponse instance
  125. except Exception as e:
  126. raise RPCFailure(str(e))
  127. return (r.read(),r.status)
  128. class curl(base):
  129. def __init__(self,caller):
  130. def gen_opts():
  131. for k,v in caller.http_hdrs.items():
  132. for s in ('--header',f'{k}: {v}'):
  133. yield s
  134. if caller.auth_type:
  135. """
  136. Authentication with curl is insecure, as it exposes the user's credentials
  137. via the command line. Use for testing only.
  138. """
  139. for s in ('--user',f'{caller.auth.user}:{caller.auth.passwd}'):
  140. yield s
  141. if caller.auth_type == 'digest':
  142. yield '--digest'
  143. if caller.network_proto == 'https' and caller.verify_server == False:
  144. yield '--insecure'
  145. super().__init__(caller)
  146. self.exec_opts = list(gen_opts()) + ['--silent']
  147. self.arg_max = 8192 # set way below system ARG_MAX, just to be safe
  148. async def run(self,payload,timeout,wallet):
  149. data = json.dumps(payload,cls=json_encoder)
  150. if len(data) > self.arg_max:
  151. return self.httplib(payload,timeout=timeout)
  152. dmsg_rpc('\n RPC PAYLOAD data (curl) ==>\n{}\n',payload)
  153. exec_cmd = [
  154. 'curl',
  155. '--proxy', f'socks5h://{self.proxy}' if self.proxy else '',
  156. '--connect-timeout', str(timeout or self.timeout),
  157. '--write-out', '%{http_code}',
  158. '--data-binary', data
  159. ] + self.exec_opts + [self.url + self.make_host_path(wallet)]
  160. dmsg_rpc(' RPC curl exec data ==>\n{}\n',exec_cmd)
  161. from subprocess import run,PIPE
  162. res = run(exec_cmd,stdout=PIPE,check=True).stdout.decode()
  163. # res = run(exec_cmd,stdout=PIPE,check=True,text='UTF-8').stdout # Python 3.7+
  164. return (res[:-3],int(res[-3:]))
  165. from collections import namedtuple
  166. auth_data = namedtuple('rpc_auth_data',['user','passwd'])
  167. class CallSigs:
  168. class Bitcoin:
  169. class bitcoin_core:
  170. @classmethod
  171. def createwallet(cls,wallet_name,no_keys=True,passphrase='',load_on_startup=True):
  172. """
  173. Quirk: when --datadir is specified (even if standard), wallet is created directly in
  174. datadir, otherwise in datadir/wallets
  175. """
  176. return (
  177. 'createwallet',
  178. wallet_name, # 1. wallet_name
  179. no_keys, # 2. disable_private_keys
  180. no_keys, # 3. blank (no keys or seed)
  181. passphrase, # 4. passphrase (empty string for non-encrypted)
  182. False, # 5. avoid_reuse (track address reuse)
  183. False, # 6. descriptors (native descriptor wallet)
  184. load_on_startup # 7. load_on_startup
  185. )
  186. class litecoin_core(bitcoin_core):
  187. @classmethod
  188. def createwallet(cls,wallet_name,no_keys=True,passphrase='',load_on_startup=True):
  189. return (
  190. 'createwallet',
  191. wallet_name, # 1. wallet_name
  192. no_keys, # 2. disable_private_keys
  193. no_keys, # 3. blank (no keys or seed)
  194. )
  195. class bitcoin_cash_node(litecoin_core): pass
  196. class Ethereum: pass
  197. class RPCClient(MMGenObject):
  198. json_rpc = True
  199. auth_type = None
  200. has_auth_cookie = False
  201. network_proto = 'http'
  202. host_path = ''
  203. proxy = None
  204. def __init__(self,host,port,test_connection=True):
  205. dmsg_rpc('=== {}.__init__() debug ==='.format(type(self).__name__))
  206. dmsg_rpc(f' cls [{type(self).__name__}] host [{host}] port [{port}]\n')
  207. if test_connection:
  208. import socket
  209. try:
  210. socket.create_connection((host,port),timeout=1).close()
  211. except:
  212. raise SocketError(f'Unable to connect to {host}:{port}')
  213. self.http_hdrs = { 'Content-Type': 'application/json' }
  214. self.url = f'{self.network_proto}://{host}:{port}{self.host_path}'
  215. self.host = host
  216. self.port = port
  217. self.timeout = g.http_timeout
  218. self.auth = None
  219. @staticmethod
  220. def make_host_path(foo):
  221. return ''
  222. def set_backend(self,backend=None):
  223. bn = backend or opt.rpc_backend
  224. if bn == 'auto':
  225. self.backend = {'linux':RPCBackends.httplib,'win':RPCBackends.curl}[g.platform](self)
  226. else:
  227. self.backend = getattr(RPCBackends,bn)(self)
  228. def set_auth(self):
  229. """
  230. MMGen's credentials override coin daemon's
  231. """
  232. if g.rpc_user:
  233. user,passwd = (g.rpc_user,g.rpc_password)
  234. else:
  235. user,passwd = self.get_daemon_cfg_options(('rpcuser','rpcpassword')).values()
  236. if user and passwd:
  237. self.auth = auth_data(user,passwd)
  238. return
  239. if self.has_auth_cookie:
  240. cookie = self.get_daemon_auth_cookie()
  241. if cookie:
  242. self.auth = auth_data(*cookie.split(':'))
  243. return
  244. die(1,rpc_credentials_msg.format(
  245. proto_name = self.proto.name,
  246. cf_name = (self.proto.is_fork_of or self.proto.name).lower(),
  247. ))
  248. # Call family of methods - direct-to-daemon RPC call:
  249. # positional params are passed to the daemon, 'timeout' and 'wallet' kwargs to the backend
  250. async def call(self,method,*params,timeout=None,wallet=None):
  251. """
  252. default call: call with param list unrolled, exactly as with cli
  253. """
  254. if method == g.rpc_fail_on_command:
  255. method = 'badcommand_' + method
  256. return await self.process_http_resp(self.backend.run(
  257. payload = {'id': 1, 'jsonrpc': '2.0', 'method': method, 'params': params },
  258. timeout = timeout,
  259. wallet = wallet
  260. ))
  261. async def batch_call(self,method,param_list,timeout=None,wallet=None):
  262. """
  263. Make a single call with a list of tuples as first argument
  264. For RPC calls that return a list of results
  265. """
  266. return await self.process_http_resp(self.backend.run(
  267. payload = [{
  268. 'id': n,
  269. 'jsonrpc': '2.0',
  270. 'method': method,
  271. 'params': params } for n,params in enumerate(param_list,1) ],
  272. timeout = timeout,
  273. wallet = wallet
  274. ),batch=True)
  275. async def gathered_call(self,method,args_list,timeout=None,wallet=None):
  276. """
  277. Perform multiple RPC calls, returning results in a list
  278. Can be called two ways:
  279. 1) method = methodname, args_list = [args_tuple1, args_tuple2,...]
  280. 2) method = None, args_list = [(methodname1,args_tuple1), (methodname2,args_tuple2), ...]
  281. """
  282. cmd_list = args_list if method == None else tuple(zip([method] * len(args_list), args_list))
  283. cur_pos = 0
  284. chunk_size = 1024
  285. ret = []
  286. while cur_pos < len(cmd_list):
  287. tasks = [self.process_http_resp(self.backend.run(
  288. payload = {'id': n, 'jsonrpc': '2.0', 'method': method, 'params': params },
  289. timeout = timeout,
  290. wallet = wallet
  291. )) for n,(method,params) in enumerate(cmd_list[cur_pos:chunk_size+cur_pos],1)]
  292. ret.extend(await asyncio.gather(*tasks))
  293. cur_pos += chunk_size
  294. return ret
  295. # Icall family of methods - indirect RPC call using CallSigs mechanism:
  296. # - 'timeout' and 'wallet' kwargs are passed to corresponding Call method
  297. # - remaining kwargs are passed to CallSigs method
  298. # - CallSigs method returns method and positional params for Call method
  299. def icall(self,method,**kwargs):
  300. timeout = kwargs.pop('timeout',None)
  301. wallet = kwargs.pop('wallet',None)
  302. return self.call(
  303. *getattr(self.call_sigs,method)(**kwargs),
  304. timeout = timeout,
  305. wallet = wallet )
  306. async def process_http_resp(self,coro,batch=False):
  307. text,status = await coro
  308. if status == 200:
  309. dmsg_rpc(' RPC RESPONSE data ==>\n{}\n',text,is_json=True)
  310. if batch:
  311. return [r['result'] for r in json.loads(text,parse_float=Decimal)]
  312. else:
  313. try:
  314. if self.json_rpc:
  315. return json.loads(text,parse_float=Decimal)['result']
  316. else:
  317. return json.loads(text,parse_float=Decimal)
  318. except:
  319. t = json.loads(text)
  320. try:
  321. m = t['error']['message']
  322. except:
  323. try: m = t['error']
  324. except: m = t
  325. raise RPCFailure(m)
  326. else:
  327. import http
  328. m,s = ( '', http.HTTPStatus(status) )
  329. if text:
  330. try:
  331. m = json.loads(text)['error']['message']
  332. except:
  333. try: m = text.decode()
  334. except: m = text
  335. raise RPCFailure(f'{s.value} {s.name}: {m}')
  336. class BitcoinRPCClient(RPCClient,metaclass=AsyncInit):
  337. auth_type = 'basic'
  338. has_auth_cookie = True
  339. async def __init__(self,proto,daemon,backend):
  340. self.proto = proto
  341. self.daemon = daemon
  342. self.call_sigs = getattr(getattr(CallSigs,proto.base_proto),daemon.id,None)
  343. super().__init__(
  344. host = 'localhost' if g.test_suite else (g.rpc_host or 'localhost'),
  345. port = daemon.rpc_port )
  346. self.set_auth() # set_auth() requires cookie, so must be called after __init__() tests daemon is listening
  347. self.set_backend(backend) # backend requires self.auth
  348. self.cached = {}
  349. (
  350. self.cached['networkinfo'],
  351. self.blockcount,
  352. self.cached['blockchaininfo'],
  353. block0
  354. ) = await self.gathered_call(None, (
  355. ('getnetworkinfo',()),
  356. ('getblockcount',()),
  357. ('getblockchaininfo',()),
  358. ('getblockhash',(0,)),
  359. ))
  360. self.daemon_version = self.cached['networkinfo']['version']
  361. self.daemon_version_str = self.cached['networkinfo']['subversion']
  362. self.chain = self.cached['blockchaininfo']['chain']
  363. tip = await self.call('getblockhash',self.blockcount)
  364. self.cur_date = (await self.call('getblockheader',tip))['time']
  365. if self.chain != 'regtest':
  366. self.chain += 'net'
  367. assert self.chain in self.proto.networks
  368. async def check_chainfork_mismatch(block0):
  369. try:
  370. if block0 != self.proto.block0:
  371. raise ValueError(f'Invalid Genesis block for {self.proto.cls_name} protocol')
  372. for fork in self.proto.forks:
  373. if fork.height == None or self.blockcount < fork.height:
  374. break
  375. if fork.hash != await self.call('getblockhash',fork.height):
  376. die(3,f'Bad block hash at fork block {fork.height}. Is this the {fork.name} chain?')
  377. except Exception as e:
  378. die(2,'{!s}\n{c!r} requested, but this is not the {c} chain!'.format(e,c=self.proto.coin))
  379. if self.chain == 'mainnet': # skip this for testnet, as Genesis block may change
  380. await check_chainfork_mismatch(block0)
  381. self.caps = ('full_node',)
  382. for func,cap in (
  383. ('setlabel','label_api'),
  384. ('signrawtransactionwithkey','sign_with_key') ):
  385. if len((await self.call('help',func)).split('\n')) > 3:
  386. self.caps += (cap,)
  387. if not (g.prog_name == 'mmgen-regtest' or g.bob or g.alice):
  388. await self.check_tracking_wallet()
  389. async def check_tracking_wallet(self,wallet_checked=[]):
  390. if not wallet_checked:
  391. wallets = await self.call('listwallets')
  392. if len(wallets) == 0:
  393. wname = self.daemon.tracking_wallet_name
  394. await self.icall('createwallet',wallet_name=wname)
  395. ymsg(f'Created {self.daemon.coind_name} wallet {wname!r}')
  396. elif len(wallets) > 1: # support only one loaded wallet for now
  397. rdie(2,f'ERROR: more than one {self.daemon.coind_name} wallet loaded: {wallets}')
  398. wallet_checked.append(True)
  399. def get_daemon_cfg_fn(self):
  400. # Use dirname() to remove 'bob' or 'alice' component
  401. return os.path.join(
  402. (os.path.dirname(g.data_dir) if self.proto.regtest else self.daemon.datadir),
  403. self.daemon.cfg_file )
  404. def get_daemon_auth_cookie_fn(self):
  405. return os.path.join(self.daemon.network_datadir,'.cookie')
  406. def get_daemon_cfg_options(self,req_keys):
  407. fn = self.get_daemon_cfg_fn()
  408. try:
  409. lines = get_lines_from_file(fn,'',silent=not opt.verbose)
  410. except:
  411. vmsg(f'Warning: {fn!r} does not exist or is unreadable')
  412. return dict((k,None) for k in req_keys)
  413. def gen():
  414. for key in req_keys:
  415. val = None
  416. for l in lines:
  417. if l.startswith(key):
  418. res = l.split('=',1)
  419. if len(res) == 2 and not ' ' in res[1].strip():
  420. val = res[1].strip()
  421. yield (key,val)
  422. return dict(gen())
  423. def get_daemon_auth_cookie(self):
  424. fn = self.get_daemon_auth_cookie_fn()
  425. return get_lines_from_file(fn,'')[0] if file_is_readable(fn) else ''
  426. @staticmethod
  427. def make_host_path(wallet):
  428. return (
  429. '/wallet/{}'.format('bob' if g.bob else 'alice') if (g.bob or g.alice) else
  430. '/wallet/{}'.format(wallet) if wallet else '/'
  431. )
  432. def info(self,info_id):
  433. def segwit_is_active():
  434. d = self.cached['blockchaininfo']
  435. if d['chain'] == 'regtest':
  436. return True
  437. try:
  438. if d['softforks']['segwit']['active'] == True:
  439. return True
  440. except:
  441. pass
  442. try:
  443. if d['bip9_softforks']['segwit']['status'] == 'active':
  444. return True
  445. except:
  446. pass
  447. if g.test_suite:
  448. return True
  449. return False
  450. return locals()[info_id]()
  451. rpcmethods = (
  452. 'backupwallet',
  453. 'createrawtransaction',
  454. 'decoderawtransaction',
  455. 'disconnectnode',
  456. 'estimatefee',
  457. 'estimatesmartfee',
  458. 'getaddressesbyaccount',
  459. 'getaddressesbylabel',
  460. 'getblock',
  461. 'getblockchaininfo',
  462. 'getblockcount',
  463. 'getblockhash',
  464. 'getblockheader',
  465. 'getblockstats', # mmgen-node-tools
  466. 'getmempoolinfo',
  467. 'getmempoolentry',
  468. 'getnettotals',
  469. 'getnetworkinfo',
  470. 'getpeerinfo',
  471. 'getrawmempool',
  472. 'getmempoolentry',
  473. 'getrawtransaction',
  474. 'gettransaction',
  475. 'importaddress',
  476. 'listaccounts',
  477. 'listlabels',
  478. 'listunspent',
  479. 'setlabel',
  480. 'sendrawtransaction',
  481. 'signrawtransaction',
  482. 'signrawtransactionwithkey', # method new to Core v0.17.0
  483. 'validateaddress',
  484. 'walletpassphrase',
  485. )
  486. class EthereumRPCClient(RPCClient,metaclass=AsyncInit):
  487. async def __init__(self,proto,daemon,backend):
  488. self.proto = proto
  489. self.daemon = daemon
  490. self.call_sigs = getattr(getattr(CallSigs,proto.base_proto),daemon.id,None)
  491. super().__init__(
  492. host = 'localhost' if g.test_suite else (g.rpc_host or 'localhost'),
  493. port = daemon.rpc_port )
  494. self.set_backend(backend)
  495. vi,bh,ci = await self.gathered_call(None, (
  496. ('web3_clientVersion',()),
  497. ('eth_getBlockByNumber',('latest',False)),
  498. ('eth_chainId',()),
  499. ))
  500. import re
  501. vip = re.match(self.daemon.version_pat,vi,re.ASCII)
  502. if not vip:
  503. ydie(1,fmt(f"""
  504. Aborting on daemon mismatch:
  505. Requested daemon: {self.daemon.id}
  506. Running daemon: {vi}
  507. """,strip_char='\t').rstrip())
  508. self.daemon_version = int('{:d}{:03d}{:03d}'.format(*[int(e) for e in vip.groups()]))
  509. self.daemon_version_str = '{}.{}.{}'.format(*vip.groups())
  510. self.daemon_version_info = vi
  511. self.blockcount = int(bh['number'],16)
  512. self.cur_date = int(bh['timestamp'],16)
  513. self.caps = ()
  514. from .obj import Int
  515. if self.daemon.id in ('parity','openethereum'):
  516. if (await self.call('parity_nodeKind'))['capability'] == 'full':
  517. self.caps += ('full_node',)
  518. self.chainID = None if ci == None else Int(ci,16) # parity/oe return chainID only for dev chain
  519. self.chain = (await self.call('parity_chain')).replace(' ','_').replace('_testnet','')
  520. elif self.daemon.id in ('geth','erigon'):
  521. if self.daemon.network == 'mainnet':
  522. daemon_warning(self.daemon.id)
  523. self.caps += ('full_node',)
  524. self.chainID = Int(ci,16)
  525. self.chain = self.proto.chain_ids[self.chainID]
  526. rpcmethods = (
  527. 'eth_blockNumber',
  528. 'eth_call',
  529. # Returns the EIP155 chain ID used for transaction signing at the current best block.
  530. # Parity: Null is returned if not available, ID not required in transactions
  531. # Erigon: always returns ID, requires ID in transactions
  532. 'eth_chainId',
  533. 'eth_gasPrice',
  534. 'eth_getBalance',
  535. 'eth_getCode',
  536. 'eth_getTransactionCount',
  537. 'eth_getTransactionReceipt',
  538. 'eth_sendRawTransaction',
  539. 'parity_chain',
  540. 'parity_nodeKind',
  541. 'parity_pendingTransactions',
  542. 'txpool_content',
  543. )
  544. class MoneroRPCClient(RPCClient):
  545. auth_type = None
  546. network_proto = 'https'
  547. host_path = '/json_rpc'
  548. verify_server = False
  549. def __init__(self,host,port,user,passwd,test_connection=True,proxy=None):
  550. if proxy is not None:
  551. from .obj import IPPort
  552. self.proxy = IPPort(proxy)
  553. test_connection = False
  554. if host.endswith('.onion'):
  555. self.network_proto = 'http'
  556. super().__init__(host,port,test_connection)
  557. if self.auth_type:
  558. self.auth = auth_data(user,passwd)
  559. if True:
  560. self.set_backend('requests')
  561. else: # insecure, for debugging only
  562. self.set_backend('curl')
  563. self.backend.exec_opts.remove('--silent')
  564. self.backend.exec_opts.append('--verbose')
  565. async def call(self,method,*params,**kwargs):
  566. assert params == (), f'{type(self).__name__}.call() accepts keyword arguments only'
  567. return await self.process_http_resp(self.backend.run(
  568. payload = {'id': 0, 'jsonrpc': '2.0', 'method': method, 'params': kwargs },
  569. timeout = 3600, # allow enough time to sync ≈1,000,000 blocks
  570. wallet = None
  571. ))
  572. rpcmethods = ( 'get_info', )
  573. class MoneroRPCClientRaw(MoneroRPCClient):
  574. json_rpc = False
  575. host_path = '/'
  576. async def call(self,method,*params,**kwargs):
  577. assert params == (), f'{type(self).__name__}.call() accepts keyword arguments only'
  578. return await self.process_http_resp(self.backend.run(
  579. payload = kwargs,
  580. timeout = self.timeout,
  581. wallet = method
  582. ))
  583. @staticmethod
  584. def make_host_path(arg):
  585. return arg
  586. rpcmethods = ( 'get_height', 'send_raw_transaction' )
  587. class MoneroWalletRPCClient(MoneroRPCClient):
  588. auth_type = 'digest'
  589. rpcmethods = (
  590. 'get_version',
  591. 'get_height', # sync height of the open wallet
  592. 'get_balance', # account_index=0, address_indices=[]
  593. 'create_wallet', # filename, password, language="English"
  594. 'open_wallet', # filename, password
  595. 'close_wallet',
  596. 'restore_deterministic_wallet', # name,password,seed (restore_height,language,seed_offset,autosave_current)
  597. 'refresh', # start_height
  598. )
  599. class daemon_warning(oneshot_warning):
  600. class geth:
  601. color = 'yellow'
  602. message = 'Geth has not been tested on mainnet. You may experience problems.'
  603. class erigon:
  604. color = 'red'
  605. message = 'Erigon support is EXPERIMENTAL. Use at your own risk!!!'
  606. class version:
  607. color = 'yellow'
  608. message = 'ignoring unsupported {} daemon version at user request'
  609. def handle_unsupported_daemon_version(rpc,name,warn_only):
  610. if warn_only:
  611. daemon_warning('version',div=name,fmt_args=[rpc.daemon.coind_name])
  612. else:
  613. name = rpc.daemon.coind_name
  614. rdie(1,'\n'+fmt(f"""
  615. The running {name} daemon has version {rpc.daemon_version_str}.
  616. This version of MMGen is tested only on {name} v{rpc.daemon.coind_version_str} and below.
  617. To avoid this error, downgrade your daemon to a supported version.
  618. Alternatively, you may invoke the command with the --ignore-daemon-version
  619. option, in which case you proceed at your own risk.
  620. """,indent=' '))
  621. async def rpc_init(proto,backend=None,daemon=None,ignore_daemon_version=False):
  622. if not 'rpc' in proto.mmcaps:
  623. die(1,f'Coin daemon operations not supported for {proto.name} protocol!')
  624. from .daemon import CoinDaemon
  625. rpc = await {
  626. 'Bitcoin': BitcoinRPCClient,
  627. 'Ethereum': EthereumRPCClient,
  628. }[proto.base_proto](
  629. proto = proto,
  630. daemon = daemon or CoinDaemon(proto=proto,test_suite=g.test_suite),
  631. backend = backend or opt.rpc_backend )
  632. if rpc.daemon_version > rpc.daemon.coind_version:
  633. handle_unsupported_daemon_version(
  634. rpc,
  635. proto.name,
  636. ignore_daemon_version or proto.ignore_daemon_version or g.ignore_daemon_version )
  637. if rpc.chain not in proto.chain_names:
  638. raise RPCChainMismatch('\n'+fmt(f"""
  639. Protocol: {proto.cls_name}
  640. Valid chain names: {fmt_list(proto.chain_names,fmt='bare')}
  641. RPC client chain: {rpc.chain}
  642. """,indent=' ').rstrip())
  643. if g.bogus_wallet_data:
  644. rpc.blockcount = 1000000
  645. return rpc