rpc.py 23 KB

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