ct_regtest.py 67 KB

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