rpc.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2024 The MMGen Project <mmgen@tuta.io>
  5. # Licensed under the GNU General Public License, Version 3:
  6. # https://www.gnu.org/licenses
  7. # Public project repositories:
  8. # https://github.com/mmgen/mmgen-wallet
  9. # https://gitlab.com/mmgen/mmgen-wallet
  10. """
  11. proto.btc.rpc: Bitcoin base protocol RPC client class
  12. """
  13. import os
  14. from ...base_obj import AsyncInit
  15. from ...obj import TrackingWalletName
  16. from ...util import ymsg, die, fmt
  17. from ...fileutil import get_lines_from_file
  18. from ...rpc import RPCClient, auth_data
  19. no_credentials_errmsg = """
  20. Error: no {proto_name} RPC authentication method found
  21. RPC credentials must be supplied using one of the following methods:
  22. 1) If daemon is local and running as same user as you:
  23. - no credentials required, or matching rpcuser/rpcpassword and
  24. rpc_user/rpc_password values in {cf_name}.conf and mmgen.cfg
  25. 2) If daemon is running remotely or as different user:
  26. - matching credentials in {cf_name}.conf and mmgen.cfg as described
  27. above
  28. The --rpc-user/--rpc-password options may be supplied on the MMGen command
  29. line. They override the corresponding values in mmgen.cfg. Set them to an
  30. empty string to use cookie authentication with a local server when the
  31. options are set in mmgen.cfg.
  32. For better security, rpcauth should be used in {cf_name}.conf instead of
  33. rpcuser/rpcpassword.
  34. """
  35. class CallSigs:
  36. class bitcoin_core:
  37. def __init__(self, cfg):
  38. self.cfg = cfg
  39. def createwallet(
  40. self,
  41. wallet_name,
  42. no_keys = True,
  43. blank = True,
  44. passphrase = '',
  45. descriptors = True,
  46. load_on_startup = True):
  47. """
  48. Quirk: when --datadir is specified (even if standard), wallet is created directly in
  49. datadir, otherwise in datadir/wallets
  50. """
  51. return (
  52. 'createwallet',
  53. wallet_name, # 1. wallet_name
  54. no_keys, # 2. disable_private_keys
  55. blank, # 3. blank (no keys or seed)
  56. passphrase, # 4. passphrase (empty string for non-encrypted)
  57. False, # 5. avoid_reuse (track address reuse)
  58. descriptors, # 6. descriptors (native descriptor wallet)
  59. load_on_startup) # 7. load_on_startup
  60. def gettransaction(self, txid, include_watchonly, verbose):
  61. return (
  62. 'gettransaction',
  63. txid, # 1. transaction id
  64. include_watchonly, # 2. optional, default=true for watch-only wallets, otherwise false
  65. verbose) # 3. optional, default=false -- include a `decoded` field containing
  66. # => the decoded transaction (equivalent to RPC decoderawtransaction)
  67. class litecoin_core(bitcoin_core):
  68. def createwallet(
  69. self,
  70. wallet_name,
  71. no_keys = True,
  72. blank = True,
  73. passphrase = '',
  74. descriptors = True,
  75. load_on_startup = True):
  76. return (
  77. 'createwallet',
  78. wallet_name, # 1. wallet_name
  79. no_keys, # 2. disable_private_keys
  80. blank) # 3. blank (no keys or seed)
  81. def gettransaction(self, txid, include_watchonly, verbose):
  82. return (
  83. 'gettransaction',
  84. txid, # 1. transaction id
  85. include_watchonly) # 2. optional, default=true for watch-only wallets, otherwise false
  86. class bitcoin_cash_node(litecoin_core):
  87. pass
  88. class BitcoinRPCClient(RPCClient, metaclass=AsyncInit):
  89. auth_type = 'basic'
  90. has_auth_cookie = True
  91. wallet_path = '/'
  92. dfl_twname = 'mmgen-tracking-wallet'
  93. async def __init__(
  94. self,
  95. cfg,
  96. proto,
  97. daemon,
  98. backend,
  99. ignore_wallet):
  100. self.proto = proto
  101. self.daemon = daemon
  102. self.call_sigs = getattr(CallSigs, daemon.id)(cfg)
  103. self.twname = TrackingWalletName(cfg.regtest_user or proto.tw_name or cfg.tw_name or self.dfl_twname)
  104. super().__init__(
  105. cfg = cfg,
  106. host = (
  107. 'localhost' if cfg.test_suite or cfg.network == 'regtest'
  108. else (proto.rpc_host or cfg.rpc_host or 'localhost')),
  109. port = daemon.rpc_port)
  110. self.set_auth()
  111. await self.set_backend_async(backend) # backend requires self.auth
  112. self.cached = {}
  113. self.caps = ('full_node',)
  114. for func, cap in (
  115. ('setlabel', 'label_api'),
  116. ('getdeploymentinfo', 'deployment_info'),
  117. ('signrawtransactionwithkey', 'sign_with_key')):
  118. if len((await self.call('help', func)).split('\n')) > 3:
  119. self.caps += (cap,)
  120. call_group = [
  121. ('getblockcount', ()),
  122. ('getblockhash', (0,)),
  123. ('getnetworkinfo', ()),
  124. ('getblockchaininfo', ()),
  125. ] + (
  126. [('getdeploymentinfo', ())] if 'deployment_info' in self.caps else []
  127. )
  128. (
  129. self.blockcount,
  130. block0,
  131. self.cached['networkinfo'],
  132. self.cached['blockchaininfo'],
  133. self.cached['deploymentinfo'],
  134. ) = (
  135. await self.gathered_call(None, tuple(call_group))
  136. ) + (
  137. [] if 'deployment_info' in self.caps else [None]
  138. )
  139. self.daemon_version = self.cached['networkinfo']['version']
  140. self.daemon_version_str = self.cached['networkinfo']['subversion']
  141. self.chain = self.cached['blockchaininfo']['chain']
  142. tip = await self.call('getblockhash', self.blockcount)
  143. self.cur_date = (await self.call('getblockheader', tip))['time']
  144. if self.chain != 'regtest':
  145. self.chain += 'net'
  146. assert self.chain in self.proto.networks
  147. async def check_chainfork_mismatch(block0):
  148. try:
  149. if block0 != self.proto.block0:
  150. raise ValueError(f'Invalid Genesis block for {self.proto.cls_name} protocol')
  151. for fork in self.proto.forks:
  152. if fork.height is None or self.blockcount < fork.height:
  153. break
  154. if fork.hash != await self.call('getblockhash', fork.height):
  155. die(3, f'Bad block hash at fork block {fork.height}. Is this the {fork.name} chain?')
  156. except Exception as e:
  157. die(2, '{!s}\n{c!r} requested, but this is not the {c} chain!'.format(e, c=self.proto.coin))
  158. if self.chain == 'mainnet': # skip this for testnet, as Genesis block may change
  159. await check_chainfork_mismatch(block0)
  160. if not ignore_wallet:
  161. await self.check_or_create_daemon_wallet()
  162. # for regtest, wallet_path must remain '/' until Carol’s user wallet has been created
  163. if self.chain != 'regtest' or cfg.regtest_user:
  164. self.wallet_path = f'/wallet/{self.twname}'
  165. @property
  166. async def walletinfo(self):
  167. if not hasattr(self, '_walletinfo'):
  168. self._walletinfo = await self.call('getwalletinfo')
  169. return self._walletinfo
  170. def set_auth(self):
  171. """
  172. MMGen's credentials override coin daemon's
  173. """
  174. if self.cfg.network == 'regtest':
  175. from .regtest import MMGenRegtest
  176. user = MMGenRegtest.rpc_user
  177. passwd = MMGenRegtest.rpc_password
  178. else:
  179. user = (
  180. self.proto.rpc_user or self.cfg.rpc_user or self.get_daemon_cfg_option('rpcuser')
  181. or self.daemon.rpc_user)
  182. passwd = (
  183. self.proto.rpc_password or self.cfg.rpc_password or self.get_daemon_cfg_option('rpcpassword')
  184. or self.daemon.rpc_password)
  185. if user and passwd:
  186. self.auth = auth_data(user, passwd)
  187. return
  188. if self.has_auth_cookie:
  189. if cookie := self.get_daemon_auth_cookie():
  190. self.auth = auth_data(*cookie.split(':'))
  191. return
  192. die(1, '\n\n' + fmt(no_credentials_errmsg, strip_char='\t', indent=' ').format(
  193. proto_name = self.proto.name,
  194. cf_name = (self.proto.is_fork_of or self.proto.name).lower()))
  195. def make_host_path(self, wallet):
  196. return f'/wallet/{wallet}' if wallet else self.wallet_path
  197. @property
  198. async def tracking_wallet_exists(self):
  199. return self.twname in [i['name'] for i in (await self.call('listwalletdir'))['wallets']]
  200. async def check_or_create_daemon_wallet(self):
  201. if self.chain == 'regtest' and self.cfg.regtest_user != 'carol':
  202. return
  203. loaded_wnames = await self.call('listwallets')
  204. if self.twname not in loaded_wnames:
  205. wnames = [i['name'] for i in (await self.call('listwalletdir'))['wallets']]
  206. if self.twname in wnames:
  207. await self.call('loadwallet', self.twname)
  208. else:
  209. await self.icall('createwallet', wallet_name=self.twname)
  210. ymsg(f'Created {self.daemon.coind_name} wallet {self.twname!r}')
  211. def get_daemon_cfg_fn(self):
  212. # Use dirname() to remove 'bob' or 'alice' component
  213. return os.path.join(
  214. (os.path.dirname(self.cfg.data_dir) if self.proto.regtest else self.daemon.datadir),
  215. self.daemon.cfg_file)
  216. def get_daemon_cfg_option(self, req_key):
  217. return list(self.get_daemon_cfg_options([req_key]).values())[0]
  218. def get_daemon_cfg_options(self, req_keys):
  219. fn = self.get_daemon_cfg_fn()
  220. try:
  221. lines = get_lines_from_file(self.cfg, fn, 'daemon config file', silent=not self.cfg.verbose)
  222. except:
  223. self.cfg._util.vmsg(f'Warning: {fn!r} does not exist or is unreadable')
  224. return dict((k, None) for k in req_keys)
  225. def gen():
  226. for key in req_keys:
  227. val = None
  228. for l in lines:
  229. if l.startswith(key):
  230. res = l.split('=', 1)
  231. if len(res) == 2 and not ' ' in res[1].strip():
  232. val = res[1].strip()
  233. yield (key, val)
  234. return dict(gen())
  235. def get_daemon_auth_cookie(self):
  236. fn = self.daemon.auth_cookie_fn
  237. return get_lines_from_file(self.cfg, fn, 'cookie', quiet=True)[0] if os.access(fn, os.R_OK) else ''
  238. def info(self, info_id):
  239. def segwit_is_active():
  240. if 'deployment_info' in self.caps:
  241. return (
  242. self.cached['deploymentinfo']['deployments']['segwit']['active']
  243. or (self.cfg.test_suite and not self.chain == 'regtest')
  244. )
  245. d = self.cached['blockchaininfo']
  246. try:
  247. if d['softforks']['segwit']['active'] is True:
  248. return True
  249. except:
  250. pass
  251. try:
  252. if d['bip9_softforks']['segwit']['status'] == 'active':
  253. return True
  254. except:
  255. pass
  256. if self.cfg.test_suite and not self.chain == 'regtest':
  257. return True
  258. return False
  259. return locals()[info_id]()
  260. rpcmethods = (
  261. 'backupwallet',
  262. 'createrawtransaction',
  263. 'decoderawtransaction',
  264. 'disconnectnode',
  265. 'estimatefee',
  266. 'estimatesmartfee',
  267. 'getaddressesbyaccount',
  268. 'getaddressesbylabel',
  269. 'getblock',
  270. 'getblockchaininfo',
  271. 'getblockcount',
  272. 'getblockhash',
  273. 'getblockheader',
  274. 'getblockstats', # mmgen-node-tools
  275. 'getmempoolinfo',
  276. 'getmempoolentry',
  277. 'getnettotals',
  278. 'getnetworkinfo',
  279. 'getpeerinfo',
  280. 'getrawmempool',
  281. 'getmempoolentry',
  282. 'getrawtransaction',
  283. 'gettransaction',
  284. 'importaddress', # address (address or script) label rescan p2sh (Add P2SH version of the script)
  285. 'importdescriptors', # like above, but for descriptor wallets
  286. 'listaccounts',
  287. 'listlabels',
  288. 'listunspent',
  289. 'setlabel',
  290. 'sendrawtransaction',
  291. 'signrawtransaction',
  292. 'signrawtransactionwithkey', # method new to Core v0.17.0
  293. 'validateaddress',
  294. 'walletpassphrase',
  295. )