ct_regtest.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2022 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-node-tools
  9. # https://gitlab.com/mmgen/mmgen-node-tools
  10. """
  11. test.cmdtest_py_d.ct_regtest: Regtest tests for the cmdtest.py test suite
  12. """
  13. import sys,os
  14. from mmgen.util import msg_r,die,gmsg
  15. from mmgen.protocol import init_proto
  16. from mmgen.proto.btc.regtest import MMGenRegtest
  17. from ..include.common import cfg,imsg,stop_test_daemons,joinpath
  18. from .ct_base import CmdTestBase
  19. args1 = ['--bob']
  20. args2 = ['--bob','--rpc-backend=http']
  21. def gen_addrs(proto,network,keys):
  22. from mmgen.tool.api import tool_api
  23. tool = tool_api(cfg)
  24. tool.init_coin(proto.coin,'regtest')
  25. tool.addrtype = proto.mmtypes[-1]
  26. return [tool.privhex2addr('{:064x}'.format(key)) for key in keys]
  27. class CmdTestRegtest(CmdTestBase):
  28. 'various operations via regtest mode'
  29. networks = ('btc','ltc','bch')
  30. passthru_opts = ('coin',)
  31. extra_spawn_args = ['--regtest=1']
  32. tmpdir_nums = [1]
  33. color = True
  34. deterministic = False
  35. cmd_group_in = (
  36. ('setup', 'regtest mode setup'),
  37. ('subgroup.netrate', []),
  38. ('subgroup.halving_calculator', []),
  39. ('subgroup.fund_addrbal', []),
  40. ('subgroup.addrbal', ['fund_addrbal']),
  41. ('subgroup.blocks_info', ['addrbal']),
  42. ('subgroup.feeview', []),
  43. ('stop', 'stopping regtest daemon'),
  44. )
  45. cmd_subgroups = {
  46. 'netrate': (
  47. "'mmnode-netrate' script",
  48. ('netrate1', "netrate (--help)"),
  49. ('netrate2', "netrate"),
  50. ),
  51. 'halving_calculator': (
  52. "'mmnode-halving-calculator' script",
  53. ('halving_calculator1', "halving calculator (--help)"),
  54. ('halving_calculator2', "halving calculator"),
  55. ('halving_calculator3', "halving calculator (--list)"),
  56. ('halving_calculator4', "halving calculator (--mined)"),
  57. ('halving_calculator5', "halving calculator (--mined --bdr-proj=5)"),
  58. ('halving_calculator6', "halving calculator (--mined --sample-size=20)"),
  59. ),
  60. 'fund_addrbal': (
  61. "funding addresses for 'addrbal' subgroup",
  62. ('sendto1', 'sending funds to address #1 (1)'),
  63. ('sendto2', 'sending funds to address #1 (2)'),
  64. ('sendto3', 'sending funds to address #2'),
  65. ),
  66. 'addrbal': (
  67. "'mmnode-addrbal' script",
  68. ('addrbal_single', 'getting address balance (single address)'),
  69. ('addrbal_multiple', 'getting address balances (multiple addresses)'),
  70. ('addrbal_multiple_tabular1', 'getting address balances (multiple addresses, tabular output)'),
  71. ('addrbal_multiple_tabular2', 'getting address balances (multiple addresses, tabular, show first block)'),
  72. ('addrbal_nobal1', 'getting address balances (no balance)'),
  73. ('addrbal_nobal2', 'getting address balances (no balances)'),
  74. ('addrbal_nobal3', 'getting address balances (one null balance)'),
  75. ('addrbal_nobal3_tabular1', 'getting address balances (one null balance, tabular output)'),
  76. ('addrbal_nobal3_tabular2', 'getting address balances (one null balance, tabular, show first block)'),
  77. ),
  78. 'blocks_info': (
  79. "'mmnode-blocks-info' script",
  80. ('blocks_info1', "blocks-info (--help)"),
  81. ('blocks_info2', "blocks-info (no args)"),
  82. ('blocks_info3', "blocks-info +100"),
  83. ('blocks_info4', "blocks-info --miner-info --fields=all --stats=all +1"),
  84. ),
  85. 'feeview': (
  86. "'mmnode-feeview' script",
  87. ('feeview_setup', 'setting up feeview test'),
  88. ('feeview1', "'mmnode-feeview'"),
  89. ('feeview2', "'mmnode-feeview --columns=40 --include-current'"),
  90. ('feeview3', "'mmnode-feeview --precision=6'"),
  91. ('feeview4', "'mmnode-feeview --detail'"),
  92. ('feeview5', "'mmnode-feeview --show-empty --log'"),
  93. ('feeview6', "'mmnode-feeview --ignore-below=1MB'"),
  94. ('feeview7', "'mmnode-feeview --ignore-below=20kB'"),
  95. ('feeview8', "'mmnode-feeview' (empty mempool)"),
  96. ),
  97. }
  98. def __init__(self,trunner,cfgs,spawn):
  99. CmdTestBase.__init__(self,trunner,cfgs,spawn)
  100. if trunner == None:
  101. return
  102. if cfg._proto.testnet:
  103. die(2,'--testnet and --regtest options incompatible with regtest test suite')
  104. self.proto = init_proto( cfg, self.proto.coin, network='regtest', need_amt=True )
  105. self.addrs = gen_addrs(self.proto,'regtest',[1,2,3,4,5])
  106. self.regtest = MMGenRegtest(cfg,self.proto.coin)
  107. def setup(self):
  108. stop_test_daemons(self.proto.network_id,force=True,remove_datadir=True)
  109. from shutil import rmtree
  110. try: rmtree(joinpath(self.tr.data_dir,'regtest'))
  111. except: pass
  112. t = self.spawn('mmgen-regtest',['-n','setup'])
  113. for s in ('Starting','Creating','Creating','Creating','Mined','Setup complete'):
  114. t.expect(s)
  115. return t
  116. def netrate(self,add_args,expect_str):
  117. t = self.spawn( 'mmnode-netrate', args1 + add_args )
  118. t.expect(expect_str,regex=True)
  119. return t
  120. def netrate1(self):
  121. return self.netrate( ['--help'], 'USAGE:.*' )
  122. def netrate2(self):
  123. t = self.netrate( [], r'sent:.*' )
  124. t.kill(15)
  125. if sys.platform == 'win32':
  126. return 'ok'
  127. t.req_exit_val = -15
  128. return t
  129. def halving_calculator(self,add_args,expect_list):
  130. t = self.spawn('mmnode-halving-calculator',args1+add_args)
  131. t.match_expect_list(expect_list)
  132. return t
  133. def halving_calculator1(self):
  134. return self.halving_calculator(['--help'],['USAGE:'])
  135. def halving_calculator2(self):
  136. return self.halving_calculator([],['Current block: 393',f'Current block subsidy: 12.5 {cfg.coin}'])
  137. def halving_calculator3(self):
  138. return self.halving_calculator(['--list'],['33 4950','0'])
  139. def halving_calculator4(self):
  140. return self.halving_calculator(['--mined'],['0 0.0000015 14949.9999835'])
  141. def halving_calculator5(self):
  142. return self.halving_calculator(['--mined','--bdr-proj=5'],['5.00000 0 0.0000015 14949.9999835'])
  143. def halving_calculator6(self):
  144. return self.halving_calculator(['--mined','--sample-size=20'],['33 4950','0 0.0000015 14949.9999835'])
  145. def sendto(self,addr,amt):
  146. return self.spawn('mmgen-regtest',['send',addr,amt])
  147. def sendto1(self): return self.sendto(self.addrs[0],'0.123')
  148. def sendto2(self): return self.sendto(self.addrs[0],'0.234')
  149. def sendto3(self): return self.sendto(self.addrs[1],'0.345')
  150. def addrbal(self,args,expect_list):
  151. t = self.spawn('mmnode-addrbal',args)
  152. t.match_expect_list(expect_list)
  153. return t
  154. def addrbal_single(self):
  155. return self.addrbal(
  156. args2 + [self.addrs[0]],
  157. [
  158. f'Balance: 0.357 {cfg.coin}',
  159. '2 unspent outputs in 2 blocks',
  160. '394','0.123',
  161. '395','0.234'
  162. ])
  163. def addrbal_multiple(self):
  164. return self.addrbal(
  165. args2 + [self.addrs[1],self.addrs[0]],
  166. [
  167. '396','0.345',
  168. '394','0.123',
  169. '395','0.234'
  170. ])
  171. def addrbal_multiple_tabular1(self):
  172. return self.addrbal(
  173. args2 + ['--tabular',self.addrs[1],self.addrs[0]],
  174. [
  175. self.addrs[1] + ' 1 396','0.345',
  176. self.addrs[0] + ' 2 395','0.357'
  177. ])
  178. def addrbal_multiple_tabular2(self):
  179. return self.addrbal(
  180. args2 + ['--tabular','--first-block',self.addrs[1],self.addrs[0]],
  181. [
  182. self.addrs[1] + ' 1 396','396','0.345',
  183. self.addrs[0] + ' 2 394','395','0.357'
  184. ])
  185. def addrbal_nobal1(self):
  186. return self.addrbal(
  187. args2 + [self.addrs[2]], ['Address has no balance'] )
  188. def addrbal_nobal2(self):
  189. return self.addrbal(
  190. args2 + [self.addrs[2],self.addrs[3]], ['Addresses have no balances'] )
  191. def addrbal_nobal3(self):
  192. return self.addrbal(
  193. args2 + [self.addrs[4],self.addrs[0],self.addrs[3]],
  194. [
  195. 'No balance',
  196. '2 unspent outputs in 2 blocks',
  197. '394','0.123','395','0.234',
  198. 'No balance'
  199. ])
  200. def addrbal_nobal3_tabular1(self):
  201. return self.addrbal(
  202. args2 + ['--tabular',self.addrs[4],self.addrs[0],self.addrs[3]],
  203. [
  204. self.addrs[4] + ' - - -',
  205. self.addrs[0] + ' 2 395','0.357',
  206. self.addrs[3] + ' - - -',
  207. ])
  208. def addrbal_nobal3_tabular2(self):
  209. return self.addrbal(
  210. args2 + ['--tabular','--first-block',self.addrs[4],self.addrs[0],self.addrs[3]],
  211. [
  212. self.addrs[4] + ' - - - -',
  213. self.addrs[0] + ' 2 394','395','0.357',
  214. self.addrs[3] + ' - - - -',
  215. ])
  216. def blocks_info(self,args,expect_list):
  217. t = self.spawn('mmnode-blocks-info',args)
  218. t.match_expect_list(expect_list)
  219. return t
  220. def blocks_info1(self):
  221. return self.blocks_info( args1 + ['--help'], ['USAGE:','OPTIONS:'])
  222. def blocks_info2(self):
  223. return self.blocks_info( args1, [
  224. 'Current height: 396',
  225. ])
  226. def blocks_info3(self):
  227. return self.blocks_info( args1 + ['+100'], [
  228. 'Range: 297-396',
  229. 'Current height: 396',
  230. 'Next diff adjust: 2016'
  231. ])
  232. def blocks_info4(self):
  233. n1,i1,o1,n2,i2,o2 = (2,1,3,6,3,9) if cfg.coin == 'BCH' else (2,1,4,6,3,12)
  234. return self.blocks_info( args1 + ['--miner-info','--fields=all','--stats=all','+3'], [
  235. 'Averages',
  236. f'nTx: {n1}',
  237. f'Inputs: {i1}',
  238. f'Outputs: {o1}',
  239. 'Totals',
  240. f'nTx: {n2}',
  241. f'Inputs: {i2}',
  242. f'Outputs: {o2}',
  243. 'Current height: 396',
  244. 'Next diff adjust: 2016'
  245. ])
  246. async def feeview_setup(self):
  247. def create_pairs(nPairs):
  248. from mmgen.tool.api import tool_api
  249. from collections import namedtuple
  250. t = tool_api(cfg)
  251. t.init_coin(self.proto.coin,self.proto.network)
  252. t.addrtype = 'compressed' if self.proto.coin == 'BCH' else 'bech32'
  253. wp = namedtuple('wifaddrpair',['wif','addr'])
  254. def gen():
  255. for n in range(0xfaceface,nPairs+0xfaceface):
  256. wif = t.hex2wif(f'{n:064x}')
  257. yield wp( wif, t.wif2addr(wif) )
  258. return list(gen())
  259. def gen_fees(n_in,low,high):
  260. # very approximate tx size estimation:
  261. ibytes,wbytes,obytes = (148,0,34) if self.proto.coin == 'BCH' else (43,108,31)
  262. x = (ibytes + (wbytes//4) + (obytes * nPairs)) * self.proto.coin_amt(self.proto.coin_amt.satoshi)
  263. n = n_in - 1
  264. vmax = high - low
  265. for i in range(n_in):
  266. yield (low + (i/n)**6 * vmax) * x
  267. async def do_tx(inputs,outputs,wif):
  268. tx_hex = await r.rpc_call( 'createrawtransaction', inputs, outputs )
  269. tx = await r.rpc_call( 'signrawtransactionwithkey', tx_hex, [wif], [], self.proto.sighash_type )
  270. assert tx['complete'] == True
  271. return tx['hex']
  272. async def do_tx1():
  273. us = await r.rpc_call('listunspent',wallet='miner')
  274. tx_input = us[7] # 25 BTC in coinbase -- us[0] could have < 25 BTC
  275. fee = self.proto.coin_amt('0.001')
  276. outputs = {p.addr:tx1_amt for p in pairs[:nTxs]}
  277. outputs.update({burn_addr: tx_input['amount'] - (tx1_amt*nTxs) - fee})
  278. return await do_tx(
  279. [{ 'txid': tx_input['txid'], 'vout': 0 }],
  280. outputs,
  281. r.miner_wif )
  282. async def do_tx2(tx,pairno):
  283. fee = fees[pairno]
  284. outputs = {p.addr:tx2_amt for p in pairs}
  285. outputs.update({burn_addr: tx1_amt - (tx2_amt*len(pairs)) - fee})
  286. return await do_tx(
  287. [{ 'txid': tx['txid'], 'vout': pairno }],
  288. outputs,
  289. pairs[pairno].wif )
  290. async def do_txs(tx_in):
  291. for pairno in range(nTxs):
  292. tx_hex = await do_tx2(tx_in,pairno)
  293. await r.rpc_call('sendrawtransaction',tx_hex)
  294. self.spawn('',msg_only=True)
  295. r = self.regtest
  296. nPairs = 100
  297. nTxs = 25
  298. tx1_amt = self.proto.coin_amt('{:0.4f}'.format(24 / nTxs)) # 25 BTC subsidy, leave extra for fee
  299. tx2_amt = self.proto.coin_amt('0.00005') # make this as small as possible
  300. imsg(f'Creating {nPairs} key-address pairs')
  301. pairs = create_pairs(nPairs+1)
  302. burn_addr = pairs.pop()[1]
  303. imsg(f'Creating funding transaction with {nTxs} outputs of value {tx1_amt} {self.proto.coin}')
  304. tx1_hex = await do_tx1()
  305. imsg(f'Relaying funding transaction')
  306. await r.rpc_call('sendrawtransaction',tx1_hex)
  307. imsg(f'Mining a block')
  308. await r.generate(1,silent=True)
  309. imsg(f'Generating fees for mempool transactions')
  310. fees = list(gen_fees(nTxs,2,120))
  311. imsg(f'Creating and relaying {nTxs} mempool transactions with {nPairs} outputs each')
  312. await do_txs(await r.rpc_call('decoderawtransaction',tx1_hex))
  313. return 'ok'
  314. def _feeview(self,args,expect_list=[]):
  315. t = self.spawn('mmnode-feeview',args)
  316. if expect_list:
  317. t.match_expect_list(expect_list)
  318. return t
  319. def feeview1(self):
  320. return self._feeview([])
  321. def feeview2(self):
  322. return self._feeview(['--columns=40','--include-current'])
  323. def feeview3(self):
  324. return self._feeview(['--precision=6'])
  325. def feeview4(self):
  326. return self._feeview(['--detail'])
  327. def feeview5(self):
  328. return self._feeview(['--show-empty','--log',f'--outdir={self.tmpdir}'])
  329. def feeview6(self):
  330. return self._feeview(['--ignore-below=1MB'])
  331. def feeview7(self):
  332. return self._feeview(['--ignore-below=4kB'])
  333. async def feeview8(self):
  334. imsg('Clearing mempool')
  335. await self.regtest.generate(1,silent=True)
  336. return self._feeview([])
  337. def stop(self):
  338. if cfg.no_daemon_stop:
  339. self.spawn('',msg_only=True)
  340. msg_r('(leaving daemon running by user request)')
  341. return 'ok'
  342. else:
  343. return self.spawn('mmgen-regtest',['stop'])