ts_regtest.py 66 KB

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