ts_regtest.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2020 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. ts_regtest.py: Regtest tests for the test.py test suite
  20. """
  21. import os,json
  22. from decimal import Decimal
  23. from mmgen.globalvars import g
  24. from mmgen.opts import opt
  25. from mmgen.util import die,gmsg,write_data_to_file
  26. from mmgen.protocol import CoinProtocol
  27. from mmgen.addr import AddrList
  28. from mmgen.wallet import MMGenWallet
  29. from ..include.common import *
  30. from .common import *
  31. pat_date = r'\b\d\d-\d\d-\d\d\b'
  32. pat_date_time = r'\b\d\d\d\d-\d\d-\d\d\s+\d\d:\d\d\b'
  33. dfl_wcls = MMGenWallet
  34. rt_pw = 'abc-α'
  35. rt_data = {
  36. 'tx_fee': {'btc':'0.0001','bch':'0.001','ltc':'0.01'},
  37. 'rtFundAmt': {'btc':'500','bch':'500','ltc':'5500'},
  38. 'rtFee': {
  39. 'btc': ('20s','10s','60s','31s','10s','20s'),
  40. 'bch': ('20s','10s','60s','0.0001','10s','20s'),
  41. 'ltc': ('1000s','500s','1500s','0.05','400s','1000s')
  42. },
  43. 'rtBals': {
  44. 'btc': ('499.9999488','399.9998282','399.9998147','399.9996877',
  45. '52.99980410','946.99933647','999.99914057','52.9999',
  46. '946.99933647'),
  47. 'bch': ('499.9999484','399.9999194','399.9998972','399.9997692',
  48. '46.78890380','953.20966920','999.99857300','46.789',
  49. '953.2096692'),
  50. 'ltc': ('5499.99744','5399.994425','5399.993885','5399.987535',
  51. '52.98520500','10946.93753500','10999.92274000','52.99',
  52. '10946.937535'),
  53. },
  54. 'rtBals_gb': {
  55. 'btc': {
  56. '0conf0': {
  57. 'mmgen': ('283.22339537','0','283.22339537'),
  58. 'nonmm': ('16.77647763','0','116.77629233'),
  59. 'total': ('299.999873','0','399.9996877'),
  60. },
  61. '0conf1': {
  62. 'mmgen': ('283.22339537','283.22339537','0'),
  63. 'nonmm': ('16.77647763','16.77647763','99.9998147'),
  64. 'total': ('299.999873','299.999873','99.9998147'),
  65. },
  66. '1conf1': {
  67. 'mmgen': ('0','0','283.22339537'),
  68. 'nonmm': ('0','0','116.77629233'),
  69. 'total': ('0','0','399.9996877'),
  70. },
  71. '1conf2': {
  72. 'mmgen': ('0','283.22339537','0'),
  73. 'nonmm': ('0','16.77647763','99.9998147'),
  74. 'total': ('0','299.999873','99.9998147'),
  75. },
  76. },
  77. 'bch': {
  78. '0conf0': {
  79. 'mmgen': ('283.22339437','0','283.22339437'),
  80. 'nonmm': ('16.77647763','0','116.77637483'),
  81. 'total': ('299.999872','0','399.9997692'),
  82. },
  83. '0conf1': {
  84. 'mmgen': ('283.22339437','283.22339437','0'),
  85. 'nonmm': ('16.77647763','16.77647763','99.9998972'),
  86. 'total': ('299.999872','299.999872','99.9998972'),
  87. },
  88. '1conf1': {
  89. 'mmgen': ('0','0','283.22339437'),
  90. 'nonmm': ('0','0','116.77637483'),
  91. 'total': ('0','0','399.9997692'),
  92. },
  93. '1conf2': {
  94. 'mmgen': ('0','283.22339437','0'),
  95. 'nonmm': ('0','16.77647763','99.9998972'),
  96. 'total': ('0','299.999872','99.9998972'),
  97. },
  98. },
  99. 'ltc': {
  100. '0conf0': {
  101. 'mmgen': ('283.21717237','0','283.21717237'),
  102. 'nonmm': ('16.77647763','0','5116.77036263'),
  103. 'total': ('299.99365','0','5399.987535'),
  104. },
  105. '0conf1': {
  106. 'mmgen': ('283.21717237','283.21717237','0'),
  107. 'nonmm': ('16.77647763','16.77647763','5099.993885'),
  108. 'total': ('299.99365','299.99365','5099.993885'),
  109. },
  110. '1conf1': {
  111. 'mmgen': ('0','0','283.21717237'),
  112. 'nonmm': ('0','0','5116.77036263'),
  113. 'total': ('0','0','5399.987535'),
  114. },
  115. '1conf2': {
  116. 'mmgen': ('0','283.21717237','0'),
  117. 'nonmm': ('0','16.77647763','5099.993885'),
  118. 'total': ('0','299.99365','5099.993885'),
  119. },
  120. }
  121. },
  122. 'rtBobOp3': {'btc':'S:2','bch':'L:3','ltc':'S:2'},
  123. 'rtAmts': {
  124. 'btc': ('500','500'),
  125. 'bch': ('500','560'),
  126. 'ltc': ('5500','5500')
  127. }
  128. }
  129. from .ts_base import *
  130. from .ts_shared import *
  131. class TestSuiteRegtest(TestSuiteBase,TestSuiteShared):
  132. 'transacting and tracking wallet operations via regtest mode'
  133. networks = ('btc','ltc','bch')
  134. passthru_opts = ('coin',)
  135. tmpdir_nums = [17]
  136. cmd_group = (
  137. ('setup', 'regtest (Bob and Alice) mode setup'),
  138. ('current_user', 'current user'),
  139. ('walletgen_bob', 'wallet generation (Bob)'),
  140. ('walletgen_alice', 'wallet generation (Alice)'),
  141. ('addrgen_bob', 'address generation (Bob)'),
  142. ('addrgen_alice', 'address generation (Alice)'),
  143. ('addrimport_bob', "importing Bob's addresses"),
  144. ('addrimport_alice', "importing Alice's addresses"),
  145. ('fund_bob', "funding Bob's wallet"),
  146. ('fund_alice', "funding Alice's wallet"),
  147. ('bob_bal1', "Bob's balance"),
  148. ('bob_add_label', "adding an 80-screen-width label (lat+cyr+gr)"),
  149. ('bob_twview1', "viewing Bob's tracking wallet"),
  150. ('bob_split1', "splitting Bob's funds"),
  151. ('generate', 'mining a block'),
  152. ('bob_bal2', "Bob's balance"),
  153. ('bob_rbf_1output_create', 'creating RBF tx with one output'),
  154. ('bob_rbf_1output_bump', 'bumping RBF tx with one output'),
  155. ('bob_bal2a', "Bob's balance (age_fmt=confs)"),
  156. ('bob_bal2b', "Bob's balance (showempty=1)"),
  157. ('bob_bal2c', "Bob's balance (showempty=1 minconf=2 age_fmt=days)"),
  158. ('bob_bal2d', "Bob's balance (minconf=2)"),
  159. ('bob_bal2e', "Bob's balance (showempty=1 sort=age)"),
  160. ('bob_bal2f', "Bob's balance (showempty=1 sort=age,reverse)"),
  161. ('bob_send_maybe_rbf', 'sending funds to Alice (RBF, if supported)'),
  162. ('get_mempool1', 'mempool (before RBF bump)'),
  163. ('bob_rbf_status1', 'getting status of transaction'),
  164. ('bob_rbf_bump', 'bumping RBF transaction'),
  165. ('get_mempool2', 'mempool (after RBF bump)'),
  166. ('bob_rbf_status2', 'getting status of transaction after replacement'),
  167. ('bob_rbf_status3', 'getting status of replacement transaction (mempool)'),
  168. ('generate', 'mining a block'),
  169. ('bob_rbf_status4', 'getting status of transaction after confirmed (1) replacement'),
  170. ('bob_rbf_status5', 'getting status of replacement transaction (confirmed)'),
  171. ('generate', 'mining a block'),
  172. ('bob_rbf_status6', 'getting status of transaction after confirmed (2) replacement'),
  173. ('bob_bal3', "Bob's balance"),
  174. ('bob_pre_import', 'sending to non-imported address'),
  175. ('generate', 'mining a block'),
  176. ('bob_import_addr', 'importing non-MMGen address with --rescan'),
  177. ('bob_bal4', "Bob's balance (after import with rescan)"),
  178. ('bob_import_list', 'importing flat address list'),
  179. ('bob_split2', "splitting Bob's funds"),
  180. ('bob_0conf0_getbalance', "Bob's balance (unconfirmed, minconf=0)"),
  181. ('bob_0conf1_getbalance', "Bob's balance (unconfirmed, minconf=1)"),
  182. ('generate', 'mining a block'),
  183. ('bob_1conf1_getbalance', "Bob's balance (confirmed, minconf=1)"),
  184. ('bob_1conf2_getbalance', "Bob's balance (confirmed, minconf=2)"),
  185. ('bob_bal5', "Bob's balance"),
  186. ('bob_send_non_mmgen', 'sending funds to Alice (from non-MMGen addrs)'),
  187. ('generate', 'mining a block'),
  188. ('alice_bal_rpcfail', 'RPC failure code'),
  189. ('alice_send_estimatefee', 'tx creation with no fee on command line'),
  190. ('generate', 'mining a block'),
  191. ('bob_bal6', "Bob's balance"),
  192. ('bob_subwallet_addrgen1', "generating Bob's addrs from subwallet 29L"),
  193. ('bob_subwallet_addrgen2', "generating Bob's addrs from subwallet 127S"),
  194. ('bob_subwallet_addrimport1', "importing Bob's addrs from subwallet 29L"),
  195. ('bob_subwallet_addrimport2', "importing Bob's addrs from subwallet 127S"),
  196. ('bob_subwallet_fund', "funding Bob's subwallet addrs"),
  197. ('generate', 'mining a block'),
  198. ('bob_twview2', "viewing Bob's tracking wallet"),
  199. ('bob_twview3', "viewing Bob's tracking wallet"),
  200. ('bob_subwallet_txcreate', 'creating a transaction with subwallet inputs'),
  201. ('bob_subwallet_txsign', 'signing a transaction with subwallet inputs'),
  202. ('bob_subwallet_txdo', "sending from Bob's subwallet addrs"),
  203. ('generate', 'mining a block'),
  204. ('bob_twview4', "viewing Bob's tracking wallet"),
  205. ('bob_alice_bal', "Bob and Alice's balances"),
  206. ('alice_bal2', "Alice's balance"),
  207. ('alice_add_label1', 'adding a label'),
  208. ('alice_chk_label1', 'the label'),
  209. ('alice_add_label2', 'adding a label'),
  210. ('alice_chk_label2', 'the label'),
  211. ('alice_edit_label1', 'editing a label (zh)'),
  212. ('alice_edit_label2', 'editing a label (lat+cyr+gr)'),
  213. ('alice_chk_label3', 'the label'),
  214. ('alice_remove_label1', 'removing a label'),
  215. ('alice_chk_label4', 'the label'),
  216. ('alice_add_label_coinaddr', 'adding a label using the coin address'),
  217. ('alice_chk_label_coinaddr', 'the label'),
  218. ('alice_add_label_badaddr1', 'adding a label with invalid address'),
  219. ('alice_add_label_badaddr2', 'adding a label with invalid address for this chain'),
  220. ('alice_add_label_badaddr3', 'adding a label with wrong MMGen address'),
  221. ('alice_add_label_badaddr4', 'adding a label with wrong coin address'),
  222. ('alice_listaddresses', 'listaddresses'),
  223. ('alice_listaddresses_days', 'listaddresses (age_fmt=days)'),
  224. ('alice_listaddresses_date', 'listaddresses (age_fmt=date)'),
  225. ('alice_listaddresses_date_time', 'listaddresses (age_fmt=date_time)'),
  226. ('alice_twview', 'twview'),
  227. ('alice_twview_days', 'twview (age_fmt=days)'),
  228. ('alice_twview_date', 'twview (age_fmt=date)'),
  229. ('alice_twview_date_time', 'twview (age_fmt=date_time)'),
  230. ('alice_txcreate_info', 'txcreate -i'),
  231. ('stop', 'stopping regtest daemon'),
  232. )
  233. usr_subsids = { 'bob': {}, 'alice': {} }
  234. def __init__(self,trunner,cfgs,spawn):
  235. g.regtest = True
  236. os.environ['MMGEN_TEST_SUITE_REGTEST'] = '1'
  237. from mmgen.regtest import MMGenRegtest
  238. rt = MMGenRegtest(g.coin)
  239. coin = g.coin.lower()
  240. for k in rt_data:
  241. globals()[k] = rt_data[k][coin] if coin in rt_data[k] else None
  242. return TestSuiteBase.__init__(self,trunner,cfgs,spawn)
  243. def _add_comments_to_addr_file(self,addrfile,outfile,use_labels=False):
  244. silence()
  245. gmsg("Adding comments to address file '{}'".format(addrfile))
  246. a = AddrList(addrfile)
  247. for n,idx in enumerate(a.idxs(),1):
  248. if use_labels:
  249. a.set_comment(idx,get_label())
  250. else:
  251. if n % 2: a.set_comment(idx,'Test address {}'.format(n))
  252. a.format(add_comments=True)
  253. write_data_to_file(outfile,a.fmt_data,quiet=True,ignore_opt_outdir=True)
  254. end_silence()
  255. def setup(self):
  256. os.environ['MMGEN_BOGUS_WALLET_DATA'] = ''
  257. if g.testnet:
  258. die(2,'--testnet option incompatible with regtest test suite')
  259. try: shutil.rmtree(joinpath(self.tr.data_dir,'regtest'))
  260. except: pass
  261. os.environ['MMGEN_TEST_SUITE'] = '' # mnemonic is piped to stdin, so stop being a terminal
  262. t = self.spawn('mmgen-regtest',['-n','setup'])
  263. os.environ['MMGEN_TEST_SUITE'] = '1'
  264. for s in ('Starting','Creating','Mined','Creating','Creating','Setup complete'):
  265. t.expect(s)
  266. return t
  267. def current_user(self):
  268. t = self.spawn('mmgen-regtest', ['user'])
  269. t.expect('Bob')
  270. return t
  271. def walletgen(self,user):
  272. t = self.spawn('mmgen-walletgen',['-q','-r0','-p1','--'+user])
  273. t.passphrase_new('new '+dfl_wcls.desc,rt_pw)
  274. t.label()
  275. t.expect('move it to the data directory? (Y/n): ','y')
  276. t.written_to_file(capfirst(dfl_wcls.desc))
  277. return t
  278. def walletgen_bob(self): return self.walletgen('bob')
  279. def walletgen_alice(self): return self.walletgen('alice')
  280. def _user_dir(self,user,coin=None):
  281. return joinpath(self.tr.data_dir,'regtest',coin or g.coin.lower(),user)
  282. def _user_sid(self,user):
  283. return os.path.basename(get_file_with_ext(self._user_dir(user),'mmdat'))[:8]
  284. def _get_user_subsid(self,user,subseed_idx):
  285. if subseed_idx in self.usr_subsids[user]:
  286. return self.usr_subsids[user][subseed_idx]
  287. icls = MMGenWallet
  288. fn = get_file_with_ext(self._user_dir(user),icls.ext)
  289. t = self.spawn('mmgen-tool',['get_subseed',subseed_idx,'wallet='+fn],no_msg=True)
  290. t.passphrase(icls.desc,rt_pw)
  291. sid = t.read().strip()[:8]
  292. self.usr_subsids[user][subseed_idx] = sid
  293. return sid
  294. def addrgen(self,user,wf=None,addr_range='1-5',subseed_idx=None,mmtypes=[]):
  295. from mmgen.addr import MMGenAddrType
  296. for mmtype in mmtypes or g.proto.mmtypes:
  297. t = self.spawn('mmgen-addrgen',
  298. ['--quiet','--'+user,'--type='+mmtype,'--outdir={}'.format(self._user_dir(user))] +
  299. ([wf] if wf else []) +
  300. (['--subwallet='+subseed_idx] if subseed_idx else []) +
  301. [addr_range],
  302. extra_desc='({})'.format(MMGenAddrType.mmtypes[mmtype].name))
  303. t.passphrase(dfl_wcls.desc,rt_pw)
  304. t.written_to_file('Addresses')
  305. ok_msg()
  306. t.skip_ok = True
  307. return t
  308. def addrgen_bob(self): return self.addrgen('bob')
  309. def addrgen_alice(self): return self.addrgen('alice')
  310. def addrimport(self,user,sid=None,addr_range='1-5',num_addrs=5,mmtypes=[]):
  311. id_strs = { 'legacy':'', 'compressed':'-C', 'segwit':'-S', 'bech32':'-B' }
  312. if not sid: sid = self._user_sid(user)
  313. from mmgen.addr import MMGenAddrType
  314. for mmtype in mmtypes or g.proto.mmtypes:
  315. desc = MMGenAddrType.mmtypes[mmtype].name
  316. addrfile = joinpath(self._user_dir(user),
  317. '{}{}{}[{}]{x}.testnet.addrs'.format(
  318. sid,self.altcoin_pfx,id_strs[desc],addr_range,
  319. x='-α' if g.debug_utf8 else ''))
  320. if mmtype == g.proto.mmtypes[0] and user == 'bob':
  321. psave = g.proto
  322. g.proto = CoinProtocol(g.coin,True)
  323. self._add_comments_to_addr_file(addrfile,addrfile,use_labels=True)
  324. g.proto = psave
  325. t = self.spawn( 'mmgen-addrimport',
  326. ['--quiet', '--'+user, '--batch', addrfile],
  327. extra_desc='({})'.format(desc))
  328. if g.debug:
  329. t.expect("Type uppercase 'YES' to confirm: ",'YES\n')
  330. t.expect('Importing')
  331. t.expect('{} addresses imported'.format(num_addrs))
  332. ok_msg()
  333. t.skip_ok = True
  334. return t
  335. def addrimport_bob(self): return self.addrimport('bob')
  336. def addrimport_alice(self): return self.addrimport('alice')
  337. def fund_wallet(self,user,mmtype,amt,sid=None,addr_range='1-5'):
  338. if not sid: sid = self._user_sid(user)
  339. addr = self.get_addr_from_addrlist(user,sid,mmtype,0,addr_range=addr_range)
  340. t = self.spawn('mmgen-regtest', ['send',str(addr),str(amt)])
  341. t.expect('Sending {} miner {}'.format(amt,g.coin))
  342. t.expect('Mined 1 block')
  343. return t
  344. def fund_bob(self): return self.fund_wallet('bob','C',rtFundAmt)
  345. def fund_alice(self): return self.fund_wallet('alice',('L','S')[g.proto.cap('segwit')],rtFundAmt)
  346. def user_twview(self,user,chk=None,sort='age'):
  347. t = self.spawn('mmgen-tool',['--'+user,'twview','sort='+sort])
  348. if chk: t.expect(chk,regex=True)
  349. t.read()
  350. return t
  351. def bob_twview1(self): return self.user_twview('bob',chk=r'1\).*\b{}\b'.format(rtAmts[0]))
  352. def user_bal(self,user,bal,args=['showempty=1'],skip_check=False,exit_val=0):
  353. t = self.spawn('mmgen-tool',['--'+user,'listaddresses'] + args)
  354. if skip_check:
  355. t.read()
  356. else:
  357. total = t.expect_getend('TOTAL: ')
  358. cmp_or_die('{} {}'.format(bal,g.coin),total)
  359. t.req_exit_val = exit_val
  360. return t
  361. def alice_bal1(self):
  362. return self.user_bal('alice',rtFundAmt)
  363. def alice_bal2(self):
  364. return self.user_bal('alice',rtBals[8])
  365. def bob_bal1(self):
  366. return self.user_bal('bob',rtFundAmt)
  367. def bob_bal2(self):
  368. return self.user_bal('bob',rtBals[0])
  369. def bob_bal2a(self):
  370. return self.user_bal('bob',rtBals[0],args=['showempty=1','age_fmt=confs'])
  371. def bob_bal2b(self):
  372. return self.user_bal('bob',rtBals[0],args=['showempty=1'])
  373. def bob_bal2c(self):
  374. return self.user_bal('bob',rtBals[0],args=['showempty=1','minconf=2','age_fmt=days'],skip_check=True)
  375. def bob_bal2d(self):
  376. return self.user_bal('bob',rtBals[0],args=['minconf=2'],skip_check=True)
  377. def bob_bal2e(self):
  378. return self.user_bal('bob',rtBals[0],args=['showempty=1','sort=age'])
  379. def bob_bal2f(self):
  380. return self.user_bal('bob',rtBals[0],args=['showempty=1','sort=age,reverse'])
  381. def bob_bal3(self):
  382. return self.user_bal('bob',rtBals[1])
  383. def bob_bal4(self):
  384. return self.user_bal('bob',rtBals[2])
  385. def bob_bal5(self):
  386. return self.user_bal('bob',rtBals[3])
  387. def bob_bal6(self):
  388. return self.user_bal('bob',rtBals[7])
  389. def bob_subwallet_addrgen1(self):
  390. return self.addrgen('bob',subseed_idx='29L',mmtypes=['C']) # 29L: 2FA7BBA8
  391. def bob_subwallet_addrgen2(self):
  392. return self.addrgen('bob',subseed_idx='127S',mmtypes=['C']) # 127S: '09E8E286'
  393. def subwallet_addrimport(self,user,subseed_idx):
  394. sid = self._get_user_subsid(user,subseed_idx)
  395. return self.addrimport(user,sid=sid,mmtypes=['C'])
  396. def bob_subwallet_addrimport1(self): return self.subwallet_addrimport('bob','29L')
  397. def bob_subwallet_addrimport2(self): return self.subwallet_addrimport('bob','127S')
  398. def bob_subwallet_fund(self):
  399. sid1 = self._get_user_subsid('bob','29L')
  400. sid2 = self._get_user_subsid('bob','127S')
  401. chg_addr = self._user_sid('bob') + (':B:1',':L:1')[g.coin=='BCH']
  402. outputs_cl = [sid1+':C:2,0.29',sid2+':C:3,0.127',chg_addr]
  403. inputs = ('3','1')[g.coin=='BCH']
  404. return self.user_txdo('bob',rtFee[1],outputs_cl,inputs,extra_args=['--subseeds=127'])
  405. def bob_twview2(self):
  406. sid1 = self._get_user_subsid('bob','29L')
  407. return self.user_twview('bob',chk=r'\b{}:C:2\b\s+{}'.format(sid1,'0.29'),sort='twmmid')
  408. def bob_twview3(self):
  409. sid2 = self._get_user_subsid('bob','127S')
  410. return self.user_twview('bob',chk=r'\b{}:C:3\b\s+{}'.format(sid2,'0.127'),sort='amt')
  411. def bob_subwallet_txcreate(self):
  412. sid1 = self._get_user_subsid('bob','29L')
  413. sid2 = self._get_user_subsid('bob','127S')
  414. outputs_cl = [sid1+':C:5,0.0159',sid2+':C:5']
  415. t = self.spawn('mmgen-txcreate',['-d',self.tmpdir,'-B','--bob'] + outputs_cl)
  416. return self.txcreate_ui_common(t,
  417. menu = ['a'],
  418. inputs = ('1,2','2,3')[g.coin=='BCH'],
  419. interactive_fee = '0.00001')
  420. def bob_subwallet_txsign(self):
  421. fn = get_file_with_ext(self.tmpdir,'rawtx')
  422. t = self.spawn('mmgen-txsign',['-d',self.tmpdir,'--bob','--subseeds=127',fn])
  423. t.view_tx('t')
  424. t.passphrase(dfl_wcls.desc,rt_pw)
  425. t.do_comment(None)
  426. t.expect('(Y/n): ','y')
  427. t.written_to_file('Signed transaction')
  428. return t
  429. def bob_subwallet_txdo(self):
  430. outputs_cl = [self._user_sid('bob')+':L:5']
  431. inputs = ('1,2','2,3')[g.coin=='BCH']
  432. return self.user_txdo('bob',rtFee[5],outputs_cl,inputs,menu=['a'],extra_args=['--subseeds=127']) # sort: amt
  433. def bob_twview4(self):
  434. sid = self._user_sid('bob')
  435. amt = ('0.4169328','0.41364')[g.coin=='LTC']
  436. return self.user_twview('bob',chk=r'\b{}:L:5\b\s+.*\s+\b{}\b'.format(sid,amt),sort='twmmid')
  437. def bob_getbalance(self,bals,confs=1):
  438. for i in (0,1,2):
  439. assert Decimal(bals['mmgen'][i]) + Decimal(bals['nonmm'][i]) == Decimal(bals['total'][i])
  440. t = self.spawn('mmgen-tool',['--bob','getbalance','minconf={}'.format(confs)])
  441. for k in ('mmgen','nonmm','total'):
  442. t.expect(r'\n\S+:\s+{} {c}\s+{} {c}\s+{} {c}'.format(*bals[k],c=g.coin),regex=True)
  443. t.read()
  444. return t
  445. def bob_0conf0_getbalance(self): return self.bob_getbalance(rtBals_gb['0conf0'],confs=0)
  446. def bob_0conf1_getbalance(self): return self.bob_getbalance(rtBals_gb['0conf1'],confs=1)
  447. def bob_1conf1_getbalance(self): return self.bob_getbalance(rtBals_gb['1conf1'],confs=1)
  448. def bob_1conf2_getbalance(self): return self.bob_getbalance(rtBals_gb['1conf2'],confs=2)
  449. def bob_alice_bal(self):
  450. t = self.spawn('mmgen-regtest',['balances'])
  451. t.expect('Switching')
  452. ret = t.expect_getend("Alice's balance:").strip()
  453. cmp_or_die(rtBals[5],ret)
  454. ret = t.expect_getend("Bob's balance:").strip()
  455. cmp_or_die(rtBals[4],ret)
  456. ret = t.expect_getend("Total balance:").strip()
  457. cmp_or_die(rtBals[6],ret)
  458. return t
  459. def user_txsend_status(self,user,tx_file,exp1='',exp2='',extra_args=[],bogus_send=False):
  460. os.environ['MMGEN_BOGUS_SEND'] = ('','1')[bool(bogus_send)]
  461. t = self.spawn('mmgen-txsend',['-d',self.tmpdir,'--'+user,'--status'] + extra_args + [tx_file])
  462. os.environ['MMGEN_BOGUS_SEND'] = '1'
  463. if exp1: t.expect(exp1,regex=True)
  464. if exp2: t.expect(exp2,regex=True)
  465. return t
  466. def user_txdo( self, user, fee, outputs_cl, outputs_list,
  467. extra_args = [],
  468. wf = None,
  469. do_label = False,
  470. bad_locktime = False,
  471. full_tx_view = False,
  472. menu = ['M'],
  473. bogus_send = False):
  474. os.environ['MMGEN_BOGUS_SEND'] = ('','1')[bool(bogus_send)]
  475. t = self.spawn('mmgen-txdo',
  476. ['-d',self.tmpdir,'-B','--'+user] +
  477. (['--tx-fee='+fee] if fee else []) +
  478. extra_args + ([],[wf])[bool(wf)] + outputs_cl)
  479. os.environ['MMGEN_BOGUS_SEND'] = '1'
  480. self.txcreate_ui_common(t,
  481. caller = 'txdo',
  482. menu = menu,
  483. inputs = outputs_list,
  484. file_desc = 'Signed transaction',
  485. interactive_fee = (tx_fee,'')[bool(fee)],
  486. add_comment = tx_label_jp,
  487. view = 't',save=True)
  488. t.passphrase(dfl_wcls.desc,rt_pw)
  489. t.written_to_file('Signed transaction')
  490. self._do_confirm_send(t)
  491. s,exit_val = (('Transaction sent',0),("can't be included",1))[bad_locktime]
  492. t.expect(s)
  493. t.req_exit_val = exit_val
  494. return t
  495. def bob_split1(self):
  496. sid = self._user_sid('bob')
  497. outputs_cl = [sid+':C:1,100', sid+':L:2,200',sid+':'+rtBobOp3]
  498. return self.user_txdo('bob',rtFee[0],outputs_cl,'1',do_label=True,full_tx_view=True)
  499. def get_addr_from_addrlist(self,user,sid,mmtype,idx,addr_range='1-5'):
  500. id_str = { 'L':'', 'S':'-S', 'C':'-C', 'B':'-B' }[mmtype]
  501. ext = '{}{}{}[{}]{x}.testnet.addrs'.format(
  502. sid,self.altcoin_pfx,id_str,addr_range,x='-α' if g.debug_utf8 else '')
  503. addrfile = get_file_with_ext(self._user_dir(user),ext,no_dot=True)
  504. psave = g.proto
  505. g.proto = CoinProtocol(g.coin,True)
  506. silence()
  507. addr = AddrList(addrfile).data[idx].addr
  508. end_silence()
  509. g.proto = psave
  510. return addr
  511. def _create_tx_outputs(self,user,data):
  512. sid = self._user_sid(user)
  513. return [self.get_addr_from_addrlist(user,sid,mmtype,idx-1)+amt_str for mmtype,idx,amt_str in data]
  514. def bob_rbf_1output_create(self):
  515. if g.coin != 'BTC': return 'skip' # non-coin-dependent test, so run just once for BTC
  516. out_addr = self._create_tx_outputs('alice',(('B',5,''),))
  517. t = self.spawn('mmgen-txcreate',['-d',self.tr.trash_dir,'-B','--bob','--rbf'] + out_addr)
  518. return self.txcreate_ui_common(t,menu=[],inputs='3',interactive_fee='3s') # out amt: 199.99999343
  519. def bob_rbf_1output_bump(self):
  520. if g.coin != 'BTC': return 'skip'
  521. ext = '9343,3]{x}.testnet.rawtx'.format(x='-α' if g.debug_utf8 else '')
  522. txfile = get_file_with_ext(self.tr.trash_dir,ext,delete=False,no_dot=True)
  523. return self.user_txbump('bob',self.tr.trash_dir,txfile,'8s',has_label=False,signed_tx=False,one_output=True)
  524. def bob_send_maybe_rbf(self):
  525. outputs_cl = self._create_tx_outputs('alice',(('L',1,',60'),('C',1,',40'))) # alice_sid:L:1, alice_sid:C:1
  526. outputs_cl += [self._user_sid('bob')+':'+rtBobOp3]
  527. return self.user_txdo('bob',rtFee[1],outputs_cl,'3',
  528. extra_args=([],['--rbf'])[g.proto.cap('rbf')])
  529. def bob_send_non_mmgen(self):
  530. outputs_cl = self._create_tx_outputs('alice',(
  531. (('L','S')[g.proto.cap('segwit')],2,',10'),
  532. (('L','S')[g.proto.cap('segwit')],3,'')
  533. )) # alice_sid:S:2, alice_sid:S:3
  534. keyfile = joinpath(self.tmpdir,'non-mmgen.keys')
  535. return self.user_txdo('bob',rtFee[3],outputs_cl,'1,4-10',
  536. extra_args=['--keys-from-file='+keyfile,'--vsize-adj=1.02'])
  537. def alice_send_estimatefee(self):
  538. outputs_cl = self._create_tx_outputs('bob',(('L',1,''),)) # bob_sid:L:1
  539. return self.user_txdo('alice',None,outputs_cl,'1') # fee=None
  540. def user_txbump(self,user,outdir,txfile,fee,add_args=[],has_label=True,signed_tx=True,one_output=False):
  541. if not g.proto.cap('rbf'): return 'skip'
  542. os.environ['MMGEN_BOGUS_SEND'] = ''
  543. t = self.spawn('mmgen-txbump',
  544. ['-d',outdir,'--'+user,'--tx-fee='+fee,'--output-to-reduce=c'] + add_args + [txfile])
  545. os.environ['MMGEN_BOGUS_SEND'] = '1'
  546. if not one_output:
  547. t.expect('OK? (Y/n): ','y') # output OK?
  548. t.expect('OK? (Y/n): ','y') # fee OK?
  549. t.do_comment(False,has_label=has_label)
  550. if signed_tx:
  551. t.passphrase(dfl_wcls.desc,rt_pw)
  552. t.written_to_file('Signed transaction')
  553. self.txsend_ui_common(t,caller='txdo',bogus_send=False,file_desc='Signed transaction')
  554. else:
  555. t.expect('Save transaction? (y/N): ','y')
  556. t.written_to_file('Transaction')
  557. t.read()
  558. return t
  559. def bob_rbf_bump(self):
  560. ext = ',{}]{x}.testnet.sigtx'.format(rtFee[1][:-1],x='-α' if g.debug_utf8 else '')
  561. txfile = self.get_file_with_ext(ext,delete=False,no_dot=True)
  562. return self.user_txbump('bob',self.tmpdir,txfile,rtFee[2],add_args=['--send'])
  563. def generate(self,coin=None,num_blocks=1):
  564. int(num_blocks)
  565. if coin: opt.coin = coin
  566. t = self.spawn('mmgen-regtest',['generate',str(num_blocks)])
  567. t.expect('Mined {} block'.format(num_blocks))
  568. return t
  569. def _get_mempool(self):
  570. if not g.debug_utf8:
  571. disable_debug()
  572. ret = self.spawn('mmgen-regtest',['mempool']).read()
  573. if not g.debug_utf8:
  574. restore_debug()
  575. m = re.search(r'(\[\s*"[a-f0-9]{64}"\s*])',ret) # allow for extra output by handler at end
  576. return json.loads(m.group(1))
  577. def get_mempool1(self):
  578. mp = self._get_mempool()
  579. if len(mp) != 1:
  580. rdie(2,'Mempool has more or less than one TX!')
  581. self.write_to_tmpfile('rbf_txid',mp[0]+'\n')
  582. return 'ok'
  583. def bob_rbf_status(self,fee,exp1,exp2=''):
  584. if not g.proto.cap('rbf'): return 'skip'
  585. ext = ',{}]{x}.testnet.sigtx'.format(fee[:-1],x='-α' if g.debug_utf8 else '')
  586. txfile = self.get_file_with_ext(ext,delete=False,no_dot=True)
  587. return self.user_txsend_status('bob',txfile,exp1,exp2)
  588. def bob_rbf_status1(self):
  589. if not g.proto.cap('rbf'): return 'skip'
  590. return self.bob_rbf_status(rtFee[1],'in mempool, replaceable')
  591. def get_mempool2(self):
  592. if not g.proto.cap('rbf'): return 'skip'
  593. mp = self._get_mempool()
  594. if len(mp) != 1:
  595. rdie(2,'Mempool has more or less than one TX!')
  596. chk = self.read_from_tmpfile('rbf_txid')
  597. if chk.strip() == mp[0]:
  598. rdie(2,'TX in mempool has not changed! RBF bump failed')
  599. self.write_to_tmpfile('rbf_txid2',mp[0]+'\n')
  600. return 'ok'
  601. def bob_rbf_status2(self):
  602. if not g.proto.cap('rbf'): return 'skip'
  603. new_txid = self.read_from_tmpfile('rbf_txid2').strip()
  604. return self.bob_rbf_status(rtFee[1],
  605. 'Transaction has been replaced','{} in mempool'.format(new_txid))
  606. def bob_rbf_status3(self):
  607. if not g.proto.cap('rbf'): return 'skip'
  608. return self.bob_rbf_status(rtFee[2],'status: in mempool, replaceable')
  609. def bob_rbf_status4(self):
  610. if not g.proto.cap('rbf'): return 'skip'
  611. new_txid = self.read_from_tmpfile('rbf_txid2').strip()
  612. return self.bob_rbf_status(rtFee[1],
  613. 'Replacement transaction has 1 confirmation',
  614. 'Replacing transactions:\s+{}'.format(new_txid))
  615. def bob_rbf_status5(self):
  616. if not g.proto.cap('rbf'): return 'skip'
  617. return self.bob_rbf_status(rtFee[2],'Transaction has 1 confirmation')
  618. def bob_rbf_status6(self):
  619. if not g.proto.cap('rbf'): return 'skip'
  620. new_txid = self.read_from_tmpfile('rbf_txid2').strip()
  621. return self.bob_rbf_status(rtFee[1],
  622. 'Replacement transaction has 2 confirmations',
  623. 'Replacing transactions:\s+{}'.format(new_txid))
  624. @staticmethod
  625. def _gen_pairs(n):
  626. disable_debug()
  627. from subprocess import run,PIPE
  628. ret = [run(['python3',joinpath('cmds','mmgen-tool'),'--testnet=1'] +
  629. (['--type=compressed'],[])[i==0] +
  630. ['-r0','randpair'],
  631. stdout=PIPE,check=True
  632. ).stdout.decode().split() for i in range(n)]
  633. restore_debug()
  634. return ret
  635. def bob_pre_import(self):
  636. pairs = self._gen_pairs(5)
  637. self.write_to_tmpfile('non-mmgen.keys','\n'.join([a[0] for a in pairs])+'\n')
  638. self.write_to_tmpfile('non-mmgen.addrs','\n'.join([a[1] for a in pairs])+'\n')
  639. return self.user_txdo('bob',rtFee[4],[pairs[0][1]],'3')
  640. def user_import(self,user,args):
  641. t = self.spawn('mmgen-addrimport',['--'+user]+args)
  642. if g.debug:
  643. t.expect("Type uppercase 'YES' to confirm: ",'YES\n')
  644. t.expect('Importing')
  645. t.expect('OK')
  646. t.read()
  647. return t
  648. def bob_import_addr(self):
  649. addr = self.read_from_tmpfile('non-mmgen.addrs').split()[0]
  650. return self.user_import('bob',['--rescan','--address='+addr])
  651. def bob_import_list(self):
  652. addrfile = joinpath(self.tmpdir,'non-mmgen.addrs')
  653. return self.user_import('bob',['--addrlist',addrfile])
  654. def bob_split2(self):
  655. addrs = self.read_from_tmpfile('non-mmgen.addrs').split()
  656. amts = (1.12345678,2.87654321,3.33443344,4.00990099,5.43214321)
  657. outputs1 = list(map('{},{}'.format,addrs,amts))
  658. sid = self._user_sid('bob')
  659. l1,l2 = (':S',':B') if 'B' in g.proto.mmtypes else (':S',':S') if g.proto.cap('segwit') else (':L',':L')
  660. outputs2 = [sid+':C:2,6.333', sid+':L:3,6.667',sid+l1+':4,0.123',sid+l2+':5']
  661. return self.user_txdo('bob',rtFee[5],outputs1+outputs2,'1-2')
  662. def user_add_label(self,user,addr,label):
  663. t = self.spawn('mmgen-tool',['--'+user,'add_label',addr,label])
  664. t.expect('Added label.*in tracking wallet',regex=True)
  665. return t
  666. def user_remove_label(self,user,addr):
  667. t = self.spawn('mmgen-tool',['--'+user,'remove_label',addr])
  668. t.expect('Removed label.*in tracking wallet',regex=True)
  669. return t
  670. def bob_add_label(self):
  671. sid = self._user_sid('bob')
  672. return self.user_add_label('bob',sid+':C:1',tw_label_lat_cyr_gr)
  673. def alice_add_label1(self):
  674. sid = self._user_sid('alice')
  675. return self.user_add_label('alice',sid+':C:1','Original Label - 月へ')
  676. def alice_add_label2(self):
  677. sid = self._user_sid('alice')
  678. return self.user_add_label('alice',sid+':C:1','Replacement Label')
  679. def alice_add_label_coinaddr(self):
  680. mmid = self._user_sid('alice') + (':S:1',':L:1')[g.coin=='BCH']
  681. t = self.spawn('mmgen-tool',['--alice','listaddress',mmid],no_msg=True)
  682. btcaddr = [i for i in t.read().splitlines() if i.lstrip()[0:len(mmid)] == mmid][0].split()[1]
  683. return self.user_add_label('alice',btcaddr,'Label added using coin address')
  684. def user_chk_label(self,user,addr,label):
  685. t = self.spawn('mmgen-tool',['--'+user,'listaddresses','all_labels=1'])
  686. t.expect(r'{}\s+\S{{30}}\S+\s+{}\s+'.format(addr,label),regex=True)
  687. return t
  688. def alice_chk_label_coinaddr(self):
  689. mmid = self._user_sid('alice') + (':S:1',':L:1')[g.coin=='BCH']
  690. return self.user_chk_label('alice',mmid,'Label added using coin address')
  691. def alice_add_label_badaddr(self,addr,reply):
  692. t = self.spawn('mmgen-tool',['--alice','add_label',addr,'(none)'])
  693. t.expect(reply,regex=True)
  694. return t
  695. def alice_add_label_badaddr1(self):
  696. return self.alice_add_label_badaddr(rt_pw,'Invalid coin address for this chain: ')
  697. def alice_add_label_badaddr2(self):
  698. addr = g.proto.pubhash2addr('00'*20,False) # mainnet zero address
  699. return self.alice_add_label_badaddr(addr,'Invalid coin address for this chain: '+addr)
  700. def alice_add_label_badaddr3(self):
  701. addr = self._user_sid('alice') + ':C:123'
  702. return self.alice_add_label_badaddr(addr,
  703. "MMGen address '{}' not found in tracking wallet".format(addr))
  704. def alice_add_label_badaddr4(self):
  705. addr = CoinProtocol(g.coin,True).pubhash2addr('00'*20,False) # testnet zero address
  706. return self.alice_add_label_badaddr(addr,
  707. "Address '{}' not found in tracking wallet".format(addr))
  708. def alice_bal_rpcfail(self):
  709. addr = self._user_sid('alice') + ':C:2'
  710. os.environ['MMGEN_RPC_FAIL_ON_COMMAND'] = 'listunspent'
  711. t = self.spawn('mmgen-tool',['--alice','getbalance'])
  712. os.environ['MMGEN_RPC_FAIL_ON_COMMAND'] = ''
  713. t.expect('Method not found')
  714. t.read()
  715. t.req_exit_val = 3
  716. return t
  717. def alice_remove_label1(self):
  718. sid = self._user_sid('alice')
  719. mmid = sid + (':S:3',':L:3')[g.coin=='BCH']
  720. return self.user_remove_label('alice',mmid)
  721. def alice_chk_label1(self):
  722. sid = self._user_sid('alice')
  723. return self.user_chk_label('alice',sid+':C:1','Original Label - 月へ')
  724. def alice_chk_label2(self):
  725. sid = self._user_sid('alice')
  726. return self.user_chk_label('alice',sid+':C:1','Replacement Label')
  727. def alice_edit_label1(self): return self.user_edit_label('alice','4',tw_label_lat_cyr_gr)
  728. def alice_edit_label2(self): return self.user_edit_label('alice','3',tw_label_zh)
  729. def alice_chk_label3(self):
  730. sid = self._user_sid('alice')
  731. mmid = sid + (':S:3',':L:3')[g.coin=='BCH']
  732. return self.user_chk_label('alice',mmid,tw_label_lat_cyr_gr)
  733. def alice_chk_label4(self):
  734. sid = self._user_sid('alice')
  735. mmid = sid + (':S:3',':L:3')[g.coin=='BCH']
  736. return self.user_chk_label('alice',mmid,'-')
  737. def user_edit_label(self,user,output,label):
  738. t = self.spawn('mmgen-txcreate',['-B','--'+user,'-i'])
  739. t.expect(r'add \[l\]abel:.','M',regex=True)
  740. t.expect(r'add \[l\]abel:.','l',regex=True)
  741. t.expect(r"Enter unspent.*return to main menu\):.",output+'\n',regex=True)
  742. t.expect(r"Enter label text.*return to main menu\):.",label+'\n',regex=True)
  743. t.expect(r'\[q\]uit view, .*?:.','q',regex=True)
  744. return t
  745. def alice_listaddresses(self,args=[],expect=None):
  746. expect = expect or rf'{rtAmts[1]}\b'
  747. t = self.spawn('mmgen-tool',['--alice','listaddresses','showempty=1'] + args)
  748. t.expect(expect,regex=True)
  749. t.read()
  750. return t
  751. def alice_listaddresses_days(self):
  752. return self.alice_listaddresses(args=['age_fmt=days'],expect=rf'{rtAmts[1]}\s+\d+\b')
  753. def alice_listaddresses_date(self):
  754. return self.alice_listaddresses(args=['age_fmt=date'],expect=rf'{rtAmts[1]}\s+'+pat_date)
  755. def alice_listaddresses_date_time(self):
  756. return self.alice_listaddresses(
  757. args=['age_fmt=date_time'],
  758. expect=rf'{rtAmts[1]}\s+'+pat_date_time)
  759. def alice_twview(self,args=[],expect=None):
  760. expect = expect or rf'{rtAmts[0]}\b'
  761. t = self.spawn('mmgen-tool',['--alice','twview'] + args)
  762. t.expect(expect,regex=True)
  763. t.read()
  764. return t
  765. def alice_twview_days(self):
  766. return self.alice_twview(args=['age_fmt=days'],expect=rf'{rtAmts[0]}\s+\d+\b')
  767. def alice_twview_date(self):
  768. return self.alice_twview(args=['age_fmt=date'],expect=rf'{rtAmts[0]}\s+'+pat_date)
  769. def alice_twview_date_time(self):
  770. return self.alice_twview(args=['age_fmt=date_time'],expect=rf'{rtAmts[0]}\s+'+pat_date_time)
  771. def alice_txcreate_info(self,args=[]):
  772. t = self.spawn('mmgen-txcreate',['--alice','-Bi'])
  773. for e,s in (
  774. (rf'{rtAmts[0]}\s+\d+\b','D'),
  775. (rf'{rtAmts[0]}\s+\d+\b','D'),
  776. (rf'{rtAmts[0]}\s+\d+\b','D'),
  777. (rf'{rtAmts[0]}\s+'+pat_date,'w'),
  778. (rf'{rtAmts[0]}\s+\d+\s+\d+\s+'+pat_date_time,'q'),
  779. ):
  780. t.expect(e,s,regex=True)
  781. t.read()
  782. return t
  783. def stop(self):
  784. if opt.no_daemon_stop:
  785. self.spawn('',msg_only=True)
  786. msg_r('(leaving daemon running by user request)')
  787. return 'ok'
  788. else:
  789. return self.spawn('mmgen-regtest',['stop'])