rpc.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2017 Philemon <mmgen-py@yandex.com>
  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: Bitcoin RPC library for the MMGen suite
  20. """
  21. import httplib,base64,json
  22. from mmgen.common import *
  23. from decimal import Decimal
  24. from mmgen.obj import BTCAmt
  25. class BitcoinRPCConnection(object):
  26. client_version = 0
  27. def __init__(
  28. self,
  29. host=g.rpc_host,port=(8332,18332)[g.testnet],
  30. user=None,passwd=None,auth_cookie=None,
  31. ):
  32. dmsg('=== BitcoinRPCConnection.__init__() debug ===')
  33. dmsg(' host [{}] port [{}] user [{}] passwd [{}] auth_cookie [{}]\n'.format(
  34. host,port,user,passwd,auth_cookie))
  35. if user and passwd:
  36. self.auth_str = '{}:{}'.format(user,passwd)
  37. elif auth_cookie:
  38. self.auth_str = auth_cookie
  39. else:
  40. msg('Error: no Bitcoin RPC authentication method found')
  41. if passwd: die(1,"'rpcuser' entry not found in bitcoin.conf or mmgen.cfg")
  42. elif user: die(1,"'rpcpassword' entry not found in bitcoin.conf or mmgen.cfg")
  43. else:
  44. m1 = 'Either provide rpcuser/rpcpassword in bitcoin.conf or mmgen.cfg'
  45. m2 = '(or, alternatively, copy the authentication cookie to Bitcoin data dir'
  46. m3 = 'if {} and Bitcoin are running as different users)'.format(g.proj_name)
  47. die(1,'\n'.join((m1,m2,m3)))
  48. self.host = host
  49. self.port = port
  50. # Normal mode: call with arg list unrolled, exactly as with 'bitcoin-cli'
  51. # Batch mode: call with list of arg lists as first argument
  52. # kwargs are for local use and are not passed to server
  53. # By default, dies with an error msg on all errors and exceptions
  54. # With on_fail='return', returns 'rpcfail',(resp_object,(die_args))
  55. def request(self,cmd,*args,**kwargs):
  56. cf = { 'timeout':g.http_timeout, 'batch':False, 'on_fail':'die' }
  57. for k in cf:
  58. if k in kwargs and kwargs[k]: cf[k] = kwargs[k]
  59. hc = httplib.HTTPConnection(self.host, self.port, False, cf['timeout'])
  60. if cf['batch']:
  61. p = [{'method':cmd,'params':r,'id':n} for n,r in enumerate(args[0],1)]
  62. else:
  63. p = {'method':cmd,'params':args,'id':1}
  64. def die_maybe(*args):
  65. if cf['on_fail'] == 'return':
  66. return 'rpcfail',args
  67. else:
  68. die(*args[1:])
  69. dmsg('=== request() debug ===')
  70. dmsg(' RPC POST data ==> %s\n' % p)
  71. caller = self
  72. class MyJSONEncoder(json.JSONEncoder):
  73. def default(self, obj):
  74. if isinstance(obj, BTCAmt):
  75. return (float,str)[caller.client_version>=120000](obj)
  76. return json.JSONEncoder.default(self, obj)
  77. # Can't do UTF-8 labels yet: httplib only ascii?
  78. # if type(p) != list and p['method'] == 'importaddress':
  79. # dump = json.dumps(p,cls=MyJSONEncoder,ensure_ascii=False)
  80. # print(dump)
  81. dmsg(' RPC AUTHORIZATION data ==> [Basic {}]\n'.format(base64.b64encode(self.auth_str)))
  82. try:
  83. hc.request('POST', '/', json.dumps(p,cls=MyJSONEncoder), {
  84. 'Host': self.host,
  85. 'Authorization': 'Basic {}'.format(base64.b64encode(self.auth_str))
  86. })
  87. except Exception as e:
  88. return die_maybe(None,2,'%s\nUnable to connect to bitcoind' % e)
  89. r = hc.getresponse() # returns HTTPResponse instance
  90. dmsg(' RPC GETRESPONSE data ==> %s\n' % r.__dict__)
  91. if r.status != 200:
  92. msg_r(yellow('Bitcoind RPC Error: '))
  93. msg(red('{} {}'.format(r.status,r.reason)))
  94. e1 = r.read()
  95. try:
  96. e3 = json.loads(e1)['error']
  97. e2 = '{} (code {})'.format(e3['message'],e3['code'])
  98. except:
  99. e2 = str(e1)
  100. return die_maybe(r,1,e2)
  101. r2 = r.read()
  102. dmsg(' RPC REPLY data ==> %s\n' % r2)
  103. if not r2:
  104. return die_maybe(r,2,'Error: empty reply')
  105. # from decimal import Decimal
  106. r3 = json.loads(r2.decode('utf8'), parse_float=Decimal)
  107. ret = []
  108. for resp in r3 if cf['batch'] else [r3]:
  109. if 'error' in resp and resp['error'] != None:
  110. return die_maybe(r,1,'Bitcoind returned an error: %s' % resp['error'])
  111. elif 'result' not in resp:
  112. return die_maybe(r,1, 'Missing JSON-RPC result\n' + repr(resps))
  113. else:
  114. ret.append(resp['result'])
  115. return ret if cf['batch'] else ret[0]
  116. rpcmethods = (
  117. 'createrawtransaction',
  118. 'backupwallet',
  119. 'decoderawtransaction',
  120. 'disconnectnode',
  121. 'estimatefee',
  122. 'getaddressesbyaccount',
  123. 'getbalance',
  124. 'getblock',
  125. 'getblockcount',
  126. 'getblockhash',
  127. 'getinfo',
  128. 'getpeerinfo',
  129. 'importaddress',
  130. 'listaccounts',
  131. 'listunspent',
  132. 'sendrawtransaction',
  133. 'signrawtransaction',
  134. 'getrawmempool',
  135. 'walletpassphrase',
  136. )
  137. for name in rpcmethods:
  138. exec "def {n}(self,*a,**k):return self.request('{n}',*a,**k)\n".format(n=name)
  139. def rpc_error(ret):
  140. return type(ret) is tuple and ret and ret[0] == 'rpcfail'
  141. def rpc_errmsg(ret): return ret[1][2]