rpc.py 23 KB

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