ct_regtest.py 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2024 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. test.cmdtest_py_d.ct_regtest: Regtest tests for the cmdtest.py test suite
  20. """
  21. import sys,os,json,time,re
  22. from decimal import Decimal
  23. from mmgen.color import yellow
  24. from mmgen.util import msg_r,die,gmsg,capfirst,fmt_list
  25. from mmgen.protocol import init_proto
  26. from mmgen.addrlist import AddrList
  27. from mmgen.wallet import Wallet,get_wallet_cls
  28. from ..include.common import (
  29. cfg,
  30. imsg,
  31. omsg,
  32. stop_test_daemons,
  33. joinpath,
  34. silence,
  35. end_silence,
  36. cmp_or_die,
  37. strip_ansi_escapes,
  38. gr_uc,
  39. getrandhex
  40. )
  41. from .common import (
  42. ok_msg,
  43. get_file_with_ext,
  44. get_comment,
  45. tw_comment_lat_cyr_gr,
  46. tw_comment_zh,
  47. tx_comment_jp,
  48. get_env_without_debug_vars
  49. )
  50. from .ct_base import CmdTestBase
  51. from .ct_shared import CmdTestShared
  52. pat_date = r'\b\d\d-\d\d-\d\d\b'
  53. pat_date_time = r'\b\d\d\d\d-\d\d-\d\d\s+\d\d:\d\d\b'
  54. dfl_wcls = get_wallet_cls('mmgen')
  55. tx_fee = rtFundAmt = rtFee = rtBals = rtBals_gb = rtBobOp3 = rtAmts = {} # pylint
  56. rt_pw = 'abc-α'
  57. rt_data = {
  58. 'tx_fee': {'btc':'0.0001','bch':'0.001','ltc':'0.01'},
  59. 'rtFundAmt': {'btc':'500','bch':'500','ltc':'5500'},
  60. 'rtFee': {
  61. 'btc': ('20s','10s','60s','31s','10s','20s'),
  62. 'bch': ('20s','10s','60s','0.0001','10s','20s'),
  63. 'ltc': ('1000s','500s','1500s','0.05','400s','1000s')
  64. },
  65. 'rtBals': {
  66. 'btc': ('499.9999488','399.9998282','399.9998147','399.9996877',
  67. '52.99980410','946.99933647','999.99914057','52.9999',
  68. '946.99933647','0.4169328','6.24987417'),
  69. 'bch': ('499.9999484','399.9999194','399.9998972','399.9997692',
  70. '46.78890380','953.20966920','999.99857300','46.789',
  71. '953.2096692','0.4169328','39.58187387'),
  72. 'ltc': ('5499.99744','5399.994425','5399.993885','5399.987535',
  73. '52.98520500','10946.93753500','10999.92274000','52.99',
  74. '10946.937535','0.41364','6.24846787'),
  75. },
  76. 'rtBals_gb': {
  77. 'btc': {
  78. '0conf0': {
  79. 'mmgen': ('283.22339537','283.22339537'),
  80. 'nonmm': ('16.77647763','116.77629233'),
  81. 'total': ('299.999873','399.9996877'),
  82. },
  83. '0conf1': {
  84. 'mmgen': ('283.22339537','0'),
  85. 'nonmm': ('16.77647763','99.9998147'),
  86. 'total': ('299.999873','99.9998147'),
  87. },
  88. '1conf1': {
  89. 'mmgen': ('0','283.22339537'),
  90. 'nonmm': ('0','116.77629233'),
  91. 'total': ('0','399.9996877'),
  92. },
  93. '1conf2': {
  94. 'mmgen': ('0','283.22339537','0'),
  95. 'nonmm': ('0','16.77647763','99.9998147'),
  96. 'total': ('0','299.999873','99.9998147'),
  97. },
  98. },
  99. 'bch': {
  100. '0conf0': {
  101. 'mmgen': ('283.22339437','283.22339437'),
  102. 'nonmm': ('16.77647763','116.77637483'),
  103. 'total': ('299.999872','399.9997692'),
  104. },
  105. '0conf1': {
  106. 'mmgen': ('283.22339437','0'),
  107. 'nonmm': ('16.77647763','99.9998972'),
  108. 'total': ('299.999872','99.9998972'),
  109. },
  110. '1conf1': {
  111. 'mmgen': ('0','283.22339437'),
  112. 'nonmm': ('0','116.77637483'),
  113. 'total': ('0','399.9997692'),
  114. },
  115. '1conf2': {
  116. 'mmgen': ('0','283.22339437','0'),
  117. 'nonmm': ('0','16.77647763','99.9998972'),
  118. 'total': ('0','299.999872','99.9998972'),
  119. },
  120. },
  121. 'ltc': {
  122. '0conf0': {
  123. 'mmgen': ('283.21717237','283.21717237'),
  124. 'nonmm': ('16.77647763','5116.77036263'),
  125. 'total': ('299.99365','5399.987535'),
  126. },
  127. '0conf1': {
  128. 'mmgen': ('283.21717237','0'),
  129. 'nonmm': ('16.77647763','5099.993885'),
  130. 'total': ('299.99365','5099.993885'),
  131. },
  132. '1conf1': {
  133. 'mmgen': ('0','283.21717237'),
  134. 'nonmm': ('0','5116.77036263'),
  135. 'total': ('0','5399.987535'),
  136. },
  137. '1conf2': {
  138. 'mmgen': ('0','283.21717237','0'),
  139. 'nonmm': ('0','16.77647763','5099.993885'),
  140. 'total': ('0','299.99365','5099.993885'),
  141. },
  142. }
  143. },
  144. 'rtBobOp3': {'btc':'S:2','bch':'L:3','ltc':'S:2'},
  145. 'rtAmts': {
  146. 'btc': ('500','500'),
  147. 'bch': ('500','560'),
  148. 'ltc': ('5500','5500')
  149. }
  150. }
  151. def make_burn_addr(proto):
  152. from mmgen.tool.coin import tool_cmd
  153. return tool_cmd(
  154. cfg = cfg,
  155. cmdname = 'pubhash2addr',
  156. proto = proto,
  157. mmtype = 'compressed' ).pubhash2addr('00'*20)
  158. class CmdTestRegtest(CmdTestBase,CmdTestShared):
  159. 'transacting and tracking wallet operations via regtest mode'
  160. networks = ('btc','ltc','bch')
  161. passthru_opts = ('coin','rpc_backend')
  162. extra_spawn_args = ['--regtest=1']
  163. tmpdir_nums = [17]
  164. color = True
  165. deterministic = False
  166. test_rbf = False
  167. proto = None # pylint
  168. cmd_group_in = (
  169. ('setup', 'regtest (Bob and Alice) mode setup'),
  170. ('subgroup.misc', []),
  171. ('subgroup.init_bob', []),
  172. ('subgroup.init_alice', []),
  173. ('subgroup.fund_users', ['init_bob','init_alice']),
  174. ('subgroup.msg', ['init_bob']),
  175. ('subgroup.twexport', ['fund_users']),
  176. ('subgroup.rescan', ['fund_users']),
  177. ('subgroup.errors', ['fund_users']),
  178. ('subgroup.main', ['fund_users']),
  179. ('subgroup.twprune', ['main']),
  180. ('subgroup.txhist', ['main']),
  181. ('subgroup.label', ['main']),
  182. ('subgroup.view', ['label']),
  183. ('subgroup._auto_chg_deps', ['twexport','label']),
  184. ('subgroup.auto_chg', ['_auto_chg_deps']),
  185. ('stop', 'stopping regtest daemon'),
  186. )
  187. cmd_subgroups = {
  188. 'misc': (
  189. 'miscellaneous commands',
  190. ('daemon_version', 'mmgen-tool daemon_version'),
  191. ('halving_calculator_bob', 'halving calculator (Bob)'),
  192. ),
  193. 'init_bob': (
  194. 'creating Bob’s MMGen wallet and tracking wallet',
  195. ('walletgen_bob', 'wallet generation (Bob)'),
  196. ('addrgen_bob', 'address generation (Bob)'),
  197. ('addrimport_bob', "importing Bob's addresses"),
  198. ),
  199. 'init_alice': (
  200. 'creating Alice’s MMGen wallet and tracking wallet',
  201. ('walletgen_alice', 'wallet generation (Alice)'),
  202. ('addrgen_alice', 'address generation (Alice)'),
  203. ('addrimport_alice', "importing Alice's addresses"),
  204. ),
  205. 'fund_users': (
  206. 'funding Bob and Alice’s wallets',
  207. ('bob_import_miner_addr', "importing miner’s coinbase addr into Bob’s wallet"),
  208. ('fund_bob_deterministic', "funding Bob’s first MMGen address (deterministic method)"),
  209. ('fund_alice_deterministic', "funding Alice’s first MMGen address (deterministic method)"),
  210. ('bob_recreate_tracking_wallet', 'creation of new tracking wallet (Bob)'),
  211. ('addrimport_bob2', "reimporting Bob's addresses"),
  212. ('fund_bob', "funding Bob's wallet"),
  213. ('fund_alice', "funding Alice's wallet"),
  214. ('generate', 'mining a block'),
  215. ('bob_bal1', "Bob's balance"),
  216. ('generate_extra_deterministic', "generate extra blocks for deterministic run"),
  217. ),
  218. 'msg': (
  219. 'message signing',
  220. ('bob_msgcreate', 'creating a message file for signing'),
  221. ('bob_msgsign', 'signing the message file (default wallet)'),
  222. ('bob_walletconv_words', 'creating an MMGen mnemonic wallet'),
  223. ('bob_subwalletgen_bip39', 'creating a BIP39 mnemonic subwallet'),
  224. ('bob_msgsign_userwallet', 'signing the message file (user-specified wallet)'),
  225. ('bob_msgsign_userwallets', 'signing the message file (user-specified wallets)'),
  226. ('bob_msgverify', 'verifying the message file (all addresses)'),
  227. ('bob_msgverify_raw', 'verifying the raw message file (all addresses)'),
  228. ('bob_msgverify_single', 'verifying the message file (single address)'),
  229. ('bob_msgexport_single', 'exporting the message file (single address)'),
  230. ('bob_msgexport', 'exporting the message file (all addresses)'),
  231. ('bob_msgverify_export', 'verifying the exported JSON data (all addresses)'),
  232. ('bob_msgverify_export_single', 'verifying the exported JSON data (single address)'),
  233. ),
  234. 'twexport': (
  235. 'exporting and importing tracking wallet to JSON',
  236. ('bob_twexport', 'exporting a tracking wallet to JSON'),
  237. ('carol_twimport', 'importing a tracking wallet JSON dump'),
  238. ('carol_delete_wallet', 'unloading and deleting Carol’s tracking wallet'),
  239. ('bob_twexport_noamt', 'exporting a tracking wallet to JSON (include_amts=0)'),
  240. ('carol_twimport_nochksum', 'importing a tracking wallet JSON dump (ignore_checksum=1)'),
  241. ('carol_delete_wallet', 'unloading and deleting Carol’s tracking wallet'),
  242. ('carol_twimport_batch', 'importing a tracking wallet JSON dump (batch=1)'),
  243. ('bob_twexport_pretty', 'exporting a tracking wallet to JSON (pretty=1)'),
  244. ('bob_edit_json_twdump', 'editing a tracking wallet JSON dump'),
  245. ('carol_delete_wallet', 'unloading and deleting Carol’s tracking wallet'),
  246. ('carol_twimport_pretty', 'importing an edited tracking wallet JSON dump (ignore_checksum=1)'),
  247. ('carol_listaddresses', 'viewing Carol’s tracking wallet'),
  248. ('carol_delete_wallet', 'unloading and deleting Carol’s tracking wallet'),
  249. ),
  250. 'rescan': (
  251. 'rescanning address and blockchain',
  252. ('bob_resolve_addr', 'resolving an address in the tracking wallet'),
  253. ('bob_rescan_addr', 'rescanning an address'),
  254. ('bob_rescan_blockchain_all', 'rescanning the blockchain (full rescan)'),
  255. ('bob_rescan_blockchain_gb', 'rescanning the blockchain (Genesis block)'),
  256. ('bob_rescan_blockchain_one', 'rescanning the blockchain (single block)'),
  257. ('bob_rescan_blockchain_ss', 'rescanning the blockchain (range of blocks)'),
  258. ),
  259. 'errors': (
  260. 'various error conditions',
  261. ('bob_bad_locktime1', 'broadcast of transaction with bad locktime (block)'),
  262. ('bob_bad_locktime2', 'broadcast of transaction with bad locktime (integer size)'),
  263. ('bob_bad_locktime3', 'broadcast of transaction with bad locktime (time)'),
  264. ),
  265. 'main': (
  266. 'creating, signing, sending and bumping transactions',
  267. ('bob_add_comment1', "adding an 80-screen-width label (lat+cyr+gr)"),
  268. ('bob_twview1', "viewing Bob's tracking wallet"),
  269. ('bob_split1', "splitting Bob's funds"),
  270. ('generate', 'mining a block'),
  271. ('bob_bal2', "Bob's balance"),
  272. ('bob_rbf_1output_create', 'creating RBF tx with one output'),
  273. ('bob_rbf_1output_bump', 'bumping RBF tx with one output'),
  274. ('bob_bal2a', "Bob's balance (age_fmt=confs)"),
  275. ('bob_bal2b', "Bob's balance (showempty=1)"),
  276. ('bob_bal2c', "Bob's balance (showempty=1 minconf=2 age_fmt=days)"),
  277. ('bob_bal2d', "Bob's balance (minconf=2)"),
  278. ('bob_bal2e', "Bob's balance (showempty=1 sort=age)"),
  279. ('bob_bal2f', "Bob's balance (showempty=1 sort=age,reverse)"),
  280. ('bob_send_maybe_rbf', 'sending funds to Alice (RBF, if supported)'),
  281. ('get_mempool1', 'mempool (before RBF bump)'),
  282. ('bob_rbf_status1', 'getting status of transaction'),
  283. ('bob_rbf_bump', 'bumping RBF transaction'),
  284. ('get_mempool2', 'mempool (after RBF bump)'),
  285. ('bob_rbf_status2', 'getting status of transaction after replacement'),
  286. ('bob_rbf_status3', 'getting status of replacement transaction (mempool)'),
  287. ('generate', 'mining a block'),
  288. ('bob_rbf_status4', 'getting status of transaction after confirmed (1) replacement'),
  289. ('bob_rbf_status5', 'getting status of replacement transaction (confirmed)'),
  290. ('generate', 'mining a block'),
  291. ('bob_rbf_status6', 'getting status of transaction after confirmed (2) replacement'),
  292. ('bob_bal3', "Bob's balance"),
  293. ('bob_pre_import', 'sending to non-imported address'),
  294. ('generate', 'mining a block'),
  295. ('bob_import_addr', 'importing non-MMGen address'),
  296. ('bob_bal4', "Bob's balance (after import)"),
  297. ('bob_import_list', 'importing flat address list'),
  298. ('bob_import_list_rescan', 'importing flat address list with --rescan'),
  299. ('bob_import_list_rescan_aio', 'importing flat address list with --rescan (aiohttp backend)'),
  300. ('bob_split2', "splitting Bob's funds"),
  301. ('bob_0conf0_getbalance', "Bob's balance (unconfirmed, minconf=0)"),
  302. ('bob_0conf1_getbalance', "Bob's balance (unconfirmed, minconf=1)"),
  303. ('generate', 'mining a block'),
  304. ('bob_1conf1_getbalance', "Bob's balance (confirmed, minconf=1)"),
  305. ('bob_1conf2_getbalance', "Bob's balance (confirmed, minconf=2)"),
  306. ('bob_bal5', "Bob's balance"),
  307. ('bob_send_non_mmgen', 'sending funds to Alice (from non-MMGen addrs)'),
  308. ('generate', 'mining a block'),
  309. ('alice_send_estimatefee', 'tx creation with no fee on command line'),
  310. ('generate', 'mining a block'),
  311. ('bob_bal6', "Bob's balance"),
  312. ('bob_subwallet_addrgen1', "generating Bob's addrs from subwallet 29L"),
  313. ('bob_subwallet_addrgen2', "generating Bob's addrs from subwallet 127S"),
  314. ('bob_subwallet_addrimport1', "importing Bob's addrs from subwallet 29L"),
  315. ('bob_subwallet_addrimport2', "importing Bob's addrs from subwallet 127S"),
  316. ('bob_subwallet_fund', "funding Bob's subwallet addrs"),
  317. ('generate', 'mining a block'),
  318. ('bob_twview2', "viewing Bob's tracking wallet"),
  319. ('bob_twview3', "viewing Bob's tracking wallet"),
  320. ('bob_subwallet_txcreate', 'creating a transaction with subwallet inputs'),
  321. ('bob_subwallet_txsign', 'signing a transaction with subwallet inputs'),
  322. ('bob_subwallet_txdo', "sending from Bob's subwallet addrs"),
  323. ('generate', 'mining a block'),
  324. ('bob_twview4', "viewing Bob's tracking wallet"),
  325. ('bob_alice_bal', "Bob and Alice's balances"),
  326. ('bob_nochg_burn', 'zero-change transaction to burn address'),
  327. ('generate', 'mining a block'),
  328. ),
  329. 'twprune': (
  330. 'exporting a pruned tracking wallet to JSON',
  331. ('bob_twprune_noask', 'pruning a tracking wallet'),
  332. ('bob_twprune_skip', 'pruning a tracking wallet (skip pruning)'),
  333. ('bob_twprune_all', 'pruning a tracking wallet (pruning all addrs)'),
  334. ('bob_twprune_skipamt', 'pruning a tracking wallet (skipping addrs with amt)'),
  335. ('bob_twprune_skipused', 'pruning a tracking wallet (skipping used addrs)'),
  336. ('bob_twprune_allamt', 'pruning a tracking wallet (pruning addrs with amt)'),
  337. ('bob_twprune_allused', 'pruning a tracking wallet (pruning used addrs)'),
  338. ('bob_twprune1', 'pruning a tracking wallet (selective prune)'),
  339. ('bob_twprune2', 'pruning a tracking wallet (selective prune)'),
  340. ('bob_twprune3', 'pruning a tracking wallet (selective prune)'),
  341. ('bob_twprune4', 'pruning a tracking wallet (selective prune)'),
  342. ('bob_twprune5', 'pruning a tracking wallet (selective prune)'),
  343. ('bob_twprune6', 'pruning a tracking wallet (selective prune)'),
  344. ),
  345. 'txhist': (
  346. 'viewing transaction history',
  347. ('bob_txhist1', "viewing Bob's transaction history (sort=age)"),
  348. ('bob_txhist2', "viewing Bob's transaction history (sort=blockheight reverse=1)"),
  349. ('bob_txhist3', "viewing Bob's transaction history (sort=blockheight sinceblock=-7)"),
  350. ('bob_txhist4', "viewing Bob's transaction history (sinceblock=399 detail=1)"),
  351. ('bob_txhist_interactive', "viewing Bob's transaction history (age_fmt=date_time interactive=true)"),
  352. ),
  353. 'label': (
  354. 'adding, removing and editing labels',
  355. ('alice_bal2', "Alice's balance"),
  356. ('alice_add_comment1', 'adding a label'),
  357. ('alice_chk_comment1', 'the label'),
  358. ('alice_add_comment2', 'adding a label'),
  359. ('alice_chk_comment2', 'the label'),
  360. ('alice_edit_comment1', 'editing a label (zh)'),
  361. ('alice_edit_comment2', 'editing a label (lat+cyr+gr)'),
  362. ('alice_chk_comment3', 'the label'),
  363. ('alice_remove_comment1', 'removing a label'),
  364. ('alice_chk_comment4', 'the label'),
  365. ('alice_add_comment_coinaddr', 'adding a label using the coin address'),
  366. ('alice_chk_comment_coinaddr', 'the label'),
  367. ('alice_add_comment_badaddr1', 'adding a label with invalid address'),
  368. ('alice_add_comment_badaddr2', 'adding a label with invalid address for this chain'),
  369. ('alice_add_comment_badaddr3', 'adding a label with wrong MMGen address'),
  370. ('alice_add_comment_badaddr4', 'adding a label with wrong coin address'),
  371. ),
  372. 'view': (
  373. 'viewing addresses and unspent outputs',
  374. ('alice_listaddresses_scroll', 'listaddresses (--scroll, interactive=1)'),
  375. ('alice_listaddresses_empty', 'listaddresses (no data)'),
  376. ('alice_listaddresses_menu', 'listaddresses (menu items)'),
  377. ('alice_listaddresses1', 'listaddresses'),
  378. ('alice_listaddresses_days', 'listaddresses (age_fmt=days)'),
  379. ('alice_listaddresses_date', 'listaddresses (age_fmt=date)'),
  380. ('alice_listaddresses_date_time', 'listaddresses (age_fmt=date_time)'),
  381. ('alice_twview1', 'twview'),
  382. ('alice_twview_days', 'twview (age_fmt=days)'),
  383. ('alice_twview_date', 'twview (age_fmt=date)'),
  384. ('alice_twview_date_time', 'twview (age_fmt=date_time)'),
  385. ('alice_txcreate_info', 'txcreate -i'),
  386. ('alice_txcreate_info_term', 'txcreate -i (pexpect_spawn)'),
  387. ('bob_send_to_alice_2addr', 'sending a TX to 2 addresses in Alice’s wallet'),
  388. ('bob_send_to_alice_reuse', 'sending a TX to a used address in Alice’s wallet'),
  389. ('generate', 'mining a block'),
  390. ('alice_twview_grouped', 'twview (testing ‘grouped’ option for TX and address)'),
  391. ),
  392. '_auto_chg_deps': (
  393. 'automatic change address selection dependencies',
  394. ('bob_auto_chg_split', 'splitting Bob’s funds (auto-chg-addr dependency)'),
  395. ('bob_auto_chg_generate', 'mining a block (auto-chg-addr dependency)'),
  396. ),
  397. 'auto_chg': (
  398. 'automatic change address selection',
  399. ('bob_auto_chg1', 'creating an automatic change address transaction (C)'),
  400. ('bob_auto_chg2', 'creating an automatic change address transaction (B)'),
  401. ('bob_auto_chg3', 'creating an automatic change address transaction (S)'),
  402. ('bob_auto_chg4', 'creating an automatic change address transaction (single address)'),
  403. ('bob_auto_chg_addrtype1', 'creating an automatic change address transaction by addrtype (C)'),
  404. ('bob_auto_chg_addrtype2', 'creating an automatic change address transaction by addrtype (B)'),
  405. ('bob_auto_chg_addrtype3', 'creating an automatic change address transaction by addrtype (S)'),
  406. ('bob_auto_chg_addrtype4', 'creating an automatic change address transaction by addrtype (single address)'),
  407. ('bob_add_comment_uua1', 'adding a comment for unused address in tracking wallet (C)'),
  408. ('bob_auto_chg5', 'creating an auto-chg-address TX, skipping unused address with label (C)'),
  409. ('bob_auto_chg_addrtype5', 'creating an auto-chg-address TX by addrtype, skipping unused address '
  410. 'with label (C)'),
  411. ('bob_auto_chg6', 'creating an auto-chg-address TX, using unused address with label (C)'),
  412. ('bob_auto_chg_addrtype6', 'creating an auto-chg-address TX by addrtype, using unused address with '
  413. 'label (C)'),
  414. ('bob_remove_comment_uua1', 'removing a comment for unused address in tracking wallet (C)'),
  415. ('bob_auto_chg_bad1', 'error handling for auto change address transaction (bad ID FFFFFFFF:C)'),
  416. ('bob_auto_chg_bad2', 'error handling for auto change address transaction (bad ID 00000000:C)'),
  417. ('bob_auto_chg_bad3', 'error handling for auto change address transaction (no unused addresses)'),
  418. ('bob_auto_chg_bad4', 'error handling for auto change address transaction by addrtype '
  419. '(no unused addresses)'),
  420. ('carol_twimport2', 'recreating Carol’s tracking wallet from JSON dump'),
  421. ('carol_rescan_blockchain', 'rescanning the blockchain (full rescan)'),
  422. ('carol_auto_chg1', 'creating an automatic change address transaction (C)'),
  423. ('carol_auto_chg2', 'creating an automatic change address transaction (B)'),
  424. ('carol_auto_chg3', 'creating an automatic change address transaction (S)'),
  425. ('carol_auto_chg_addrtype1', 'creating an automatic change address transaction by addrtype (C)'),
  426. ('carol_auto_chg_addrtype2', 'creating an automatic change address transaction by addrtype (B)'),
  427. ('carol_auto_chg_addrtype3', 'creating an automatic change address transaction by addrtype (S)'),
  428. ('carol_auto_chg_bad1', 'error handling for auto change address transaction (no unused addresses)'),
  429. ('carol_auto_chg_bad2', 'error handling for auto change address transaction by addrtype '
  430. '(no unused addresses)'),
  431. ('carol_delete_wallet', 'unloading and deleting Carol’s tracking wallet'),
  432. ),
  433. }
  434. def __init__(self,trunner,cfgs,spawn):
  435. CmdTestBase.__init__(self,trunner,cfgs,spawn)
  436. if trunner == None:
  437. return
  438. if self.proto.testnet:
  439. die(2,'--testnet and --regtest options incompatible with regtest test suite')
  440. self.proto = init_proto( cfg, self.proto.coin, network='regtest', need_amt=True )
  441. coin = self.proto.coin.lower()
  442. for k in rt_data:
  443. setattr( sys.modules[__name__], k, rt_data[k][coin] if coin in rt_data[k] else None )
  444. if self.proto.coin == 'BTC':
  445. self.test_rbf = True # tests are non-coin-dependent, so run just once for BTC
  446. if cfg.test_suite_deterministic:
  447. self.deterministic = True
  448. self.miner_addr = 'bcrt1qaq8t3pakcftpk095tnqfv5cmmczysls024atnd' # regtest.create_hdseed()
  449. self.miner_wif = 'cTyMdQ2BgfAsjopRVZrj7AoEGp97pKfrC2NkqLuwHr4KHfPNAKwp'
  450. self.spawn_env['MMGEN_BOGUS_SEND'] = ''
  451. self.write_to_tmpfile('wallet_password',rt_pw)
  452. self.dfl_mmtype = 'C' if self.proto.coin == 'BCH' else 'B'
  453. self.burn_addr = make_burn_addr(self.proto)
  454. self.user_sids = {}
  455. def _add_comments_to_addr_file(self,addrfile,outfile,use_comments=False):
  456. silence()
  457. gmsg(f'Adding comments to address file {addrfile!r}')
  458. a = AddrList( cfg, self.proto, addrfile )
  459. for n,idx in enumerate(a.idxs(),1):
  460. if use_comments:
  461. a.set_comment(idx,get_comment())
  462. else:
  463. if n % 2:
  464. a.set_comment(idx,f'Test address {n}')
  465. a.file.format(add_comments=True)
  466. from mmgen.fileutil import write_data_to_file
  467. write_data_to_file(
  468. cfg,
  469. outfile = outfile,
  470. data = a.file.fmt_data,
  471. quiet = True,
  472. ignore_opt_outdir = True )
  473. end_silence()
  474. def setup(self):
  475. stop_test_daemons(self.proto.network_id,force=True,remove_datadir=True)
  476. from shutil import rmtree
  477. try:
  478. rmtree(joinpath(self.tr.data_dir,'regtest'))
  479. except:
  480. pass
  481. t = self.spawn('mmgen-regtest',['-n','setup'])
  482. for s in ('Starting','Creating','Creating','Creating','Mined','Setup complete'):
  483. t.expect(s)
  484. return t
  485. def daemon_version(self):
  486. t = self.spawn('mmgen-tool', ['--bob','daemon_version'])
  487. t.expect('version')
  488. return t
  489. def halving_calculator_bob(self):
  490. t = self.spawn('halving-calculator.py',['--bob'],cmd_dir='examples')
  491. t.expect('time until halving')
  492. return t
  493. def walletgen(self,user):
  494. t = self.spawn('mmgen-walletgen',['-q','-r0','-p1','--'+user])
  495. t.passphrase_new('new '+dfl_wcls.desc,rt_pw)
  496. t.label()
  497. t.expect('move it to the data directory? (Y/n): ','y')
  498. t.written_to_file(capfirst(dfl_wcls.desc))
  499. return t
  500. def walletgen_bob(self):
  501. return self.walletgen('bob')
  502. def walletgen_alice(self):
  503. return self.walletgen('alice')
  504. def _user_dir(self,user,coin=None):
  505. return joinpath(self.tr.data_dir,'regtest',coin or self.proto.coin.lower(),user)
  506. def _user_sid(self,user):
  507. if user in self.user_sids:
  508. return self.user_sids[user]
  509. else:
  510. self.user_sids[user] = os.path.basename(get_file_with_ext(self._user_dir(user),'mmdat'))[:8]
  511. return self.user_sids[user]
  512. def _get_user_subsid(self,user,subseed_idx):
  513. fn = get_file_with_ext(self._user_dir(user),dfl_wcls.ext)
  514. silence()
  515. w = Wallet( cfg, fn=fn, passwd_file=os.path.join(self.tmpdir,'wallet_password') )
  516. end_silence()
  517. return w.seed.subseed(subseed_idx).sid
  518. def addrgen(
  519. self,
  520. user,
  521. wf = None,
  522. addr_range = '1-5',
  523. subseed_idx = None,
  524. mmtypes = []):
  525. from mmgen.addr import MMGenAddrType
  526. for mmtype in mmtypes or self.proto.mmtypes:
  527. t = self.spawn(
  528. 'mmgen-addrgen',
  529. ['--quiet','--'+user,'--type='+mmtype,f'--outdir={self._user_dir(user)}'] +
  530. ([wf] if wf else []) +
  531. (['--subwallet='+subseed_idx] if subseed_idx else []) +
  532. [addr_range],
  533. extra_desc = '({})'.format( MMGenAddrType.mmtypes[mmtype].name ))
  534. t.passphrase(dfl_wcls.desc,rt_pw)
  535. t.written_to_file('Addresses')
  536. ok_msg()
  537. t.skip_ok = True
  538. return t
  539. def addrgen_bob(self):
  540. return self.addrgen('bob')
  541. def addrgen_alice(self):
  542. return self.addrgen('alice')
  543. def addrimport(
  544. self,
  545. user,
  546. sid = None,
  547. addr_range = '1-5',
  548. num_addrs = 5,
  549. mmtypes = [],
  550. batch = True,
  551. quiet = True):
  552. id_strs = { 'legacy':'', 'compressed':'-C', 'segwit':'-S', 'bech32':'-B' }
  553. if not sid:
  554. sid = self._user_sid(user)
  555. from mmgen.addr import MMGenAddrType
  556. for mmtype in mmtypes or self.proto.mmtypes:
  557. desc = MMGenAddrType.mmtypes[mmtype].name
  558. addrfile = joinpath(self._user_dir(user),
  559. '{}{}{}[{}]{x}.regtest.addrs'.format(
  560. sid,self.altcoin_pfx,id_strs[desc],addr_range,
  561. x='-α' if cfg.debug_utf8 else ''))
  562. if mmtype == self.proto.mmtypes[0] and user == 'bob':
  563. self._add_comments_to_addr_file(addrfile,addrfile,use_comments=True)
  564. t = self.spawn(
  565. 'mmgen-addrimport',
  566. args = (
  567. (['--quiet'] if quiet else []) +
  568. ['--'+user] +
  569. (['--batch'] if batch else []) +
  570. [addrfile] ),
  571. extra_desc = f'({desc})' )
  572. if cfg.debug:
  573. t.expect("Type uppercase 'YES' to confirm: ",'YES\n')
  574. t.expect('Importing')
  575. if batch:
  576. t.expect(f'{num_addrs} addresses imported')
  577. else:
  578. t.expect('import completed OK')
  579. t.ok()
  580. t.skip_ok = True
  581. return t
  582. def addrimport_bob(self):
  583. return self.addrimport('bob')
  584. def addrimport_alice(self):
  585. return self.addrimport('alice',batch=False,quiet=False)
  586. def bob_import_miner_addr(self):
  587. if not self.deterministic:
  588. return 'skip'
  589. return self.spawn(
  590. 'mmgen-addrimport',
  591. [ '--bob', '--rescan', '--quiet', f'--address={self.miner_addr}' ] )
  592. def fund_wallet_deterministic(self,addr,utxo_nums,skip_passphrase=False):
  593. """
  594. the deterministic funding method using specific inputs
  595. """
  596. if not self.deterministic:
  597. return 'skip'
  598. self.write_to_tmpfile('miner.key',f'{self.miner_wif}\n')
  599. keyfile = joinpath(self.tmpdir,'miner.key')
  600. return self.user_txdo(
  601. 'bob', '40s',
  602. [ f'{addr},{rtFundAmt}', self.burn_addr ],
  603. utxo_nums,
  604. extra_args = [f'--keys-from-file={keyfile}'],
  605. skip_passphrase = skip_passphrase )
  606. def fund_bob_deterministic(self):
  607. return self.fund_wallet_deterministic( f'{self._user_sid("bob")}:C:1', '1-11' )
  608. def fund_alice_deterministic(self):
  609. sid = self._user_sid('alice')
  610. mmtype = ('L','S')[self.proto.cap('segwit')]
  611. addr = self.get_addr_from_addrlist('alice',sid,mmtype,0,addr_range='1-5')
  612. return self.fund_wallet_deterministic( addr, '1-11', skip_passphrase=True )
  613. def generate_extra_deterministic(self):
  614. if not self.deterministic:
  615. return 'skip'
  616. return self.generate(num_blocks=2) # do this so block count matches non-deterministic run
  617. async def bob_recreate_tracking_wallet(self):
  618. if not self.deterministic:
  619. return 'skip'
  620. self.spawn('',msg_only=True)
  621. from mmgen.proto.btc.regtest import MMGenRegtest
  622. rt = MMGenRegtest(cfg,self.proto.coin)
  623. await rt.stop()
  624. from shutil import rmtree
  625. imsg('Deleting Bob’s old tracking wallet')
  626. rmtree(os.path.join(rt.d.datadir,'regtest','wallets','bob'),ignore_errors=True)
  627. rt.init_daemon()
  628. rt.d.start(silent=True)
  629. imsg('Creating Bob’s new tracking wallet')
  630. await rt.rpc_call('createwallet','bob',True,True,None,False,False,False)
  631. await rt.stop()
  632. await rt.start()
  633. return 'ok'
  634. def addrimport_bob2(self):
  635. if not self.deterministic:
  636. return 'skip'
  637. return self.addrimport('bob')
  638. def fund_wallet(self,user,mmtype,amt,sid=None,addr_range='1-5'):
  639. if self.deterministic:
  640. return 'skip'
  641. if not sid:
  642. sid = self._user_sid(user)
  643. addr = self.get_addr_from_addrlist(user,sid,mmtype,0,addr_range=addr_range)
  644. t = self.spawn('mmgen-regtest', ['send',str(addr),str(amt)])
  645. t.expect(f'Sending {amt} miner {self.proto.coin}')
  646. t.expect('Mined 1 block')
  647. return t
  648. def fund_bob(self):
  649. return self.fund_wallet('bob','C',rtFundAmt)
  650. def fund_alice(self):
  651. return self.fund_wallet('alice',('L','S')[self.proto.cap('segwit')],rtFundAmt)
  652. def user_twview(self,user,chk,sort='age'):
  653. t = self.spawn('mmgen-tool',['--'+user,'twview','sort='+sort])
  654. if chk:
  655. t.expect(r'{}\b.*\D{}\b'.format(*chk),regex=True)
  656. return t
  657. def bob_twview1(self):
  658. return self.user_twview('bob', chk = ('1',rtAmts[0]) )
  659. def user_bal(self,user,bal,args=['showempty=1'],skip_check=False):
  660. t = self.spawn('mmgen-tool',['--'+user,'listaddresses'] + args)
  661. if not skip_check:
  662. cmp_or_die(f'{bal} {self.proto.coin}',strip_ansi_escapes(t.expect_getend('TOTAL: ')))
  663. return t
  664. def alice_bal1(self):
  665. return self.user_bal('alice',rtFundAmt)
  666. def alice_bal2(self):
  667. return self.user_bal('alice',rtBals[8])
  668. def bob_bal1(self):
  669. return self.user_bal('bob',rtFundAmt)
  670. def bob_bal2(self):
  671. return self.user_bal('bob',rtBals[0])
  672. def bob_bal2a(self):
  673. return self.user_bal('bob',rtBals[0],args=['showempty=1','age_fmt=confs'])
  674. def bob_bal2b(self):
  675. return self.user_bal('bob',rtBals[0],args=['showempty=1'])
  676. def bob_bal2c(self):
  677. return self.user_bal('bob',rtBals[0],args=['showempty=1','minconf=2','age_fmt=days'],skip_check=True)
  678. def bob_bal2d(self):
  679. return self.user_bal('bob',rtBals[0],args=['minconf=2'],skip_check=True)
  680. def bob_bal2e(self):
  681. return self.user_bal('bob',rtBals[0],args=['showempty=1','sort=amt'])
  682. def bob_bal2f(self):
  683. return self.user_bal('bob',rtBals[0],args=['showempty=0','sort=twmmid','reverse=1'])
  684. def bob_bal3(self):
  685. return self.user_bal('bob',rtBals[1])
  686. def bob_bal4(self):
  687. return self.user_bal('bob',rtBals[2])
  688. def bob_bal5(self):
  689. return self.user_bal('bob',rtBals[3])
  690. def bob_bal6(self):
  691. return self.user_bal('bob',rtBals[7])
  692. def bob_subwallet_addrgen1(self):
  693. return self.addrgen('bob',subseed_idx='29L',mmtypes=['C']) # 29L: 2FA7BBA8
  694. def bob_subwallet_addrgen2(self):
  695. return self.addrgen('bob',subseed_idx='127S',mmtypes=['C']) # 127S: '09E8E286'
  696. def subwallet_addrimport(self,user,subseed_idx):
  697. sid = self._get_user_subsid(user,subseed_idx)
  698. return self.addrimport(user,sid=sid,mmtypes=['C'])
  699. def bob_subwallet_addrimport1(self):
  700. return self.subwallet_addrimport('bob','29L')
  701. def bob_subwallet_addrimport2(self):
  702. return self.subwallet_addrimport('bob','127S')
  703. def bob_subwallet_fund(self):
  704. sid1 = self._get_user_subsid('bob','29L')
  705. sid2 = self._get_user_subsid('bob','127S')
  706. chg_addr = self._user_sid('bob') + (':B:1',':L:1')[self.proto.coin=='BCH']
  707. return self.user_txdo(
  708. user = 'bob',
  709. fee = rtFee[1],
  710. outputs_cl = [sid1+':C:2,0.29',sid2+':C:3,0.127',chg_addr],
  711. outputs_list = ('3','1')[self.proto.coin=='BCH'],
  712. extra_args = ['--subseeds=127'],
  713. used_chg_addr_resp = (None,'y')[self.proto.coin=='BCH'] )
  714. def bob_twview2(self):
  715. sid1 = self._get_user_subsid('bob','29L')
  716. return self.user_twview('bob',chk=(sid1+':C:2','0.29'),sort='twmmid')
  717. def bob_twview3(self):
  718. sid2 = self._get_user_subsid('bob','127S')
  719. return self.user_twview('bob',chk=(sid2+':C:3','0.127'),sort='amt')
  720. def bob_subwallet_txcreate(self):
  721. sid1 = self._get_user_subsid('bob','29L')
  722. sid2 = self._get_user_subsid('bob','127S')
  723. outputs_cl = [sid1+':C:5,0.0159',sid2+':C:5']
  724. t = self.spawn('mmgen-txcreate',['-d',self.tmpdir,'-B','--bob'] + outputs_cl)
  725. return self.txcreate_ui_common(t,
  726. menu = ['a'],
  727. inputs = ('1,2','2,3')[self.proto.coin=='BCH'],
  728. interactive_fee = '0.00001')
  729. def bob_subwallet_txsign(self):
  730. fn = get_file_with_ext(self.tmpdir,'rawtx')
  731. t = self.spawn('mmgen-txsign',['-d',self.tmpdir,'--bob','--subseeds=127',fn])
  732. t.view_tx('t')
  733. t.passphrase(dfl_wcls.desc,rt_pw)
  734. t.do_comment(None)
  735. t.expect('(Y/n): ','y')
  736. t.written_to_file('Signed transaction')
  737. return t
  738. def bob_subwallet_txdo(self):
  739. outputs_cl = [self._user_sid('bob')+':L:5']
  740. inputs = ('1,2','2,3')[self.proto.coin=='BCH']
  741. return self.user_txdo('bob',rtFee[5],outputs_cl,inputs,menu=['a'],extra_args=['--subseeds=127']) # sort: amt
  742. def bob_twview4(self):
  743. sid = self._user_sid('bob')
  744. return self.user_twview('bob',chk=(sid+':L:5',rtBals[9]),sort='twmmid')
  745. def user_txhist(self,user,args,expect):
  746. t = self.spawn('mmgen-tool',['--'+user,'txhist'] + args)
  747. m = re.search( expect, t.read(strip_color=True), re.DOTALL )
  748. assert m, f'Expected: {expect}'
  749. return t
  750. def bob_txhist1(self):
  751. return self.user_txhist('bob',
  752. args = ['sort=age'],
  753. expect = fr'\s1\).*\s{rtFundAmt}\s' )
  754. def bob_txhist2(self):
  755. return self.user_txhist('bob',
  756. args = ['sort=blockheight','reverse=1','age_fmt=block'],
  757. expect = fr'\s1\).*:{self.dfl_mmtype}:1\s' )
  758. def bob_txhist3(self):
  759. return self.user_txhist('bob',
  760. args = ['sort=blockheight','sinceblock=-7','age_fmt=block'],
  761. expect = fr'Displaying transactions since block 399.*\s6\)\s+405\s.*\s{rtBals[9]}\s.*:L:5.*\s7\)'
  762. )
  763. def bob_txhist4(self):
  764. return self.user_txhist('bob',
  765. args = ['sort=blockheight','sinceblock=399','age_fmt=block','detail=1'],
  766. expect = fr'Displaying transactions since block 399.*\s7\).*Block:.*406.*Value:.*{rtBals[10]}'
  767. )
  768. def bob_txhist_interactive(self):
  769. self.get_file_with_ext('out',delete_all=True)
  770. t = self.spawn('mmgen-tool',
  771. ['--bob',f'--outdir={self.tmpdir}','txhist','age_fmt=date_time','interactive=true'] )
  772. for resp in ('u','i','t','a','m','T','A','r','r','D','D','D','D','p','P','n','V'):
  773. t.expect('draw:\b',resp,regex=True)
  774. if t.pexpect_spawn:
  775. t.expect(r'Block:.*394',regex=True)
  776. time.sleep(1)
  777. t.send('q')
  778. time.sleep(0.2)
  779. t.send('n')
  780. t.expect('draw:\b','q',regex=True)
  781. else:
  782. txnum,idx = (8,1) if self.proto.coin == 'BCH' else (9,3)
  783. t.expect(rf'\s{txnum}\).*Inputs:.*:L:{idx}.*Outputs \(3\):.*:C:2.*\s10\)','q',regex=True)
  784. return t
  785. def bob_getbalance(self,bals,confs=1):
  786. for i in range(len(bals['mmgen'])):
  787. assert Decimal(bals['mmgen'][i]) + Decimal(bals['nonmm'][i]) == Decimal(bals['total'][i])
  788. sid = self._user_sid('bob')
  789. t = self.spawn('mmgen-tool',['--bob','getbalance',f'minconf={confs}'])
  790. t.expect('Wallet')
  791. for k,lbl in (
  792. ('mmgen',f'{sid}:'),
  793. ('nonmm','Non-MMGen:'),
  794. ('total',f'TOTAL {self.proto.coin}')
  795. ):
  796. ret = strip_ansi_escapes(t.expect_getend(lbl + ' '))
  797. cmp_or_die(
  798. ' '.join(bals[k]),
  799. ' '.join(ret.split()),
  800. desc = k,
  801. )
  802. return t
  803. def bob_0conf0_getbalance(self):
  804. return self.bob_getbalance(rtBals_gb['0conf0'],confs=0)
  805. def bob_0conf1_getbalance(self):
  806. return self.bob_getbalance(rtBals_gb['0conf1'],confs=1)
  807. def bob_1conf1_getbalance(self):
  808. return self.bob_getbalance(rtBals_gb['1conf1'],confs=1)
  809. def bob_1conf2_getbalance(self):
  810. return self.bob_getbalance(rtBals_gb['1conf2'],confs=2)
  811. def bob_nochg_burn(self):
  812. return self.user_txdo('bob',
  813. fee = '0.00009713',
  814. outputs_cl = [self.burn_addr],
  815. outputs_list = '1' )
  816. def bob_alice_bal(self):
  817. t = self.spawn('mmgen-regtest',['balances'])
  818. ret = t.expect_getend("Bob's balance:").strip()
  819. cmp_or_die(rtBals[4],ret)
  820. ret = t.expect_getend("Alice's balance:").strip()
  821. cmp_or_die(rtBals[5],ret)
  822. ret = t.expect_getend("Total balance:").strip()
  823. cmp_or_die(rtBals[6],ret)
  824. return t
  825. def user_txsend_status(self,user,tx_file,exp1='',exp2='',extra_args=[]):
  826. t = self.spawn('mmgen-txsend',['-d',self.tmpdir,'--'+user,'--status'] + extra_args + [tx_file])
  827. if exp1:
  828. t.expect(exp1,regex=True)
  829. if exp2:
  830. t.expect(exp2,regex=True)
  831. return t
  832. def user_txdo( self,
  833. user,
  834. fee,
  835. outputs_cl,
  836. outputs_list,
  837. extra_args = [],
  838. wf = None,
  839. add_comment = tx_comment_jp,
  840. return_early = False,
  841. return_after_send = False,
  842. menu = ['M'],
  843. skip_passphrase = False,
  844. used_chg_addr_resp = None):
  845. t = self.spawn('mmgen-txdo',
  846. ['-d',self.tmpdir,'-B','--'+user] +
  847. (['--fee='+fee] if fee else []) +
  848. extra_args + ([],[wf])[bool(wf)] + outputs_cl)
  849. self.txcreate_ui_common(
  850. t,
  851. caller = 'txdo',
  852. menu = menu,
  853. inputs = outputs_list,
  854. file_desc = 'Signed transaction',
  855. interactive_fee = (tx_fee,'')[bool(fee)],
  856. add_comment = add_comment,
  857. return_early = return_early,
  858. view = 't',
  859. save = True,
  860. used_chg_addr_resp = used_chg_addr_resp)
  861. if return_early:
  862. return t
  863. if not skip_passphrase:
  864. t.passphrase(dfl_wcls.desc,rt_pw)
  865. t.written_to_file('Signed transaction')
  866. self._do_confirm_send(t)
  867. if return_after_send:
  868. return t
  869. t.expect('Transaction sent')
  870. return t
  871. def bob_split1(self):
  872. sid = self._user_sid('bob')
  873. outputs_cl = [sid+':C:1,100', sid+':L:2,200',sid+':'+rtBobOp3]
  874. return self.user_txdo('bob',rtFee[0],outputs_cl,'1',extra_args=['--locktime=500000001'])
  875. def get_addr_from_addrlist(self,user,sid,mmtype,idx,addr_range='1-5'):
  876. id_str = { 'L':'', 'S':'-S', 'C':'-C', 'B':'-B' }[mmtype]
  877. ext = '{}{}{}[{}]{x}.regtest.addrs'.format(
  878. sid,self.altcoin_pfx,id_str,addr_range,x='-α' if cfg.debug_utf8 else '')
  879. addrfile = get_file_with_ext(self._user_dir(user),ext,no_dot=True)
  880. silence()
  881. addr = AddrList( cfg, self.proto, addrfile ).data[idx].addr
  882. end_silence()
  883. return addr
  884. def _create_tx_outputs(self,user,data):
  885. sid = self._user_sid(user)
  886. return [self.get_addr_from_addrlist(user,sid,mmtype,idx-1)+amt_str for mmtype,idx,amt_str in data]
  887. def bob_rbf_1output_create(self):
  888. if not self.test_rbf:
  889. return 'skip'
  890. out_addr = self._create_tx_outputs('alice',(('B',5,''),))
  891. t = self.spawn('mmgen-txcreate',['-d',self.tr.trash_dir,'-B','--bob'] + out_addr)
  892. return self.txcreate_ui_common(t,menu=[],inputs='3',interactive_fee='3s') # out amt: 199.99999343
  893. def bob_rbf_1output_bump(self):
  894. if not self.test_rbf:
  895. return 'skip'
  896. ext = '9343,3]{x}.regtest.rawtx'.format(x='-α' if cfg.debug_utf8 else '')
  897. txfile = get_file_with_ext(self.tr.trash_dir,ext,delete=False,no_dot=True)
  898. return self.user_txbump('bob',
  899. self.tr.trash_dir,
  900. txfile,
  901. '8s',
  902. has_label = False,
  903. signed_tx = False,
  904. one_output = True )
  905. def bob_send_maybe_rbf(self):
  906. outputs_cl = self._create_tx_outputs('alice',(('L',1,',60'),('C',1,',40'))) # alice_sid:L:1, alice_sid:C:1
  907. outputs_cl += [self._user_sid('bob')+':'+rtBobOp3]
  908. return self.user_txdo('bob',rtFee[1],outputs_cl,'3',
  909. extra_args = (['--no-rbf'],[])[self.proto.cap('rbf')],
  910. used_chg_addr_resp = 'y' )
  911. def bob_send_non_mmgen(self):
  912. outputs_cl = self._create_tx_outputs('alice',(
  913. (('L','S')[self.proto.cap('segwit')],2,',10'),
  914. (('L','S')[self.proto.cap('segwit')],3,'')
  915. )) # alice_sid:S:2, alice_sid:S:3
  916. keyfile = joinpath(self.tmpdir,'non-mmgen.keys')
  917. return self.user_txdo('bob',rtFee[3],outputs_cl,'1,4-10',
  918. extra_args=['--keys-from-file='+keyfile,'--vsize-adj=1.02'])
  919. def alice_send_estimatefee(self):
  920. outputs_cl = self._create_tx_outputs('bob',(('L',1,''),)) # bob_sid:L:1
  921. return self.user_txdo('alice',None,outputs_cl,'1') # fee=None
  922. def user_txbump(
  923. self,
  924. user,
  925. outdir,
  926. txfile,
  927. fee,
  928. add_args = [],
  929. has_label = True,
  930. signed_tx = True,
  931. one_output = False):
  932. if not self.proto.cap('rbf'):
  933. return 'skip'
  934. t = self.spawn('mmgen-txbump',
  935. ['-d',outdir,'--'+user,'--fee='+fee,'--output-to-reduce=c'] + add_args + [txfile])
  936. if not one_output:
  937. t.expect('OK? (Y/n): ','y') # output OK?
  938. t.expect('OK? (Y/n): ','y') # fee OK?
  939. t.do_comment(False,has_label=has_label)
  940. if signed_tx:
  941. t.passphrase(dfl_wcls.desc,rt_pw)
  942. t.written_to_file('Signed transaction')
  943. self.txsend_ui_common(t,caller='txdo',bogus_send=False,file_desc='Signed transaction')
  944. else:
  945. t.expect('Save fee-bumped transaction? (y/N): ','y')
  946. t.written_to_file('Fee-bumped transaction')
  947. return t
  948. def bob_rbf_bump(self):
  949. ext = ',{}]{x}.regtest.sigtx'.format(rtFee[1][:-1],x='-α' if cfg.debug_utf8 else '')
  950. txfile = self.get_file_with_ext(ext,delete=False,no_dot=True)
  951. return self.user_txbump('bob',self.tmpdir,txfile,rtFee[2],add_args=['--send'])
  952. def generate(self,num_blocks=1):
  953. int(num_blocks)
  954. t = self.spawn('mmgen-regtest',['generate',str(num_blocks)])
  955. t.expect(f'Mined {num_blocks} block')
  956. return t
  957. def _get_mempool(self):
  958. ret = self.spawn(
  959. 'mmgen-regtest',
  960. ['mempool'],
  961. env = os.environ if cfg.debug_utf8 else get_env_without_debug_vars(),
  962. ).read()
  963. m = re.search(r'(\[\s*"[a-f0-9]{64}"\s*])',ret) # allow for extra output by handler at end
  964. return json.loads(m.group(1))
  965. def get_mempool1(self):
  966. mp = self._get_mempool()
  967. if len(mp) != 1:
  968. die(4,'Mempool has more or less than one TX!')
  969. self.write_to_tmpfile('rbf_txid',mp[0]+'\n')
  970. return 'ok'
  971. def bob_rbf_status(self,fee,exp1,exp2=''):
  972. if not self.proto.cap('rbf'):
  973. return 'skip'
  974. ext = ',{}]{x}.regtest.sigtx'.format(fee[:-1],x='-α' if cfg.debug_utf8 else '')
  975. txfile = self.get_file_with_ext(ext,delete=False,no_dot=True)
  976. return self.user_txsend_status('bob',txfile,exp1,exp2)
  977. def bob_rbf_status1(self):
  978. if not self.proto.cap('rbf'):
  979. return 'skip'
  980. return self.bob_rbf_status(rtFee[1],'in mempool, replaceable')
  981. def get_mempool2(self):
  982. if not self.proto.cap('rbf'):
  983. return 'skip'
  984. mp = self._get_mempool()
  985. if len(mp) != 1:
  986. die(4,'Mempool has more or less than one TX!')
  987. chk = self.read_from_tmpfile('rbf_txid')
  988. if chk.strip() == mp[0]:
  989. die(4,'TX in mempool has not changed! RBF bump failed')
  990. self.write_to_tmpfile('rbf_txid2',mp[0]+'\n')
  991. return 'ok'
  992. def bob_rbf_status2(self):
  993. if not self.proto.cap('rbf'):
  994. return 'skip'
  995. new_txid = self.read_from_tmpfile('rbf_txid2').strip()
  996. return self.bob_rbf_status(rtFee[1],
  997. 'Transaction has been replaced',f'{new_txid} in mempool')
  998. def bob_rbf_status3(self):
  999. if not self.proto.cap('rbf'):
  1000. return 'skip'
  1001. return self.bob_rbf_status(rtFee[2],'status: in mempool, replaceable')
  1002. def bob_rbf_status4(self):
  1003. if not self.proto.cap('rbf'):
  1004. return 'skip'
  1005. new_txid = self.read_from_tmpfile('rbf_txid2').strip()
  1006. return self.bob_rbf_status(rtFee[1],
  1007. 'Replacement transaction has 1 confirmation',
  1008. rf'Replacing transactions:\s+{new_txid}' )
  1009. def bob_rbf_status5(self):
  1010. if not self.proto.cap('rbf'):
  1011. return 'skip'
  1012. return self.bob_rbf_status(rtFee[2],'Transaction has 1 confirmation')
  1013. def bob_rbf_status6(self):
  1014. if not self.proto.cap('rbf'):
  1015. return 'skip'
  1016. new_txid = self.read_from_tmpfile('rbf_txid2').strip()
  1017. return self.bob_rbf_status(rtFee[1],
  1018. 'Replacement transaction has 2 confirmations',
  1019. rf'Replacing transactions:\s+{new_txid}' )
  1020. def _gen_pairs(self,n):
  1021. from mmgen.tool.api import tool_api
  1022. t = tool_api(cfg)
  1023. t.init_coin(self.proto.coin,self.proto.network)
  1024. def gen_addr(Type):
  1025. t.addrtype = Type
  1026. wif = t.hex2wif(getrandhex(32))
  1027. return ( wif, t.wif2addr(wif) )
  1028. return [gen_addr('legacy')] + [gen_addr('compressed') for i in range(n-1)]
  1029. def bob_pre_import(self):
  1030. pairs = self._gen_pairs(5)
  1031. self.write_to_tmpfile('non-mmgen.keys','\n'.join([a[0] for a in pairs])+'\n')
  1032. self.write_to_tmpfile('non-mmgen.addrs','\n'.join([a[1] for a in pairs])+'\n')
  1033. return self.user_txdo('bob',rtFee[4],[pairs[0][1]],'3')
  1034. def user_import(self,user,args,nAddr):
  1035. t = self.spawn('mmgen-addrimport',['--'+user]+args)
  1036. if cfg.debug:
  1037. t.expect("Type uppercase 'YES' to confirm: ",'YES\n')
  1038. t.expect(f'Importing {nAddr} address')
  1039. if '--rescan' in args:
  1040. if not '--quiet' in args:
  1041. t.expect('Continue? (Y/n): ','y')
  1042. t.expect('Rescanning block')
  1043. return t
  1044. def bob_import_addr(self):
  1045. addr = self.read_from_tmpfile('non-mmgen.addrs').split()[0]
  1046. return self.user_import('bob',['--quiet','--address='+addr],nAddr=1)
  1047. def bob_import_list_rescan_aio(self):
  1048. addrfile = joinpath(self.tmpdir,'non-mmgen.addrs')
  1049. return self.user_import('bob',['--rescan','--rpc-backend=aio','--addrlist',addrfile],nAddr=5)
  1050. def bob_resolve_addr(self):
  1051. mmaddr = '{}:C:1'.format(self._user_sid('bob'))
  1052. t = self.spawn('mmgen-tool',['--bob','resolve_address',mmaddr])
  1053. coinaddr = t.read().split()[0].strip()
  1054. t = self.spawn('mmgen-tool',['--bob','resolve_address',coinaddr],no_msg=True)
  1055. mmaddr_res = t.read().split()[0].strip()
  1056. assert mmaddr == mmaddr_res, f'{mmaddr} != {mmaddr_res}'
  1057. return t
  1058. def bob_import_list(self):
  1059. addrfile = joinpath(self.tmpdir,'non-mmgen.addrs')
  1060. return self.user_import('bob',['--quiet','--addrlist',addrfile],nAddr=5)
  1061. def bob_import_list_rescan(self):
  1062. addrfile = joinpath(self.tmpdir,'non-mmgen.addrs')
  1063. return self.user_import('bob',['--quiet','--rescan','--addrlist',addrfile],nAddr=5)
  1064. def bob_rescan_addr(self):
  1065. sid = self._user_sid('bob')
  1066. t = self.spawn('mmgen-tool',['--bob','rescan_address',f'{sid}:C:1'])
  1067. t.expect('Found 1 unspent output')
  1068. t.expect('updated successfully')
  1069. return t
  1070. def _usr_rescan_blockchain(self,user,add_args,expect=None):
  1071. t = self.spawn('mmgen-tool',[f'--{user}','rescan_blockchain'] + add_args)
  1072. if expect:
  1073. t.expect(f'Scanning blocks {expect}')
  1074. t.expect('Done')
  1075. return t
  1076. def bob_rescan_blockchain_all(self):
  1077. return self._usr_rescan_blockchain('bob',[],'300-396')
  1078. def bob_rescan_blockchain_gb(self):
  1079. return self._usr_rescan_blockchain('bob',['start_block=0','stop_block=0'],'0-0')
  1080. def bob_rescan_blockchain_one(self):
  1081. return self._usr_rescan_blockchain('bob',['start_block=300','stop_block=300'],'300-300')
  1082. def bob_rescan_blockchain_ss(self):
  1083. return self._usr_rescan_blockchain('bob',['start_block=300','stop_block=302'],'300-302')
  1084. def bob_twexport(self,add_args=[]):
  1085. t = self.spawn('mmgen-tool',['--bob',f'--outdir={self.tmpdir}','twexport'] + add_args)
  1086. t.written_to_file('JSON data')
  1087. return t
  1088. def bob_twexport_noamt(self):
  1089. return self.bob_twexport(add_args=['include_amts=0'])
  1090. def bob_twexport_pretty(self):
  1091. return self.bob_twexport(add_args=['pretty=1'])
  1092. def _bob_twprune(
  1093. self,
  1094. prune_spec,
  1095. npruned,
  1096. expect_menu = (),
  1097. expect = (),
  1098. expect2 = (),
  1099. warn_used = False,
  1100. non_segwit_ok = False):
  1101. if not (non_segwit_ok or self.proto.cap('segwit')):
  1102. return 'skip'
  1103. t = self.spawn(
  1104. 'mmgen-tool',
  1105. ['--bob',f'--outdir={self.tr.trash_dir}','twexport','prune=1']
  1106. + (['warn_used=1'] if warn_used else []) )
  1107. for s in expect_menu:
  1108. t.expect('prune list:\b',s)
  1109. t.expect('prune list:\b','p')
  1110. t.expect('addresses to prune: ',f'{prune_spec}\n')
  1111. for p,s in expect:
  1112. t.expect(p,s,regex=True)
  1113. t.expect('prune list:\b','q')
  1114. for p,s in expect2:
  1115. t.expect(p,s,regex=True)
  1116. if npruned:
  1117. t.expect(f'Pruned {npruned} addresses')
  1118. taddr = 35 if self.proto.cap('segwit') else 25
  1119. t.expect(f'Exporting {taddr-npruned} addresses')
  1120. t.written_to_file('JSON data')
  1121. return t
  1122. def bob_twprune_noask(self):
  1123. return self._bob_twprune(
  1124. expect_menu = 'a', # sort by amt to make address order deterministic
  1125. prune_spec = '35,12,18,3-5',
  1126. npruned = 6 )
  1127. def bob_twprune_all(self):
  1128. taddr = 35 if self.proto.cap('segwit') else 25
  1129. return self._bob_twprune(
  1130. prune_spec = f'1-{taddr}',
  1131. npruned = taddr,
  1132. expect = [('all with balance: ','P')],
  1133. non_segwit_ok = True )
  1134. def bob_twprune_skip(self):
  1135. return self._bob_twprune(
  1136. prune_spec = '',
  1137. npruned = 0,
  1138. non_segwit_ok = True )
  1139. def bob_twprune_skipamt(self):
  1140. return self._bob_twprune(
  1141. prune_spec = '1-35',
  1142. npruned = 32,
  1143. expect = [('all with balance: ','S')] )
  1144. def bob_twprune_skipused(self):
  1145. return self._bob_twprune(
  1146. prune_spec = '1-35',
  1147. npruned = 18,
  1148. expect = [('all used: ','S')],
  1149. warn_used = True )
  1150. def bob_twprune_allamt(self):
  1151. return self._bob_twprune(
  1152. prune_spec = '1-35',
  1153. npruned = 35,
  1154. expect = [('all with balance: ','P')],
  1155. expect2 = [('Warning: pruned address .* has a balance',None)] )
  1156. def bob_twprune_allused(self):
  1157. return self._bob_twprune(
  1158. prune_spec = '1-35',
  1159. npruned = 32,
  1160. expect = [('all used: ','P'),('all with balance: ','S')],
  1161. expect2 = [('Warning: pruned address .* used',None)],
  1162. warn_used = True )
  1163. @property
  1164. def _b_start(self):
  1165. """
  1166. SIDs sort non-deterministically, so we must search for start of main (not subseeds) group, i.e. ':B:1'
  1167. """
  1168. assert self.proto.cap('segwit')
  1169. if not hasattr(self,'_b_start_'):
  1170. t = self.spawn( 'mmgen-tool', ['--color=0','--bob','listaddresses'], no_msg=True )
  1171. self._b_start_ = int([e for e in t.read().split('\n') if ':B:1' in e][0].split()[0].rstrip(')'))
  1172. t.close()
  1173. return self._b_start_
  1174. def _bob_twprune_selected(self,resp,npruned):
  1175. if not self.proto.cap('segwit'):
  1176. return 'skip'
  1177. B = self._b_start
  1178. a,b,c,d,e,f = resp
  1179. return self._bob_twprune(
  1180. expect_menu = 'a', # sort by amt to make address order deterministic
  1181. prune_spec = f'31-32,{B+14},{B+9},{B}-{B+4}',
  1182. npruned = npruned,
  1183. expect = [
  1184. ('all used: ', a),
  1185. ('all used: ', b),
  1186. ('all with balance: ', c),
  1187. ('all with balance: ', d),
  1188. ('all used: ', e),
  1189. ('all used: ', f),
  1190. ],
  1191. warn_used = True )
  1192. def bob_twprune1(self):
  1193. return self._bob_twprune_selected(resp='sssssS',npruned=3)
  1194. def bob_twprune2(self):
  1195. return self._bob_twprune_selected(resp='sppPsS',npruned=3)
  1196. def bob_twprune3(self):
  1197. return self._bob_twprune_selected(resp='sssPpS',npruned=3)
  1198. def bob_twprune4(self):
  1199. return self._bob_twprune_selected(resp='sssPpP',npruned=9)
  1200. def bob_twprune5(self):
  1201. return self._bob_twprune_selected(resp='pppPpP',npruned=9)
  1202. def bob_twprune6(self):
  1203. return self._bob_twprune_selected(resp='sssSpP',npruned=7)
  1204. def bob_edit_json_twdump(self):
  1205. self.spawn('',msg_only=True)
  1206. from mmgen.tw.json import TwJSON
  1207. fn = TwJSON.Base(cfg,self.proto).dump_fn
  1208. text = json.loads(self.read_from_tmpfile(fn))
  1209. text['data']['entries'][3][3] = f'edited comment [фубар] [{gr_uc}]'
  1210. self.write_to_tmpfile( fn, json.dumps(text,indent=4) )
  1211. return 'ok'
  1212. def carol_twimport(
  1213. self,
  1214. rpc_backend = 'http',
  1215. add_parms = [],
  1216. expect_str = None,
  1217. expect_str2 = 'Found 1 unspent output'):
  1218. from mmgen.tw.json import TwJSON
  1219. fn = joinpath( self.tmpdir, TwJSON.Base(cfg,self.proto).dump_fn )
  1220. t = self.spawn(
  1221. 'mmgen-tool',
  1222. ([f'--rpc-backend={rpc_backend}'] if rpc_backend else [])
  1223. + ['--carol','twimport',fn]
  1224. + add_parms )
  1225. t.expect('(y/N): ','y')
  1226. if expect_str:
  1227. t.expect(expect_str)
  1228. elif 'batch=true' in add_parms:
  1229. t.expect('{} addresses imported'.format(10 if self.proto.coin == 'BCH' else 20))
  1230. else:
  1231. t.expect('import completed OK')
  1232. t.expect(expect_str2)
  1233. return t
  1234. def carol_twimport_nochksum(self):
  1235. return self.carol_twimport(rpc_backend=None,add_parms=['ignore_checksum=true'])
  1236. def carol_twimport_batch(self):
  1237. return self.carol_twimport(add_parms=['batch=true'])
  1238. def carol_twimport_pretty(self):
  1239. return self.carol_twimport(add_parms=['ignore_checksum=true'],expect_str='ignoring incorrect checksum')
  1240. def carol_listaddresses(self):
  1241. return self.spawn('mmgen-tool',['--carol','listaddresses','showempty=1'])
  1242. async def carol_delete_wallet(self):
  1243. imsg('Unloading Carol’s tracking wallet')
  1244. t = self.spawn('mmgen-regtest',['cli','unloadwallet','carol'])
  1245. t.ok()
  1246. from mmgen.rpc import rpc_init
  1247. rpc = await rpc_init(cfg,self.proto)
  1248. wdir = joinpath(rpc.daemon.network_datadir,'wallets','carol')
  1249. from shutil import rmtree
  1250. imsg('Deleting Carol’s tracking wallet')
  1251. rmtree(wdir)
  1252. return 'silent'
  1253. def bob_split2(self):
  1254. addrs = self.read_from_tmpfile('non-mmgen.addrs').split()
  1255. amts = (1.12345678,2.87654321,3.33443344,4.00990099,5.43214321)
  1256. outputs1 = list(map('{},{}'.format,addrs,amts))
  1257. sid = self._user_sid('bob')
  1258. l1,l2 = (
  1259. (':S',':B') if 'B' in self.proto.mmtypes else
  1260. (':S',':S') if self.proto.cap('segwit') else
  1261. (':L',':L') )
  1262. outputs2 = [sid+':C:2,6.333', sid+':L:3,6.667',sid+l1+':4,0.123',sid+l2+':5']
  1263. return self.user_txdo('bob',rtFee[5],outputs1+outputs2,'1-2')
  1264. def user_add_comment(self,user,addr,comment):
  1265. t = self.spawn('mmgen-tool',['--'+user,'add_label',addr,comment])
  1266. t.expect('Added label.*in tracking wallet',regex=True)
  1267. return t
  1268. def user_remove_comment(self,user,addr):
  1269. t = self.spawn('mmgen-tool',['--'+user,'remove_label',addr])
  1270. t.expect('Removed label.*in tracking wallet',regex=True)
  1271. return t
  1272. def bob_bad_locktime1(self):
  1273. return self._bob_bad_locktime(123456789, 'non-final', 2) # > current block height
  1274. def bob_bad_locktime2(self):
  1275. return self._bob_bad_locktime(7_000_000_000, 'invalid', 2, return_early=True) # > 4 bytes
  1276. def bob_bad_locktime3(self):
  1277. return self._bob_bad_locktime(0xffffffff, 'non-final', 2, return_early=False) # > cur time
  1278. def _bob_bad_locktime(self,locktime,expect,exit_val,return_early=False):
  1279. sid = self._user_sid('bob')
  1280. t = self.user_txdo(
  1281. user = 'bob',
  1282. fee = '20s',
  1283. outputs_cl = [self.burn_addr+',0.1', sid+':C:5'],
  1284. outputs_list = '1',
  1285. extra_args = [f'--locktime={locktime}'],
  1286. return_early = return_early,
  1287. add_comment = False,
  1288. return_after_send = True)
  1289. t.req_exit_val = exit_val
  1290. if expect:
  1291. t.expect(expect)
  1292. return t
  1293. def bob_add_comment1(self):
  1294. sid = self._user_sid('bob')
  1295. return self.user_add_comment('bob',sid+':C:1',tw_comment_lat_cyr_gr)
  1296. def alice_add_comment1(self):
  1297. sid = self._user_sid('alice')
  1298. return self.user_add_comment('alice',sid+':C:1','Original Label - 月へ')
  1299. def alice_add_comment2(self):
  1300. sid = self._user_sid('alice')
  1301. return self.user_add_comment('alice',sid+':C:1','Replacement Label')
  1302. def _user_chk_comment(self,user,addr,comment,extra_args=[]):
  1303. t = self.spawn('mmgen-tool',['--'+user,'listaddresses','all_labels=1']+extra_args)
  1304. ret = strip_ansi_escapes(t.expect_getend(addr)).strip().split(None,2)[2]
  1305. cmp_or_die( # squeezed display, double-width chars, so truncate to min field width
  1306. ret[:3].strip(),
  1307. comment[:3].strip())
  1308. return t
  1309. def alice_add_comment_coinaddr(self):
  1310. mmid = self._user_sid('alice') + (':S:1',':L:1')[self.proto.coin=='BCH']
  1311. t = self.spawn('mmgen-tool',['--alice','listaddress',mmid,'wide=true'],no_msg=True)
  1312. addr = [i for i in strip_ansi_escapes(t.read()).splitlines() if re.search(rf'\b{mmid}\b',i)][0].split()[3]
  1313. return self.user_add_comment('alice',addr,'Label added using coin address of MMGen address')
  1314. def alice_chk_comment_coinaddr(self):
  1315. mmid = self._user_sid('alice') + (':S:1',':L:1')[self.proto.coin=='BCH']
  1316. return self._user_chk_comment('alice',mmid,'Label added using coin address of MMGen address')
  1317. def alice_add_comment_badaddr(self,addr,reply,exit_val):
  1318. if os.getenv('PYTHONOPTIMIZE'):
  1319. omsg(yellow(f'PYTHONOPTIMIZE set, skipping test {self.test_name!r}'))
  1320. return 'skip'
  1321. t = self.spawn('mmgen-tool',['--alice','add_label',addr,'(none)'])
  1322. t.expect(reply,regex=True)
  1323. t.req_exit_val = exit_val
  1324. return t
  1325. def alice_add_comment_badaddr1(self):
  1326. return self.alice_add_comment_badaddr( rt_pw, 'invalid address', 2 )
  1327. def alice_add_comment_badaddr2(self):
  1328. # mainnet zero address:
  1329. addr = init_proto( cfg, self.proto.coin, network='mainnet' ).pubhash2addr(bytes(20),False)
  1330. return self.alice_add_comment_badaddr( addr, 'invalid address', 2 )
  1331. def alice_add_comment_badaddr3(self):
  1332. addr = self._user_sid('alice') + ':C:123'
  1333. return self.alice_add_comment_badaddr( addr, f'MMGen address {addr!r} not found in tracking wallet', 2 )
  1334. def alice_add_comment_badaddr4(self):
  1335. addr = self.proto.pubhash2addr(bytes(20),False) # regtest (testnet) zero address
  1336. return self.alice_add_comment_badaddr( addr, f'Coin address {addr!r} not found in tracking wallet', 2 )
  1337. def alice_remove_comment1(self):
  1338. sid = self._user_sid('alice')
  1339. mmid = sid + (':S:3',':L:3')[self.proto.coin=='BCH']
  1340. return self.user_remove_comment('alice',mmid)
  1341. def alice_chk_comment1(self):
  1342. sid = self._user_sid('alice')
  1343. return self._user_chk_comment('alice',sid+':C:1','Original Label - 月へ')
  1344. def alice_chk_comment2(self):
  1345. sid = self._user_sid('alice')
  1346. return self._user_chk_comment('alice',sid+':C:1','Replacement Label',extra_args=['age_fmt=block'])
  1347. def alice_edit_comment1(self):
  1348. return self.user_edit_comment('alice','4',tw_comment_lat_cyr_gr)
  1349. def alice_edit_comment2(self):
  1350. return self.user_edit_comment('alice','3',tw_comment_zh)
  1351. def alice_chk_comment3(self):
  1352. sid = self._user_sid('alice')
  1353. mmid = sid + (':S:3',':L:3')[self.proto.coin=='BCH']
  1354. return self._user_chk_comment('alice',mmid,tw_comment_lat_cyr_gr,extra_args=['age_fmt=date'])
  1355. def alice_chk_comment4(self):
  1356. sid = self._user_sid('alice')
  1357. mmid = sid + (':S:3',':L:3')[self.proto.coin=='BCH']
  1358. return self._user_chk_comment('alice',mmid,'-',extra_args=['age_fmt=date_time'])
  1359. def user_edit_comment(self,user,output,comment):
  1360. t = self.spawn('mmgen-txcreate',['-B','--'+user,'-i'])
  1361. t.expect(r'add \[l\]abel:.','M',regex=True)
  1362. t.expect(r'add \[l\]abel:.','l',regex=True)
  1363. t.expect(r"Enter unspent.*return to main menu\):.",output+'\n',regex=True)
  1364. t.expect(r"Enter label text.*:.",comment+'\n',regex=True)
  1365. t.expect(r'\[q\]uit menu, .*?:.','q',regex=True)
  1366. return t
  1367. def alice_listaddresses_scroll(self):
  1368. t = self.spawn(
  1369. 'mmgen-tool', [
  1370. '--alice',
  1371. '--scroll',
  1372. f'--outdir={self.tr.trash_dir}',
  1373. 'listaddresses',
  1374. 'interactive=1',
  1375. ]
  1376. )
  1377. t.expect('abel:\b','p')
  1378. ret = t.expect([ 'abel:\b', 'to confirm: ' ])
  1379. if ret == 1:
  1380. t.send('YES\n')
  1381. t.expect('abel:\b')
  1382. t.send('l')
  1383. t.expect(
  1384. 'main menu): ',
  1385. '{}\n'.format(2 if self.proto.coin == 'BCH' else 1) )
  1386. t.expect('for address.*: ','\n',regex=True)
  1387. t.expect('unchanged')
  1388. t.expect('abel:\b','q')
  1389. return t
  1390. def _alice_listaddresses_interactive(self,expect=(),expect_menu=()):
  1391. t = self.spawn('mmgen-tool',['--alice','listaddresses','interactive=1'])
  1392. for s in expect_menu:
  1393. t.expect('abel:\b',s)
  1394. for p,s in expect:
  1395. t.expect(p,s)
  1396. return t
  1397. def alice_listaddresses_empty(self):
  1398. return self._alice_listaddresses_interactive(expect_menu='uuEq')
  1399. def alice_listaddresses_menu(self):
  1400. return self._alice_listaddresses_interactive(expect_menu='aAMrDDDDLeq')
  1401. def alice_listaddresses(self,args,expect):
  1402. t = self.spawn('mmgen-tool',['--alice','listaddresses','showempty=1'] + args)
  1403. expect_str = r'\D{}\D.*\b{}'.format(*expect)
  1404. t.expect(expect_str,regex=True)
  1405. return t
  1406. def alice_listaddresses1(self):
  1407. return self.alice_listaddresses(
  1408. args = [],
  1409. expect = (rtAmts[1],r'\d+') )
  1410. def alice_listaddresses_days(self):
  1411. return self.alice_listaddresses(
  1412. args = ['age_fmt=days'],
  1413. expect = (rtAmts[1],r'\d+') )
  1414. def alice_listaddresses_date(self):
  1415. return self.alice_listaddresses(
  1416. args = ['age_fmt=date'],
  1417. expect = (rtAmts[1],pat_date) )
  1418. def alice_listaddresses_date_time(self):
  1419. return self.alice_listaddresses(
  1420. args = ['age_fmt=date_time'],
  1421. expect = (rtAmts[1],pat_date_time) )
  1422. def alice_twview(self,args,expect):
  1423. t = self.spawn('mmgen-tool',['--alice','twview'] + args)
  1424. expect_str = r'\D{}\D.*\b{}'.format(*expect)
  1425. t.expect(expect_str,regex=True)
  1426. return t
  1427. def alice_twview1(self):
  1428. return self.alice_twview(
  1429. args = [],
  1430. expect = (rtAmts[0],r'\d+') )
  1431. def alice_twview_days(self):
  1432. return self.alice_twview(
  1433. args = ['age_fmt=days'],
  1434. expect = (rtAmts[0],r'\d+') )
  1435. def alice_twview_date(self):
  1436. return self.alice_twview(
  1437. args = ['age_fmt=date'],
  1438. expect = (rtAmts[0],pat_date) )
  1439. def alice_twview_date_time(self):
  1440. return self.alice_twview(
  1441. args = ['age_fmt=date_time'],
  1442. expect = (rtAmts[0],pat_date_time) )
  1443. def alice_txcreate_info(self,pexpect_spawn=False):
  1444. t = self.spawn('mmgen-txcreate',['--alice','-Bi'],pexpect_spawn=pexpect_spawn)
  1445. pats = (
  1446. ( r'\d+', 'w'),
  1447. ( r'\d+', 'D'),
  1448. ( r'\d+', 'D'),
  1449. ( r'\d+', 'D'),
  1450. ( pat_date, 'q'),
  1451. )
  1452. for d,s in pats:
  1453. t.expect(
  1454. r'\D{}\D.*\b{}\b'.format( rtAmts[0], d ),
  1455. s,
  1456. regex=True )
  1457. if t.pexpect_spawn and s == 'w':
  1458. t.expect(r'Total.*','q',regex=True,delay=1 if cfg.exact_output else t.send_delay)
  1459. time.sleep(t.send_delay)
  1460. t.send('e')
  1461. return t
  1462. def alice_txcreate_info_term(self):
  1463. if self.skip_for_win():
  1464. return 'skip'
  1465. return self.alice_txcreate_info(pexpect_spawn=True)
  1466. # send one TX to 2 addrs in Alice’s wallet - required for alice_twview_grouped()
  1467. def bob_send_to_alice_2addr(self):
  1468. outputs_cl = self._create_tx_outputs('alice',[('C',1,',0.02'),('C',2,',0.2')])
  1469. outputs_cl += [self._user_sid('bob')+':C:5']
  1470. return self.user_txdo('bob','25s',outputs_cl,'1')
  1471. # send to a used addr in Alice’s wallet - required for alice_twview_grouped()
  1472. def bob_send_to_alice_reuse(self):
  1473. outputs_cl = self._create_tx_outputs('alice',[('C',1,',0.0111')])
  1474. outputs_cl += [self._user_sid('bob')+':C:5']
  1475. return self.user_txdo('bob','25s',outputs_cl,'1')
  1476. def alice_twview_grouped(self):
  1477. t = self.spawn('mmgen-tool',['--alice','twview','interactive=1'])
  1478. prompt = 'abel:\b'
  1479. for s,dots in (
  1480. ('o',False),
  1481. ('M',False),
  1482. ('t',True),
  1483. ('q',True),
  1484. ):
  1485. if dots:
  1486. t.expect('........')
  1487. t.expect(prompt,s)
  1488. return t
  1489. def bob_msgcreate(self):
  1490. sid1 = self._user_sid('bob')
  1491. sid2 = self._get_user_subsid('bob','29L')
  1492. return self.spawn(
  1493. 'mmgen-msg', [
  1494. '--bob',
  1495. f'--outdir={self.tmpdir}',
  1496. 'create',
  1497. '16/3/2022 Earthquake strikes Fukushima coast',
  1498. f'{sid1}:{self.dfl_mmtype}:1-4',
  1499. f'{sid2}:C:3-7,87,98'
  1500. ])
  1501. def bob_msgsign(self,wallets=[]):
  1502. fn = get_file_with_ext(self.tmpdir,'rawmsg.json')
  1503. t = self.spawn(
  1504. 'mmgen-msg', [
  1505. '--bob',
  1506. f'--outdir={self.tmpdir}',
  1507. 'sign',
  1508. fn
  1509. ] + wallets )
  1510. if not wallets:
  1511. t.passphrase(dfl_wcls.desc,rt_pw)
  1512. return t
  1513. def bob_walletconv_words(self):
  1514. t = self.spawn(
  1515. 'mmgen-walletconv', [ '--bob', f'--outdir={self.tmpdir}', '--out-fmt=words' ] )
  1516. t.passphrase(dfl_wcls.desc,rt_pw)
  1517. t.written_to_file('data')
  1518. return t
  1519. def bob_subwalletgen_bip39(self):
  1520. t = self.spawn(
  1521. 'mmgen-subwalletgen', [ '--bob', f'--outdir={self.tmpdir}', '--out-fmt=bip39', '29L' ] )
  1522. t.passphrase(dfl_wcls.desc,rt_pw)
  1523. t.written_to_file('data')
  1524. return t
  1525. def bob_msgsign_userwallet(self):
  1526. fn1 = get_file_with_ext(self.tmpdir,'mmwords')
  1527. return self.bob_msgsign([fn1])
  1528. def bob_msgsign_userwallets(self):
  1529. fn1 = get_file_with_ext(self.tmpdir,'mmwords')
  1530. fn2 = get_file_with_ext(self.tmpdir,'bip39')
  1531. return self.bob_msgsign([fn2,fn1])
  1532. def bob_msgverify(self,addr=None,ext='sigmsg.json',cmd='verify',msgfile=None):
  1533. return self.spawn(
  1534. 'mmgen-msg', [
  1535. '--bob',
  1536. f'--outdir={self.tmpdir}',
  1537. cmd,
  1538. msgfile or get_file_with_ext(self.tmpdir,ext),
  1539. ] + ([addr] if addr else []) )
  1540. def bob_msgverify_raw(self):
  1541. t = self.bob_msgverify(ext='rawmsg.json')
  1542. t.expect('No signatures')
  1543. t.req_exit_val = 1
  1544. return t
  1545. def bob_msgverify_single(self):
  1546. sid = self._user_sid('bob')
  1547. return self.bob_msgverify(addr=f'{sid}:{self.dfl_mmtype}:1')
  1548. def bob_msgexport(self,addr=None):
  1549. t = self.bob_msgverify( addr=addr, cmd='export' )
  1550. t.written_to_file('data')
  1551. return t
  1552. def bob_msgexport_single(self):
  1553. sid = self._user_sid('bob')
  1554. return self.bob_msgexport(addr=f'{sid}:{self.dfl_mmtype}:1')
  1555. def bob_msgverify_export(self):
  1556. return self.bob_msgverify(
  1557. msgfile = os.path.join(self.tmpdir,'signatures.json')
  1558. )
  1559. def bob_msgverify_export_single(self):
  1560. sid = self._user_sid('bob')
  1561. mmid = f'{sid}:{self.dfl_mmtype}:1'
  1562. args = [ '--bob', '--color=0', 'listaddress', mmid, 'wide=true' ]
  1563. imsg(f'Running mmgen-tool {fmt_list(args,fmt="bare")}')
  1564. t = self.spawn('mmgen-tool', args, no_msg=True)
  1565. addr = t.expect_getend(mmid).split()[1]
  1566. t.close()
  1567. return self.bob_msgverify(
  1568. addr = addr,
  1569. msgfile = os.path.join(self.tmpdir,'signatures.json')
  1570. )
  1571. def bob_auto_chg_split(self):
  1572. if not self.proto.cap('segwit'):
  1573. return 'skip'
  1574. sid = self._user_sid('bob')
  1575. return self.user_txdo(
  1576. user = 'bob',
  1577. fee = '23s',
  1578. outputs_cl = [sid+':C:5,0.0135', sid+':L:4'],
  1579. outputs_list = '1' )
  1580. def bob_auto_chg_generate(self):
  1581. if not self.proto.cap('segwit'):
  1582. return 'skip'
  1583. return self.generate()
  1584. def _usr_auto_chg(
  1585. self,
  1586. user,
  1587. mmtype,
  1588. idx,
  1589. by_mmtype = False,
  1590. include_dest = True,
  1591. ignore_labels = False):
  1592. if mmtype in ('S','B') and not self.proto.cap('segwit'):
  1593. return 'skip'
  1594. sid = self._user_sid('bob')
  1595. t = self.spawn(
  1596. 'mmgen-txcreate',
  1597. [f'--outdir={self.tr.trash_dir}', '--no-blank', f'--{user}'] +
  1598. (['--autochg-ignore-labels'] if ignore_labels else []) +
  1599. [mmtype if by_mmtype else f'{sid}:{mmtype}'] +
  1600. ([self.burn_addr+',0.01'] if include_dest else [])
  1601. )
  1602. return self.txcreate_ui_common(t,
  1603. menu = [],
  1604. inputs = '1',
  1605. interactive_fee = '20s',
  1606. auto_chg_addr = f'{sid}:{mmtype}:{idx}')
  1607. def bob_auto_chg1(self):
  1608. return self._usr_auto_chg( 'bob', 'C', '3' )
  1609. def bob_auto_chg2(self):
  1610. return self._usr_auto_chg( 'bob', 'B', '2' )
  1611. def bob_auto_chg3(self):
  1612. return self._usr_auto_chg( 'bob', 'S', '1' )
  1613. def bob_auto_chg4(self):
  1614. return self._usr_auto_chg( 'bob', 'C', '3', include_dest=False )
  1615. def bob_auto_chg_addrtype1(self):
  1616. return self._usr_auto_chg( 'bob', 'C', '3', True )
  1617. def bob_auto_chg_addrtype2(self):
  1618. return self._usr_auto_chg( 'bob', 'B', '2', True )
  1619. def bob_auto_chg_addrtype3(self):
  1620. return self._usr_auto_chg( 'bob', 'S', '1', True )
  1621. def bob_auto_chg_addrtype4(self):
  1622. return self._usr_auto_chg( 'bob', 'C', '3', True, include_dest=False )
  1623. def _bob_add_comment_uua(self,addrspec,comment):
  1624. sid = self._user_sid('bob')
  1625. return self.user_add_comment('bob',sid+addrspec,comment)
  1626. def bob_add_comment_uua1(self):
  1627. return self._bob_add_comment_uua(':C:3','comment for unused address')
  1628. def bob_auto_chg5(self):
  1629. return self._usr_auto_chg( 'bob', 'C', '4' )
  1630. def bob_auto_chg_addrtype5(self):
  1631. return self._usr_auto_chg( 'bob', 'C', '4', True )
  1632. def bob_auto_chg6(self):
  1633. return self._usr_auto_chg( 'bob', 'C', '3', ignore_labels=True )
  1634. def bob_auto_chg_addrtype6(self):
  1635. return self._usr_auto_chg( 'bob', 'C', '3', True, ignore_labels=True )
  1636. def _bob_remove_comment_uua(self,addrspec):
  1637. sid = self._user_sid('bob')
  1638. return self.user_remove_comment('bob',sid+addrspec)
  1639. def bob_remove_comment_uua1(self):
  1640. return self._bob_remove_comment_uua(':C:3')
  1641. def _usr_auto_chg_bad(self,user,al_id,expect):
  1642. t = self.spawn(
  1643. 'mmgen-txcreate',
  1644. ['-d',self.tr.trash_dir,'-B',f'--{user}', self.burn_addr+',0.01', al_id] )
  1645. t.req_exit_val = 2
  1646. t.expect(expect)
  1647. return t
  1648. def bob_auto_chg_bad1(self):
  1649. return self._usr_auto_chg_bad(
  1650. 'bob',
  1651. 'FFFFFFFF:C',
  1652. 'contains no addresses' )
  1653. def bob_auto_chg_bad2(self):
  1654. return self._usr_auto_chg_bad(
  1655. 'bob',
  1656. '00000000:C',
  1657. 'contains no addresses' )
  1658. def bob_auto_chg_bad3(self):
  1659. return self._usr_auto_chg_bad(
  1660. 'bob',
  1661. self._user_sid('bob') + ':L',
  1662. 'contains no unused addresses from address list' )
  1663. def bob_auto_chg_bad4(self):
  1664. return self._usr_auto_chg_bad(
  1665. 'bob',
  1666. 'L',
  1667. 'contains no unused addresses of address type' )
  1668. def carol_twimport2(self):
  1669. u,b = (4,3) if self.proto.cap('segwit') else (3,2)
  1670. return self.carol_twimport(
  1671. rpc_backend = None,
  1672. add_parms = ['ignore_checksum=true'],
  1673. expect_str2 = f'Found {u} unspent outputs in {b} blocks' )
  1674. def carol_rescan_blockchain(self):
  1675. return self._usr_rescan_blockchain('carol',[])
  1676. def carol_auto_chg1(self):
  1677. return self._usr_auto_chg( 'carol', 'C', '3' )
  1678. def carol_auto_chg2(self):
  1679. return self._usr_auto_chg( 'carol', 'B', '2' )
  1680. def carol_auto_chg3(self):
  1681. return self._usr_auto_chg( 'carol', 'S', '1' )
  1682. def carol_auto_chg_addrtype1(self):
  1683. return self._usr_auto_chg( 'carol', 'C', '3', True )
  1684. def carol_auto_chg_addrtype2(self):
  1685. return self._usr_auto_chg( 'carol', 'B', '2', True )
  1686. def carol_auto_chg_addrtype3(self):
  1687. return self._usr_auto_chg( 'carol', 'S', '1', True )
  1688. def carol_auto_chg_bad1(self):
  1689. return self._usr_auto_chg_bad(
  1690. 'carol',
  1691. self._user_sid('bob') + ':L',
  1692. 'contains no unused addresses from address list' )
  1693. def carol_auto_chg_bad2(self):
  1694. return self._usr_auto_chg_bad(
  1695. 'carol',
  1696. 'L',
  1697. 'contains no unused addresses of address type' )
  1698. def stop(self):
  1699. if cfg.no_daemon_stop:
  1700. self.spawn('',msg_only=True)
  1701. msg_r('(leaving daemon running by user request)')
  1702. return 'ok'
  1703. else:
  1704. return self.spawn('mmgen-regtest',['stop'])