ts_regtest.py 32 KB

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