ts_regtest.py 13 KB

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