rpc.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. def __init__(self,host=None,port=None,user=None,passwd=None,auth_cookie=None):
  29. dmsg_rpc('=== CoinDaemonRPCConnection.__init__() debug ===')
  30. dmsg_rpc(' host [{}] port [{}] user [{}] passwd [{}] auth_cookie [{}]\n'.format(
  31. host,port,user,passwd,auth_cookie))
  32. import socket
  33. try:
  34. socket.create_connection((host,port),timeout=3).close()
  35. except:
  36. die(1,'Unable to connect to {}:{}'.format(host,port))
  37. if user and passwd:
  38. self.auth_str = '{}:{}'.format(user,passwd)
  39. elif auth_cookie:
  40. self.auth_str = auth_cookie
  41. else:
  42. msg('Error: no {} RPC authentication method found'.format(g.proto.name.capitalize()))
  43. if passwd: die(1,"'rpcuser' entry not found in {}.conf or mmgen.cfg".format(g.proto.name))
  44. elif user: die(1,"'rpcpassword' entry not found in {}.conf or mmgen.cfg".format(g.proto.name))
  45. else:
  46. m1 = 'Either provide rpcuser/rpcpassword in {pn}.conf or mmgen.cfg\n'
  47. m2 = '(or, alternatively, copy the authentication cookie to the {pnu}\n'
  48. m3 = 'data dir if {pnm} and {dn} are running as different users)'
  49. die(1,(m1+m2+m3).format(
  50. pn=g.proto.name,
  51. pnu=g.proto.name.capitalize(),
  52. dn=g.proto.daemon_name,
  53. pnm=g.proj_name))
  54. self.host = host
  55. self.port = port
  56. # Normal mode: call with arg list unrolled, exactly as with cli
  57. # Batch mode: call with list of arg lists as first argument
  58. # kwargs are for local use and are not passed to server
  59. # By default, dies with an error msg on all errors and exceptions
  60. # on_fail is one of 'die' (default), 'return', 'silent', 'raise'
  61. # With on_fail='return', returns 'rpcfail',(resp_object,(die_args))
  62. def request(self,cmd,*args,**kwargs):
  63. if os.getenv('MMGEN_RPC_FAIL_ON_COMMAND') == cmd:
  64. cmd = 'badcommand_' + cmd
  65. cf = { 'timeout':g.http_timeout, 'batch':False, 'on_fail':'die' }
  66. for k in cf:
  67. if k in kwargs and kwargs[k]: cf[k] = kwargs[k]
  68. hc = httplib.HTTPConnection(self.host, self.port, False, cf['timeout'])
  69. if cf['batch']:
  70. p = [{'method':cmd,'params':r,'id':n} for n,r in enumerate(args[0],1)]
  71. else:
  72. p = {'method':cmd,'params':args,'id':1}
  73. def do_fail(*args):
  74. if cf['on_fail'] in ('return','silent'):
  75. return 'rpcfail',args
  76. try: s = u'{}'.format(args[2])
  77. except: s = repr(args[2])
  78. if cf['on_fail'] == 'raise':
  79. raise RPCFailure,s
  80. elif cf['on_fail'] == 'die':
  81. die(args[1],yellow(s))
  82. dmsg_rpc('=== request() debug ===')
  83. dmsg_rpc(' RPC POST data ==> %s\n' % p)
  84. caller = self
  85. class MyJSONEncoder(json.JSONEncoder):
  86. def default(self, obj):
  87. if isinstance(obj,g.proto.coin_amt):
  88. return g.proto.get_rpc_coin_amt_type()(obj)
  89. return json.JSONEncoder.default(self, obj)
  90. # TODO: UTF-8 labels
  91. # if type(p) != list and p['method'] == 'importaddress':
  92. # dump = json.dumps(p,cls=MyJSONEncoder,ensure_ascii=False)
  93. # print(dump)
  94. dmsg_rpc(' RPC AUTHORIZATION data ==> raw: [{}]\n{}enc: [Basic {}]\n'.format(
  95. self.auth_str,' '*31,base64.b64encode(self.auth_str)))
  96. try:
  97. hc.request('POST', '/', json.dumps(p,cls=MyJSONEncoder), {
  98. 'Host': self.host,
  99. 'Authorization': 'Basic {}'.format(base64.b64encode(self.auth_str))
  100. })
  101. except Exception as e:
  102. m = '{}\nUnable to connect to {} at {}:{}'
  103. return do_fail(None,2,m.format(e,g.proto.daemon_name,self.host,self.port))
  104. try:
  105. r = hc.getresponse() # returns HTTPResponse instance
  106. except Exception:
  107. m = 'Unable to connect to {} at {}:{} (but port is bound?)'
  108. return do_fail(None,2,m.format(g.proto.daemon_name,self.host,self.port))
  109. dmsg_rpc(' RPC GETRESPONSE data ==> %s\n' % r.__dict__)
  110. if r.status != 200:
  111. if cf['on_fail'] not in ('silent','raise'):
  112. msg_r(yellow('{} RPC Error: '.format(g.proto.daemon_name.capitalize())))
  113. msg(red('{} {}'.format(r.status,r.reason)))
  114. e1 = r.read()
  115. try:
  116. e3 = json.loads(e1)['error']
  117. e2 = '{} (code {})'.format(e3['message'],e3['code'])
  118. except:
  119. e2 = str(e1)
  120. return do_fail(r,1,e2)
  121. r2 = r.read()
  122. dmsg_rpc(' RPC REPLY data ==> %s\n' % r2)
  123. if not r2:
  124. return do_fail(r,2,'Error: empty reply')
  125. # from decimal import Decimal
  126. r3 = json.loads(r2.decode('utf8'), parse_float=Decimal)
  127. ret = []
  128. for resp in r3 if cf['batch'] else [r3]:
  129. if 'error' in resp and resp['error'] != None:
  130. return do_fail(r,1,'{} returned an error: {}'.format(
  131. g.proto.daemon_name.capitalize(),resp['error']))
  132. elif 'result' not in resp:
  133. return do_fail(r,1, 'Missing JSON-RPC result\n' + repr(resps))
  134. else:
  135. ret.append(resp['result'])
  136. return ret if cf['batch'] else ret[0]
  137. rpcmethods = (
  138. 'backupwallet',
  139. 'createrawtransaction',
  140. 'decoderawtransaction',
  141. 'disconnectnode',
  142. 'estimatefee',
  143. 'estimatesmartfee',
  144. 'getaddressesbyaccount',
  145. 'getbalance',
  146. 'getblock',
  147. 'getblockchaininfo',
  148. 'getblockcount',
  149. 'getblockhash',
  150. 'getmempoolinfo',
  151. 'getmempoolentry',
  152. 'getnettotals',
  153. 'getnetworkinfo',
  154. 'getpeerinfo',
  155. 'getrawmempool',
  156. 'getmempoolentry',
  157. 'getrawtransaction',
  158. 'gettransaction',
  159. 'importaddress',
  160. 'listaccounts',
  161. 'listunspent',
  162. 'sendrawtransaction',
  163. 'signrawtransaction',
  164. 'validateaddress',
  165. 'walletpassphrase',
  166. )
  167. for name in rpcmethods:
  168. exec "def {n}(self,*a,**k):return self.request('{n}',*a,**k)\n".format(n=name)
  169. def rpc_error(ret):
  170. return type(ret) is tuple and ret and ret[0] == 'rpcfail'
  171. def rpc_errmsg(ret): return ret[1][2]