ct_regtest.py 13 KB

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