rpc.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2018 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 httplib,base64,json
  22. from mmgen.common import *
  23. from decimal import Decimal
  24. def dmsg_rpc(s):
  25. if g.debug_rpc: msg(s)
  26. class RPCFailure(Exception): pass
  27. class CoinDaemonRPCConnection(object):
  28. auth = True
  29. db_fs = ' host [{h}] port [{p}] user [{u}] passwd [{pw}] auth_cookie [{c}]\n'
  30. def __init__(self,host=None,port=None,user=None,passwd=None,auth_cookie=None):
  31. dmsg_rpc('=== {}.__init__() debug ==='.format(type(self).__name__))
  32. dmsg_rpc(self.db_fs.format(h=host,p=port,u=user,pw=passwd,c=auth_cookie))
  33. import socket
  34. try:
  35. socket.create_connection((host,port),timeout=3).close()
  36. except:
  37. die(1,'Unable to connect to {}:{}'.format(host,port))
  38. if not self.auth:
  39. pass
  40. elif user and passwd:
  41. self.auth_str = '{}:{}'.format(user,passwd)
  42. elif auth_cookie:
  43. self.auth_str = auth_cookie
  44. else:
  45. msg('Error: no {} RPC authentication method found'.format(g.proto.name.capitalize()))
  46. if passwd: die(1,"'rpcuser' entry not found in {}.conf or mmgen.cfg".format(g.proto.name))
  47. elif user: die(1,"'rpcpassword' entry not found in {}.conf or mmgen.cfg".format(g.proto.name))
  48. else:
  49. m1 = 'Either provide rpcuser/rpcpassword in {pn}.conf or mmgen.cfg\n'
  50. m2 = '(or, alternatively, copy the authentication cookie to the {pnu}\n'
  51. m3 = 'data dir if {pnm} and {dn} are running as different users)'
  52. die(1,(m1+m2+m3).format(
  53. pn=g.proto.name,
  54. pnu=g.proto.name.capitalize(),
  55. dn=g.proto.daemon_name,
  56. pnm=g.proj_name))
  57. self.host = host
  58. self.port = port
  59. for method in self.rpcmethods:
  60. exec '{c}.{m} = lambda self,*args,**kwargs: self.request("{m}",*args,**kwargs)'.format(
  61. c=type(self).__name__,m=method)
  62. # Normal mode: call with arg list unrolled, exactly as with cli
  63. # Batch mode: call with list of arg lists as first argument
  64. # kwargs are for local use and are not passed to server
  65. # By default, dies with an error msg on all errors and exceptions
  66. # on_fail is one of 'die' (default), 'return', 'silent', 'raise'
  67. # With on_fail='return', returns 'rpcfail',(resp_object,(die_args))
  68. def request(self,cmd,*args,**kwargs):
  69. if os.getenv('MMGEN_RPC_FAIL_ON_COMMAND') == cmd:
  70. cmd = 'badcommand_' + cmd
  71. cf = { 'timeout':g.http_timeout, 'batch':False, 'on_fail':'die' }
  72. for k in cf:
  73. if k in kwargs and kwargs[k]: cf[k] = kwargs[k]
  74. hc = httplib.HTTPConnection(self.host, self.port, False, cf['timeout'])
  75. if cf['batch']:
  76. p = [{'method':cmd,'params':r,'id':n,'jsonrpc':'2.0'} for n,r in enumerate(args[0],1)]
  77. else:
  78. p = {'method':cmd,'params':args,'id':1,'jsonrpc':'2.0'}
  79. def do_fail(*args):
  80. if cf['on_fail'] in ('return','silent'):
  81. return 'rpcfail',args
  82. try: s = u'{}'.format(args[2])
  83. except: s = repr(args[2])
  84. if cf['on_fail'] == 'raise':
  85. raise RPCFailure,s
  86. elif cf['on_fail'] == 'die':
  87. die(args[1],yellow(s))
  88. dmsg_rpc('=== request() debug ===')
  89. dmsg_rpc(' RPC POST data ==> {}\n'.format(p))
  90. class MyJSONEncoder(json.JSONEncoder):
  91. def default(self,obj):
  92. if isinstance(obj,g.proto.coin_amt):
  93. return g.proto.get_rpc_coin_amt_type()(obj)
  94. return json.JSONEncoder.default(self,obj)
  95. http_hdr = { 'Content-Type': 'application/json' }
  96. if self.auth:
  97. fs = ' RPC AUTHORIZATION data ==> raw: [{}]\n{:>31}enc: [Basic {}]\n'
  98. as_enc = base64.b64encode(self.auth_str)
  99. dmsg_rpc(fs.format(self.auth_str,'',as_enc))
  100. http_hdr.update({ 'Host':self.host, 'Authorization':'Basic {}'.format(as_enc) })
  101. try:
  102. hc.request('POST','/',json.dumps(p,cls=MyJSONEncoder),http_hdr)
  103. except Exception as e:
  104. m = '{}\nUnable to connect to {} at {}:{}'
  105. return do_fail(None,2,m.format(e,g.proto.daemon_name,self.host,self.port))
  106. try:
  107. r = hc.getresponse() # returns HTTPResponse instance
  108. except Exception:
  109. m = 'Unable to connect to {} at {}:{} (but port is bound?)'
  110. return do_fail(None,2,m.format(g.proto.daemon_name,self.host,self.port))
  111. dmsg_rpc(' RPC GETRESPONSE data ==> {}\n'.format(r.__dict__))
  112. if r.status != 200:
  113. if cf['on_fail'] not in ('silent','raise'):
  114. msg_r(yellow('{} RPC Error: '.format(g.proto.daemon_name.capitalize())))
  115. msg(red('{} {}'.format(r.status,r.reason)))
  116. e1 = r.read()
  117. try:
  118. e3 = json.loads(e1)['error']
  119. e2 = '{} (code {})'.format(e3['message'],e3['code'])
  120. except:
  121. e2 = str(e1)
  122. return do_fail(r,1,e2)
  123. r2 = r.read().decode('utf8')
  124. dmsg_rpc(u' RPC REPLY data ==> {}\n'.format(r2))
  125. if not r2:
  126. return do_fail(r,2,'Error: empty reply')
  127. r3 = json.loads(r2,parse_float=Decimal)
  128. ret = []
  129. for resp in r3 if cf['batch'] else [r3]:
  130. if 'error' in resp and resp['error'] != None:
  131. return do_fail(r,1,'{} returned an error: {}'.format(
  132. g.proto.daemon_name.capitalize(),resp['error']))
  133. elif 'result' not in resp:
  134. return do_fail(r,1, 'Missing JSON-RPC result\n' + repr(resps))
  135. else:
  136. ret.append(resp['result'])
  137. return ret if cf['batch'] else ret[0]
  138. rpcmethods = (
  139. 'backupwallet',
  140. 'createrawtransaction',
  141. 'decoderawtransaction',
  142. 'disconnectnode',
  143. 'estimatefee',
  144. 'estimatesmartfee',
  145. 'getaddressesbyaccount',
  146. 'getbalance',
  147. 'getblock',
  148. 'getblockchaininfo',
  149. 'getblockcount',
  150. 'getblockhash',
  151. 'getmempoolinfo',
  152. 'getmempoolentry',
  153. 'getnettotals',
  154. 'getnetworkinfo',
  155. 'getpeerinfo',
  156. 'getrawmempool',
  157. 'getmempoolentry',
  158. 'getrawtransaction',
  159. 'gettransaction',
  160. 'importaddress',
  161. 'listaccounts',
  162. 'listunspent',
  163. 'sendrawtransaction',
  164. 'signrawtransaction',
  165. 'validateaddress',
  166. 'walletpassphrase',
  167. )
  168. class EthereumRPCConnection(CoinDaemonRPCConnection):
  169. auth = False
  170. db_fs = ' host [{h}] port [{p}]\n'
  171. rpcmethods = (
  172. 'eth_accounts',
  173. 'eth_blockNumber',
  174. 'eth_call',
  175. 'eth_gasPrice',
  176. 'eth_getBalance',
  177. 'eth_getBlockByHash',
  178. 'eth_getBlockByNumber',
  179. 'eth_getCode',
  180. 'eth_getTransactionByHash',
  181. 'eth_getTransactionReceipt',
  182. 'eth_protocolVersion',
  183. 'eth_sendRawTransaction',
  184. 'eth_signTransaction',
  185. 'eth_syncing',
  186. 'net_listening',
  187. 'net_peerCount',
  188. 'net_version',
  189. 'parity_chain',
  190. # Returns the EIP155 chain ID used for transaction signing at the current best block.
  191. # Null is returned if not available.
  192. 'parity_chainId',
  193. 'parity_chainStatus',
  194. 'parity_composeTransaction',
  195. 'parity_gasCeilTarget',
  196. 'parity_gasFloorTarget',
  197. 'parity_localTransactions',
  198. 'parity_minGasPrice',
  199. 'parity_mode',
  200. 'parity_netPeers',
  201. 'parity_nextNonce',
  202. 'parity_nodeKind',
  203. 'parity_nodeName',
  204. 'parity_pendingTransactions',
  205. 'parity_pendingTransactionsStats',
  206. 'parity_versionInfo',
  207. )
  208. def rpc_error(ret):
  209. return type(ret) is tuple and ret and ret[0] == 'rpcfail'
  210. def rpc_errmsg(ret): return ret[1][2]