rpc.py 23 KB

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