regtest.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 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. regtest: Coin daemon regression test mode setup and operations for the MMGen suite
  20. """
  21. import os,time,shutil,json,re
  22. from subprocess import run,PIPE
  23. from .common import *
  24. from .protocol import init_proto
  25. from .rpc import rpc_init,json_encoder
  26. def create_data_dir(data_dir):
  27. try: os.stat(os.path.join(data_dir,'regtest'))
  28. except: pass
  29. else:
  30. if keypress_confirm(
  31. f'Delete your existing MMGen regtest setup at {data_dir!r} and create a new one?'):
  32. shutil.rmtree(data_dir)
  33. else:
  34. die()
  35. try: os.makedirs(data_dir)
  36. except: pass
  37. def create_hdseed(proto):
  38. # cTyMdQ2BgfAsjopRVZrj7AoEGp97pKfrC2NkqLuwHr4KHfPNAKwp hdseed=1
  39. # addr=bcrt1qaq8t3pakcftpk095tnqfv5cmmczysls024atnd
  40. # cTEkSYCWKvNo757uwFPd4yuCXsbZvfJDipHsHWFRapXpnikMHvgn label=
  41. # addr=bcrt1q537rgyctcqdgs8nm8gvku05znka4h2m00lx8ps hdkeypath=m/0'/0'/0'
  42. from .tool import tool_api
  43. t = tool_api()
  44. t.init_coin(proto.coin,proto.network)
  45. t.addrtype = 'bech32'
  46. return t.hex2wif('beadcafe'*8)
  47. def cliargs_convert(args):
  48. def gen():
  49. for arg in args:
  50. if arg.lower() in ('true','false'):
  51. yield (True,False)[arg.lower() == 'false']
  52. elif len(str(arg)) < 20 and re.match(r'[0-9]+',arg):
  53. yield int(arg)
  54. else:
  55. yield arg
  56. return tuple(gen())
  57. class MMGenRegtest(MMGenObject):
  58. rpc_user = 'bobandalice'
  59. rpc_password = 'hodltothemoon'
  60. users = ('bob','alice','miner')
  61. coins = ('btc','bch','ltc')
  62. usr_cmds = ('setup','generate','send','start','stop', 'state', 'balances','mempool','cli','wallet_cli')
  63. def __init__(self,coin):
  64. self.coin = coin.lower()
  65. assert self.coin in self.coins, f'{coin!r}: invalid coin for regtest'
  66. from .daemon import CoinDaemon
  67. self.proto = init_proto(self.coin,regtest=True)
  68. self.d = CoinDaemon(self.coin+'_rt',test_suite=g.test_suite)
  69. async def generate(self,blocks=1,silent=False):
  70. blocks = int(blocks)
  71. async def have_generatetoaddress():
  72. ret = await self.rpc_call('help','generatetoaddress',wallet='miner')
  73. return not 'unknown command:' in ret
  74. async def get_miner_address():
  75. return await self.rpc_call('getnewaddress',wallet='miner')
  76. if self.d.state == 'stopped':
  77. die(1,'Regtest daemon is not running')
  78. self.d.wait_for_state('ready')
  79. if await have_generatetoaddress():
  80. cmd_args = ( 'generatetoaddress', blocks, await get_miner_address() )
  81. else:
  82. cmd_args = ( 'generate', blocks )
  83. out = await self.rpc_call(*cmd_args,wallet='miner')
  84. if len(out) != blocks:
  85. rdie(1,'Error generating blocks')
  86. gmsg(f'Mined {blocks} block{suf(blocks)}')
  87. async def setup(self):
  88. try: os.makedirs(self.d.datadir)
  89. except: pass
  90. if self.d.state != 'stopped':
  91. await self.rpc_call('stop')
  92. create_data_dir(self.d.datadir)
  93. gmsg(f'Starting {self.coin.upper()} regtest setup')
  94. self.d.start(silent=True)
  95. rpc = await rpc_init(self.proto,backend=None,daemon=self.d)
  96. for user in ('miner','bob','alice'):
  97. gmsg(f'Creating {capfirst(user)}’s tracking wallet')
  98. await rpc.icall(
  99. 'createwallet',
  100. wallet_name = user,
  101. blank = user != 'miner' or self.coin == 'btc',
  102. no_keys = user != 'miner',
  103. load_on_startup = False )
  104. if self.coin == 'btc': # BCH,LTC refuse to set HD seed while in IBD
  105. await rpc.call(
  106. 'sethdseed',
  107. True,
  108. create_hdseed(self.proto),
  109. wallet = 'miner' )
  110. await self.generate(432,silent=True)
  111. gmsg('Setup complete')
  112. if opt.setup_no_stop_daemon:
  113. msg('Leaving regtest daemon running')
  114. else:
  115. msg('Stopping regtest daemon')
  116. await self.rpc_call('stop')
  117. def init_daemon(self,reindex=False):
  118. if reindex:
  119. self.d.usr_coind_args.append('--reindex')
  120. async def start_daemon(self,reindex=False,silent=True):
  121. self.init_daemon(reindex=reindex)
  122. self.d.start(silent=silent)
  123. for user in ('miner','bob','alice'):
  124. msg(f'Loading {capfirst(user)}’s wallet')
  125. await self.rpc_call('loadwallet',user,start_daemon=False)
  126. async def rpc_call(self,*args,wallet=None,start_daemon=True):
  127. if start_daemon and self.d.state == 'stopped':
  128. await self.start_daemon()
  129. rpc = await rpc_init(self.proto,backend=None,daemon=self.d)
  130. return await rpc.call(*args,wallet=wallet)
  131. async def start(self):
  132. if self.d.state == 'stopped':
  133. await self.start_daemon(silent=False)
  134. else:
  135. msg(f'{g.coin} regtest daemon already started')
  136. async def stop(self):
  137. if self.d.state == 'stopped':
  138. msg(f'{g.coin} regtest daemon already stopped')
  139. else:
  140. msg(f'Stopping {g.coin} regtest daemon')
  141. self.d.stop(silent=True)
  142. def state(self):
  143. msg(self.d.state)
  144. async def balances(self):
  145. bal = {}
  146. users = ('bob','alice')
  147. for user in users:
  148. out = await self.rpc_call('listunspent',0,wallet=user)
  149. bal[user] = sum(e['amount'] for e in out)
  150. fs = '{:<16} {:18.8f}'
  151. for user in users:
  152. msg(fs.format(user.capitalize()+"'s balance:",bal[user]))
  153. msg(fs.format('Total balance:',sum(v for k,v in bal.items())))
  154. async def send(self,addr,amt):
  155. gmsg(f'Sending {amt} miner {self.d.coin} to address {addr}')
  156. cp = await self.rpc_call('sendtoaddress',addr,str(amt),wallet='miner')
  157. await self.generate(1)
  158. async def mempool(self):
  159. await self.cli('getrawmempool')
  160. async def cli(self,*args):
  161. ret = await self.rpc_call(*cliargs_convert(args))
  162. print(ret if type(ret) == str else json.dumps(ret,cls=json_encoder,indent=4))
  163. async def wallet_cli(self,wallet,*args):
  164. ret = await self.rpc_call(*cliargs_convert(args),wallet=wallet)
  165. print(ret if type(ret) == str else json.dumps(ret,cls=json_encoder,indent=4))
  166. async def cmd(self,args):
  167. ret = getattr(self,args[0])(*args[1:])
  168. return (await ret) if type(ret).__name__ == 'coroutine' else ret
  169. async def fork(self,coin): # currently disabled
  170. proto = init_proto(coin,False)
  171. if not [f for f in proto.forks if f[2] == proto.coin.lower() and f[3] == True]:
  172. die(1,f'Coin {proto.coin} is not a replayable fork of coin {coin}')
  173. gmsg(f'Creating fork from coin {coin} to coin {proto.coin}')
  174. source_rt = MMGenRegtest(coin)
  175. try:
  176. os.stat(source_rt.d.datadir)
  177. except:
  178. die(1,f'Source directory {source_rt.d.datadir!r} does not exist!')
  179. # stop the source daemon
  180. if source_rt.d.state != 'stopped':
  181. await source_rt.d.cli('stop')
  182. # stop our daemon
  183. if self.d.state != 'stopped':
  184. await self.rpc_call('stop')
  185. try: os.makedirs(self.d.datadir)
  186. except: pass
  187. create_data_dir(self.d.datadir)
  188. os.rmdir(self.d.datadir)
  189. shutil.copytree(source_data_dir,self.d.datadir,symlinks=True)
  190. await self.start_daemon(reindex=True)
  191. await self.rpc_call('stop')
  192. gmsg(f'Fork {proto.coin} successfully created')