rpc.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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. auth_type = None
  195. has_auth_cookie = False
  196. network_proto = 'http'
  197. host_path = ''
  198. def __init__(self,host,port):
  199. dmsg_rpc('=== {}.__init__() debug ==='.format(type(self).__name__))
  200. dmsg_rpc(f' cls [{type(self).__name__}] host [{host}] port [{port}]\n')
  201. import socket
  202. try:
  203. socket.create_connection((host,port),timeout=1).close()
  204. except:
  205. raise SocketError(f'Unable to connect to {host}:{port}')
  206. self.http_hdrs = { 'Content-Type': 'application/json' }
  207. self.url = f'{self.network_proto}://{host}:{port}{self.host_path}'
  208. self.host = host
  209. self.port = port
  210. self.timeout = g.http_timeout
  211. self.auth = None
  212. @staticmethod
  213. def make_host_path(foo):
  214. return ''
  215. def set_backend(self,backend=None):
  216. bn = backend or opt.rpc_backend
  217. if bn == 'auto':
  218. self.backend = {'linux':RPCBackends.httplib,'win':RPCBackends.curl}[g.platform](self)
  219. else:
  220. self.backend = getattr(RPCBackends,bn)(self)
  221. def set_auth(self):
  222. """
  223. MMGen's credentials override coin daemon's
  224. """
  225. if g.rpc_user:
  226. user,passwd = (g.rpc_user,g.rpc_password)
  227. else:
  228. user,passwd = self.get_daemon_cfg_options(('rpcuser','rpcpassword')).values()
  229. if user and passwd:
  230. self.auth = auth_data(user,passwd)
  231. return
  232. if self.has_auth_cookie:
  233. cookie = self.get_daemon_auth_cookie()
  234. if cookie:
  235. self.auth = auth_data(*cookie.split(':'))
  236. return
  237. die(1,rpc_credentials_msg.format(
  238. proto_name = self.proto.name,
  239. cf_name = (self.proto.is_fork_of or self.proto.name).lower(),
  240. ))
  241. # Call family of methods - direct-to-daemon RPC call:
  242. # positional params are passed to the daemon, 'timeout' and 'wallet' kwargs to the backend
  243. async def call(self,method,*params,timeout=None,wallet=None):
  244. """
  245. default call: call with param list unrolled, exactly as with cli
  246. """
  247. if method == g.rpc_fail_on_command:
  248. method = 'badcommand_' + method
  249. return await self.process_http_resp(self.backend.run(
  250. payload = {'id': 1, 'jsonrpc': '2.0', 'method': method, 'params': params },
  251. timeout = timeout,
  252. wallet = wallet
  253. ))
  254. async def batch_call(self,method,param_list,timeout=None,wallet=None):
  255. """
  256. Make a single call with a list of tuples as first argument
  257. For RPC calls that return a list of results
  258. """
  259. return await self.process_http_resp(self.backend.run(
  260. payload = [{
  261. 'id': n,
  262. 'jsonrpc': '2.0',
  263. 'method': method,
  264. 'params': params } for n,params in enumerate(param_list,1) ],
  265. timeout = timeout,
  266. wallet = wallet
  267. ),batch=True)
  268. async def gathered_call(self,method,args_list,timeout=None,wallet=None):
  269. """
  270. Perform multiple RPC calls, returning results in a list
  271. Can be called two ways:
  272. 1) method = methodname, args_list = [args_tuple1, args_tuple2,...]
  273. 2) method = None, args_list = [(methodname1,args_tuple1), (methodname2,args_tuple2), ...]
  274. """
  275. cmd_list = args_list if method == None else tuple(zip([method] * len(args_list), args_list))
  276. cur_pos = 0
  277. chunk_size = 1024
  278. ret = []
  279. while cur_pos < len(cmd_list):
  280. tasks = [self.process_http_resp(self.backend.run(
  281. payload = {'id': n, 'jsonrpc': '2.0', 'method': method, 'params': params },
  282. timeout = timeout,
  283. wallet = wallet
  284. )) for n,(method,params) in enumerate(cmd_list[cur_pos:chunk_size+cur_pos],1)]
  285. ret.extend(await asyncio.gather(*tasks))
  286. cur_pos += chunk_size
  287. return ret
  288. # Icall family of methods - indirect RPC call using CallSigs mechanism:
  289. # - 'timeout' and 'wallet' kwargs are passed to corresponding Call method
  290. # - remaining kwargs are passed to CallSigs method
  291. # - CallSigs method returns method and positional params for Call method
  292. def icall(self,method,**kwargs):
  293. timeout = kwargs.pop('timeout',None)
  294. wallet = kwargs.pop('wallet',None)
  295. return self.call(
  296. *getattr(self.call_sigs,method)(**kwargs),
  297. timeout = timeout,
  298. wallet = wallet )
  299. async def process_http_resp(self,coro,batch=False):
  300. text,status = await coro
  301. if status == 200:
  302. dmsg_rpc(' RPC RESPONSE data ==>\n{}\n',text,is_json=True)
  303. if batch:
  304. return [r['result'] for r in json.loads(text,parse_float=Decimal,encoding='UTF-8')]
  305. else:
  306. try:
  307. return json.loads(text,parse_float=Decimal,encoding='UTF-8')['result']
  308. except:
  309. t = json.loads(text)
  310. try:
  311. m = t['error']['message']
  312. except:
  313. try: m = t['error']
  314. except: m = t
  315. raise RPCFailure(m)
  316. else:
  317. import http
  318. m,s = ( '', http.HTTPStatus(status) )
  319. if text:
  320. try:
  321. m = json.loads(text)['error']['message']
  322. except:
  323. try: m = text.decode()
  324. except: m = text
  325. raise RPCFailure(f'{s.value} {s.name}: {m}')
  326. class BitcoinRPCClient(RPCClient,metaclass=aInitMeta):
  327. auth_type = 'basic'
  328. has_auth_cookie = True
  329. def __init__(self,*args,**kwargs):
  330. pass
  331. async def __ainit__(self,proto,daemon,backend):
  332. self.proto = proto
  333. self.daemon = daemon
  334. self.call_sigs = getattr(getattr(CallSigs,proto.base_proto),daemon.id)
  335. super().__init__(
  336. host = 'localhost' if g.test_suite else (g.rpc_host or 'localhost'),
  337. port = daemon.rpc_port )
  338. self.set_auth() # set_auth() requires cookie, so must be called after __init__() tests daemon is listening
  339. self.set_backend(backend) # backend requires self.auth
  340. self.cached = {}
  341. (
  342. self.cached['networkinfo'],
  343. self.blockcount,
  344. self.cached['blockchaininfo'],
  345. block0
  346. ) = await self.gathered_call(None, (
  347. ('getnetworkinfo',()),
  348. ('getblockcount',()),
  349. ('getblockchaininfo',()),
  350. ('getblockhash',(0,)),
  351. ))
  352. self.daemon_version = self.cached['networkinfo']['version']
  353. self.daemon_version_str = self.cached['networkinfo']['subversion']
  354. self.chain = self.cached['blockchaininfo']['chain']
  355. tip = await self.call('getblockhash',self.blockcount)
  356. self.cur_date = (await self.call('getblockheader',tip))['time']
  357. if self.chain != 'regtest':
  358. self.chain += 'net'
  359. assert self.chain in self.proto.networks
  360. async def check_chainfork_mismatch(block0):
  361. try:
  362. if block0 != self.proto.block0:
  363. raise ValueError(f'Invalid Genesis block for {self.proto.cls_name} protocol')
  364. for fork in self.proto.forks:
  365. if fork.height == None or self.blockcount < fork.height:
  366. break
  367. if fork.hash != await self.call('getblockhash',fork.height):
  368. die(3,f'Bad block hash at fork block {fork.height}. Is this the {fork.name} chain?')
  369. except Exception as e:
  370. die(2,'{!s}\n{c!r} requested, but this is not the {c} chain!'.format(e,c=self.proto.coin))
  371. if self.chain == 'mainnet': # skip this for testnet, as Genesis block may change
  372. await check_chainfork_mismatch(block0)
  373. self.caps = ('full_node',)
  374. for func,cap in (
  375. ('setlabel','label_api'),
  376. ('signrawtransactionwithkey','sign_with_key') ):
  377. if len((await self.call('help',func)).split('\n')) > 3:
  378. self.caps += (cap,)
  379. if not (g.prog_name == 'mmgen-regtest' or g.bob or g.alice):
  380. await self.check_tracking_wallet()
  381. async def check_tracking_wallet(self,wallet_checked=[]):
  382. if not wallet_checked:
  383. wallets = await self.call('listwallets')
  384. if len(wallets) == 0:
  385. wname = self.daemon.tracking_wallet_name
  386. await self.icall('createwallet',wallet_name=wname)
  387. ymsg(f'Created {self.daemon.coind_name} wallet {wname!r}')
  388. elif len(wallets) > 1: # support only one loaded wallet for now
  389. rdie(2,f'ERROR: more than one {self.daemon.coind_name} wallet loaded: {wallets}')
  390. wallet_checked.append(True)
  391. def get_daemon_cfg_fn(self):
  392. # Use dirname() to remove 'bob' or 'alice' component
  393. return os.path.join(
  394. (os.path.dirname(g.data_dir) if self.proto.regtest else self.daemon.datadir),
  395. self.daemon.cfg_file )
  396. def get_daemon_auth_cookie_fn(self):
  397. return os.path.join( self.daemon.datadir, self.daemon.data_subdir, '.cookie' )
  398. def get_daemon_cfg_options(self,req_keys):
  399. fn = self.get_daemon_cfg_fn()
  400. try:
  401. lines = get_lines_from_file(fn,'',silent=not opt.verbose)
  402. except:
  403. vmsg(f'Warning: {fn!r} does not exist or is unreadable')
  404. return dict((k,None) for k in req_keys)
  405. def gen():
  406. for key in req_keys:
  407. val = None
  408. for l in lines:
  409. if l.startswith(key):
  410. res = l.split('=',1)
  411. if len(res) == 2 and not ' ' in res[1].strip():
  412. val = res[1].strip()
  413. yield (key,val)
  414. return dict(gen())
  415. def get_daemon_auth_cookie(self):
  416. fn = self.get_daemon_auth_cookie_fn()
  417. return get_lines_from_file(fn,'')[0] if file_is_readable(fn) else ''
  418. @staticmethod
  419. def make_host_path(wallet):
  420. return (
  421. '/wallet/{}'.format('bob' if g.bob else 'alice') if (g.bob or g.alice) else
  422. '/wallet/{}'.format(wallet) if wallet else '/'
  423. )
  424. def info(self,info_id):
  425. def segwit_is_active():
  426. d = self.cached['blockchaininfo']
  427. if d['chain'] == 'regtest':
  428. return True
  429. try:
  430. if d['softforks']['segwit']['active'] == True:
  431. return True
  432. except:
  433. pass
  434. try:
  435. if d['bip9_softforks']['segwit']['status'] == 'active':
  436. return True
  437. except:
  438. pass
  439. if g.test_suite:
  440. return True
  441. return False
  442. return locals()[info_id]()
  443. rpcmethods = (
  444. 'backupwallet',
  445. 'createrawtransaction',
  446. 'decoderawtransaction',
  447. 'disconnectnode',
  448. 'estimatefee',
  449. 'estimatesmartfee',
  450. 'getaddressesbyaccount',
  451. 'getaddressesbylabel',
  452. 'getblock',
  453. 'getblockchaininfo',
  454. 'getblockcount',
  455. 'getblockhash',
  456. 'getblockheader',
  457. 'getblockstats', # mmgen-node-tools
  458. 'getmempoolinfo',
  459. 'getmempoolentry',
  460. 'getnettotals',
  461. 'getnetworkinfo',
  462. 'getpeerinfo',
  463. 'getrawmempool',
  464. 'getmempoolentry',
  465. 'getrawtransaction',
  466. 'gettransaction',
  467. 'importaddress',
  468. 'listaccounts',
  469. 'listlabels',
  470. 'listunspent',
  471. 'setlabel',
  472. 'sendrawtransaction',
  473. 'signrawtransaction',
  474. 'signrawtransactionwithkey', # method new to Core v0.17.0
  475. 'validateaddress',
  476. 'walletpassphrase',
  477. )
  478. class EthereumRPCClient(RPCClient,metaclass=aInitMeta):
  479. def __init__(self,*args,**kwargs):
  480. pass
  481. async def __ainit__(self,proto,daemon,backend):
  482. self.proto = proto
  483. self.daemon = daemon
  484. self.call_sigs = getattr(getattr(CallSigs,proto.base_proto),daemon.id)
  485. super().__init__(
  486. host = 'localhost' if g.test_suite else (g.rpc_host or 'localhost'),
  487. port = daemon.rpc_port )
  488. self.set_backend(backend)
  489. self.blockcount = int(await self.call('eth_blockNumber'),16)
  490. vi,bh,ch,nk = await self.gathered_call(None, (
  491. ('parity_versionInfo',()),
  492. ('parity_getBlockHeaderByNumber',()),
  493. ('parity_chain',()),
  494. ('parity_nodeKind',()),
  495. ))
  496. self.daemon_version = int((
  497. lambda v: '{:d}{:03d}{:03d}'.format(v['major'],v['minor'],v['patch'])
  498. )(vi['version']))
  499. self.daemon_version_str = (
  500. lambda v: '{}.{}.{}'.format(v['major'],v['minor'],v['patch'])
  501. )(vi['version'])
  502. self.cur_date = int(bh['timestamp'],16)
  503. self.chain = ch.replace(' ','_')
  504. self.caps = ('full_node',) if nk['capability'] == 'full' else ()
  505. try:
  506. await self.call('eth_chainId')
  507. self.caps += ('eth_chainId',)
  508. except RPCFailure:
  509. pass
  510. rpcmethods = (
  511. 'eth_accounts',
  512. 'eth_blockNumber',
  513. 'eth_call',
  514. # Returns the EIP155 chain ID used for transaction signing at the current best block.
  515. # Null is returned if not available.
  516. 'eth_chainId',
  517. 'eth_gasPrice',
  518. 'eth_getBalance',
  519. 'eth_getBlockByHash',
  520. 'eth_getCode',
  521. 'eth_getTransactionByHash',
  522. 'eth_getTransactionReceipt',
  523. 'eth_protocolVersion',
  524. 'eth_sendRawTransaction',
  525. 'eth_signTransaction',
  526. 'eth_syncing',
  527. 'net_listening',
  528. 'net_peerCount',
  529. 'net_version',
  530. 'parity_chain',
  531. 'parity_chainId', # superseded by eth_chainId
  532. 'parity_chainStatus',
  533. 'parity_composeTransaction',
  534. 'parity_gasCeilTarget',
  535. 'parity_gasFloorTarget',
  536. 'parity_getBlockHeaderByNumber',
  537. 'parity_localTransactions',
  538. 'parity_minGasPrice',
  539. 'parity_mode',
  540. 'parity_netPeers',
  541. 'parity_nextNonce',
  542. 'parity_nodeKind',
  543. 'parity_nodeName',
  544. 'parity_pendingTransactions',
  545. 'parity_pendingTransactionsStats',
  546. 'parity_versionInfo',
  547. )
  548. class MoneroWalletRPCClient(RPCClient):
  549. auth_type = 'digest'
  550. network_proto = 'https'
  551. host_path = '/json_rpc'
  552. verify_server = False
  553. def __init__(self,host,port,user,passwd):
  554. super().__init__(host,port)
  555. self.auth = auth_data(user,passwd)
  556. if True:
  557. self.set_backend('requests')
  558. else: # insecure, for debugging only
  559. self.set_backend('curl')
  560. self.backend.exec_opts.remove('--silent')
  561. self.backend.exec_opts.append('--verbose')
  562. async def call(self,method,*params,**kwargs):
  563. assert params == (), f'{type(self).__name__}.call() accepts keyword arguments only'
  564. return await self.process_http_resp(self.backend.run(
  565. payload = {'id': 0, 'jsonrpc': '2.0', 'method': method, 'params': kwargs },
  566. timeout = 3600, # allow enough time to sync ≈1,000,000 blocks
  567. wallet = None
  568. ))
  569. rpcmethods = (
  570. 'get_version',
  571. 'get_height', # sync height of the open wallet
  572. 'get_balance', # account_index=0, address_indices=[]
  573. 'create_wallet', # filename, password, language="English"
  574. 'open_wallet', # filename, password
  575. 'close_wallet',
  576. 'restore_deterministic_wallet', # name,password,seed (restore_height,language,seed_offset,autosave_current)
  577. 'refresh', # start_height
  578. )
  579. def handle_unsupported_daemon_version(rpc,proto,ignore_daemon_version,warning_shown=[]):
  580. if ignore_daemon_version or proto.ignore_daemon_version or g.ignore_daemon_version:
  581. if not type(proto) in warning_shown:
  582. ymsg(f'WARNING: ignoring unsupported {rpc.daemon.coind_name} daemon version at user request')
  583. warning_shown.append(type(proto))
  584. else:
  585. rdie(1,fmt(
  586. """
  587. The running {} daemon has version {}.
  588. This version of MMGen is tested only on {} v{} and below.
  589. To avoid this error, downgrade your daemon to a supported version.
  590. Alternatively, you may invoke the command with the --ignore-daemon-version
  591. option, in which case you proceed at your own risk.
  592. """.format(
  593. rpc.daemon.coind_name,
  594. rpc.daemon_version_str,
  595. rpc.daemon.coind_name,
  596. rpc.daemon.coind_version_str,
  597. ),indent=' ').rstrip())
  598. async def rpc_init(proto,backend=None,daemon=None,ignore_daemon_version=False):
  599. if not 'rpc' in proto.mmcaps:
  600. die(1,f'Coin daemon operations not supported for {proto.name} protocol!')
  601. from .daemon import CoinDaemon
  602. rpc = await {
  603. 'Bitcoin': BitcoinRPCClient,
  604. 'Ethereum': EthereumRPCClient,
  605. }[proto.base_proto](
  606. proto = proto,
  607. daemon = daemon or CoinDaemon(proto=proto,test_suite=g.test_suite),
  608. backend = backend or opt.rpc_backend )
  609. if rpc.daemon_version > rpc.daemon.coind_version:
  610. handle_unsupported_daemon_version(rpc,proto,ignore_daemon_version)
  611. if proto.chain_name != rpc.chain:
  612. raise RPCChainMismatch(
  613. '{} protocol chain is {}, but coin daemon chain is {}'.format(
  614. proto.cls_name,
  615. proto.chain_name.upper(),
  616. rpc.chain.upper() ))
  617. if g.bogus_wallet_data:
  618. rpc.blockcount = 1000000
  619. return rpc