test.py 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2017 Philemon <mmgen-py@yandex.com>
  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: Test suite for the MMGen suite
  20. """
  21. import sys,os,subprocess,shutil,time,re
  22. repo_root = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),os.pardir)))
  23. os.chdir(repo_root)
  24. sys.path.__setitem__(0,repo_root)
  25. # Import these _after_ local path's been added to sys.path
  26. from mmgen.common import *
  27. from mmgen.test import *
  28. from mmgen.protocol import CoinProtocol
  29. g.quiet = False # if 'quiet' was set in config file, disable here
  30. os.environ['MMGEN_QUIET'] = '0' # and for the spawned scripts
  31. log_file = 'test.py_log'
  32. hincog_fn = 'rand_data'
  33. hincog_bytes = 1024*1024
  34. hincog_offset = 98765
  35. hincog_seedlen = 256
  36. incog_id_fn = 'incog_id'
  37. non_mmgen_fn = 'coinkey'
  38. pwfile = 'passwd_file'
  39. ref_dir = os.path.join('test','ref')
  40. ref_wallet_brainpass = 'abc'
  41. ref_wallet_hash_preset = '1'
  42. ref_wallet_incog_offset = 123
  43. from mmgen.obj import MMGenTXLabel,PrivKey
  44. from mmgen.addr import AddrGenerator,KeyGenerator,AddrList,AddrData,AddrIdxList
  45. ref_tx_label = ''.join([unichr(i) for i in range(65,91) +
  46. range(1040,1072) + # cyrillic
  47. range(913,939) + # greek
  48. range(97,123)])[:MMGenTXLabel.max_len]
  49. ref_bw_hash_preset = '1'
  50. ref_bw_file = 'wallet.mmbrain'
  51. ref_bw_file_spc = 'wallet-spaced.mmbrain'
  52. ref_kafile_pass = 'kafile password'
  53. ref_kafile_hash_preset = '1'
  54. ref_enc_fn = 'sample-text.mmenc'
  55. tool_enc_passwd = "Scrypt it, don't hash it!"
  56. sample_text = \
  57. 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks\n'
  58. # Laggy flash media cause pexpect to crash, so create a temporary directory
  59. # under '/dev/shm' and put datadir and temp files here.
  60. shortopts = ''.join([e[1:] for e in sys.argv if len(e) > 1 and e[0] == '-' and e[1] != '-'])
  61. shortopts = ['-'+e for e in list(shortopts)]
  62. data_dir = os.path.join('test','data_dir')
  63. if not any(e in ('--skip-deps','--resume','-S','-r') for e in sys.argv+shortopts):
  64. if g.platform == 'win':
  65. try: os.listdir(data_dir)
  66. except: pass
  67. else:
  68. try: shutil.rmtree(data_dir)
  69. except: # we couldn't remove data dir - perhaps regtest daemon is running
  70. try: subprocess.call(['python',os.path.join('cmds','mmgen-regtest'),'stop'])
  71. except: rdie(1,'Unable to remove data dir!')
  72. else:
  73. time.sleep(2)
  74. shutil.rmtree(data_dir)
  75. os.mkdir(data_dir,0755)
  76. else:
  77. d,pfx = '/dev/shm','mmgen-test-'
  78. try:
  79. subprocess.call('rm -rf %s/%s*'%(d,pfx),shell=True)
  80. except Exception as e:
  81. die(2,'Unable to delete directory tree %s/%s* (%s)'%(d,pfx,e))
  82. try:
  83. import tempfile
  84. shm_dir = tempfile.mkdtemp('',pfx,d)
  85. except Exception as e:
  86. die(2,'Unable to create temporary directory in %s (%s)'%(d,e))
  87. dd = os.path.join(shm_dir,'data_dir')
  88. os.mkdir(dd,0755)
  89. try: os.unlink(data_dir)
  90. except: pass
  91. os.symlink(dd,data_dir)
  92. opts_data = lambda: {
  93. 'desc': 'Test suite for the MMGen suite',
  94. 'usage':'[options] [command(s) or metacommand(s)]',
  95. 'options': """
  96. -h, --help Print this help message
  97. --, --longhelp Print help message for long options (common options)
  98. -b, --buf-keypress Use buffered keypresses as with real human input
  99. -c, --print-cmdline Print the command line of each spawned command
  100. -d, --debug-scripts Turn on debugging output in executed scripts
  101. -x, --debug-pexpect Produce debugging output for pexpect calls
  102. -D, --direct-exec Bypass pexpect and execute a command directly (for
  103. debugging only)
  104. -e, --exact-output Show the exact output of the MMGen script(s) being run
  105. -g, --segwit Generate and use Segwit addresses
  106. -G, --segwit-random Generate and use a random mix of Segwit and Legacy addrs
  107. -l, --list-cmds List and describe the commands in the test suite
  108. -L, --log Log commands to file {lf}
  109. -n, --names Display command names instead of descriptions
  110. -O, --popen-spawn Use pexpect's popen_spawn instead of popen (always true, so ignored)
  111. -p, --pause Pause between tests, resuming on keypress
  112. -P, --profile Record the execution time of each script
  113. -q, --quiet Produce minimal output. Suppress dependency info
  114. -r, --resume=c Resume at command 'c' after interrupted run
  115. -s, --system Test scripts and modules installed on system rather
  116. than those in the repo root
  117. -S, --skip-deps Skip dependency checking for command
  118. -u, --usr-random Get random data interactively from user
  119. -t, --traceback Run the command inside the '{tbc}' script
  120. -v, --verbose Produce more verbose output
  121. -W, --no-dw-delete Don't remove default wallet from data dir after dw tests are done
  122. """.format(tbc=g.traceback_cmd,lf=log_file),
  123. 'notes': """
  124. If no command is given, the whole suite of tests is run.
  125. """
  126. }
  127. sys.argv = [sys.argv[0]] + ['--data-dir',data_dir] + sys.argv[1:]
  128. cmd_args = opts.init(opts_data)
  129. opt.popen_spawn = True # popen has issues, so use popen_spawn always
  130. ref_subdir = '' if g.proto.base_coin == 'BTC' else g.proto.name
  131. altcoin_pfx = '' if g.proto.base_coin == 'BTC' else '-'+g.proto.base_coin
  132. tn_ext = ('','.testnet')[g.testnet]
  133. fork = {'bch':'btc','btc':'btc','ltc':'ltc'}[g.coin.lower()]
  134. tx_fee = {'btc':'0.0001','bch':'0.001','ltc':'0.01'}[g.coin.lower()]
  135. txbump_fee = {'btc':'123s','bch':'567s','ltc':'12345s'}[g.coin.lower()]
  136. rtFundAmt = {'btc':'500','bch':'500','ltc':'5500'}[g.coin.lower()]
  137. rtFee = {
  138. 'btc': ('20s','10s','60s','0.0001','10s','20s'),
  139. 'bch': ('20s','10s','60s','0.0001','10s','20s'),
  140. 'ltc': ('1000s','500s','1500s','0.05','400s','1000s')
  141. }[g.coin.lower()]
  142. rtBals = {
  143. 'btc': ('499.999942','399.9998214','399.9998079','399.9996799','13.00000000','986.99957990','999.99957990'),
  144. 'bch': ('499.9999416','399.9999124','399.99989','399.9997616','276.22339397','723.77626763','999.99966160'),
  145. 'ltc': ('5499.9971','5399.994085','5399.993545','5399.987145','13.00000000','10986.93714500','10999.93714500'),
  146. }[g.coin.lower()]
  147. rtBobOp3 = {'btc':'S:2','bch':'L:3','ltc':'S:2'}[g.coin.lower()]
  148. if opt.segwit and 'S' not in g.proto.mmtypes:
  149. die(1,'--segwit option incompatible with {}'.format(g.proto.__name__))
  150. def randbool():
  151. return hexlify(os.urandom(1))[1] in '12345678'
  152. def get_segwit_val():
  153. return randbool() if opt.segwit_random else True if opt.segwit else False
  154. cfgs = {
  155. '15': {
  156. 'tmpdir': os.path.join('test','tmp15'),
  157. 'wpasswd': 'Dorian',
  158. 'kapasswd': 'Grok the blockchain',
  159. 'addr_idx_list': '12,99,5-10,5,12', # 8 addresses
  160. 'dep_generators': {
  161. pwfile: 'walletgen_dfl_wallet',
  162. 'addrs': 'addrgen_dfl_wallet',
  163. 'rawtx': 'txcreate_dfl_wallet',
  164. 'sigtx': 'txsign_dfl_wallet',
  165. 'mmseed': 'export_seed_dfl_wallet',
  166. 'del_dw_run': 'delete_dfl_wallet',
  167. },
  168. 'segwit': get_segwit_val()
  169. },
  170. '16': {
  171. 'tmpdir': os.path.join('test','tmp16'),
  172. 'wpasswd': 'My changed password',
  173. 'hash_preset': '2',
  174. 'dep_generators': {
  175. pwfile: 'passchg_dfl_wallet',
  176. },
  177. 'segwit': get_segwit_val()
  178. },
  179. '17': {
  180. 'tmpdir': os.path.join('test','tmp17'),
  181. },
  182. '1': {
  183. 'tmpdir': os.path.join('test','tmp1'),
  184. 'wpasswd': 'Dorian',
  185. 'kapasswd': 'Grok the blockchain',
  186. 'addr_idx_list': '12,99,5-10,5,12', # 8 addresses
  187. 'dep_generators': {
  188. pwfile: 'walletgen',
  189. 'mmdat': 'walletgen',
  190. 'addrs': 'addrgen',
  191. 'rawtx': 'txcreate',
  192. 'txbump': 'txbump',
  193. 'sigtx': 'txsign',
  194. 'mmwords': 'export_mnemonic',
  195. 'mmseed': 'export_seed',
  196. 'mmhex': 'export_hex',
  197. 'mmincog': 'export_incog',
  198. 'mmincox': 'export_incog_hex',
  199. hincog_fn: 'export_incog_hidden',
  200. incog_id_fn: 'export_incog_hidden',
  201. 'akeys.mmenc': 'keyaddrgen'
  202. },
  203. 'segwit': get_segwit_val()
  204. },
  205. '2': {
  206. 'tmpdir': os.path.join('test','tmp2'),
  207. 'wpasswd': 'Hodling away',
  208. 'addr_idx_list': '37,45,3-6,22-23', # 8 addresses
  209. 'seed_len': 128,
  210. 'dep_generators': {
  211. 'mmdat': 'walletgen2',
  212. 'addrs': 'addrgen2',
  213. 'rawtx': 'txcreate2',
  214. 'sigtx': 'txsign2',
  215. 'mmwords': 'export_mnemonic2',
  216. },
  217. 'segwit': get_segwit_val()
  218. },
  219. '3': {
  220. 'tmpdir': os.path.join('test','tmp3'),
  221. 'wpasswd': 'Major miner',
  222. 'addr_idx_list': '73,54,1022-1023,2-5', # 8 addresses
  223. 'dep_generators': {
  224. 'mmdat': 'walletgen3',
  225. 'addrs': 'addrgen3',
  226. 'rawtx': 'txcreate3',
  227. 'sigtx': 'txsign3'
  228. },
  229. 'segwit': get_segwit_val()
  230. },
  231. '4': {
  232. 'tmpdir': os.path.join('test','tmp4'),
  233. 'wpasswd': 'Hashrate good',
  234. 'addr_idx_list': '63,1004,542-544,7-9', # 8 addresses
  235. 'seed_len': 192,
  236. 'dep_generators': {
  237. 'mmdat': 'walletgen4',
  238. 'mmbrain': 'walletgen4',
  239. 'addrs': 'addrgen4',
  240. 'rawtx': 'txcreate4',
  241. 'sigtx': 'txsign4',
  242. 'txdo': 'txdo4',
  243. },
  244. 'bw_filename': 'brainwallet.mmbrain',
  245. 'bw_params': '192,1',
  246. 'segwit': get_segwit_val()
  247. },
  248. '14': {
  249. 'kapasswd': 'Maxwell',
  250. 'tmpdir': os.path.join('test','tmp14'),
  251. 'wpasswd': 'The Halving',
  252. 'addr_idx_list': '61,998,502-504,7-9', # 8 addresses
  253. 'seed_len': 256,
  254. 'dep_generators': {
  255. 'mmdat': 'walletgen14',
  256. 'addrs': 'addrgen14',
  257. 'akeys.mmenc': 'keyaddrgen14',
  258. },
  259. 'segwit': get_segwit_val()
  260. },
  261. '5': {
  262. 'tmpdir': os.path.join('test','tmp5'),
  263. 'wpasswd': 'My changed password',
  264. 'hash_preset': '2',
  265. 'dep_generators': {
  266. 'mmdat': 'passchg',
  267. pwfile: 'passchg',
  268. },
  269. 'segwit': get_segwit_val()
  270. },
  271. '6': {
  272. 'name': 'reference wallet check (128-bit)',
  273. 'seed_len': 128,
  274. 'seed_id': 'FE3C6545',
  275. 'ref_bw_seed_id': '33F10310',
  276. 'addrfile_chk': {
  277. 'btc': ('B230 7526 638F 38CB','B64D 7327 EF2A 60FE'),
  278. 'ltc': ('2B23 5E97 848A B961','928D 3CB6 78FF 9829'),
  279. },
  280. 'addrfile_segwit_chk': {
  281. 'btc': ('9914 6D10 2307 F348','7DBF 441F E188 8B37'),
  282. 'ltc': ('CC09 A190 B7DF B7CD','3676 4C49 14F8 1AD0'),
  283. },
  284. 'addrfile_compressed_chk': {
  285. 'btc': ('95EB 8CC0 7B3B 7856','629D FDE4 CDC0 F276'),
  286. 'ltc': ('35D5 8ECA 9A42 46C3','37E9 A36E 94A2 010F'),
  287. },
  288. 'keyaddrfile_chk': {
  289. 'btc': ('CF83 32FB 8A8B 08E2','FEBF 7878 97BB CC35'),
  290. 'ltc': ('1896 A26C 7F14 2D01','B41D BA63 0605 DD66'),
  291. },
  292. 'keyaddrfile_segwit_chk': {
  293. 'btc': ('C13B F717 D4E8 CF59','4DB5 BAF0 45B7 6E81'),
  294. 'ltc': ('054B 9794 55B4 5D82','C373 0074 DEE6 B70A'),
  295. },
  296. 'keyaddrfile_compressed_chk': {
  297. 'btc': ('E43A FA46 5751 720A','B995 A6CF D1CD FAD0'),
  298. 'ltc': ('7603 2FE3 2145 FFAD','3248 356A C707 4A41'),
  299. },
  300. 'passfile_chk': 'EB29 DC4F 924B 289F',
  301. 'passfile32_chk': '37B6 C218 2ABC 7508',
  302. 'wpasswd': 'reference password',
  303. 'ref_wallet': 'FE3C6545-D782B529[128,1].mmdat',
  304. 'ic_wallet': 'FE3C6545-E29303EA-5E229E30[128,1].mmincog',
  305. 'ic_wallet_hex': 'FE3C6545-BC4BE3F2-32586837[128,1].mmincox',
  306. 'hic_wallet': 'FE3C6545-161E495F-BEB7548E[128,1].incog-offset123',
  307. 'hic_wallet_old': 'FE3C6545-161E495F-9860A85B[128,1].incog-old.offset123',
  308. 'tmpdir': os.path.join('test','tmp6'),
  309. 'kapasswd': '',
  310. 'addr_idx_list': '1010,500-501,31-33,1,33,500,1011', # 8 addresses
  311. 'pass_idx_list': '1,4,9-11,1100',
  312. 'dep_generators': {
  313. 'mmdat': 'refwalletgen1',
  314. pwfile: 'refwalletgen1',
  315. 'addrs': 'refaddrgen1',
  316. 'akeys.mmenc': 'refkeyaddrgen1'
  317. },
  318. 'segwit': get_segwit_val()
  319. },
  320. '7': {
  321. 'name': 'reference wallet check (192-bit)',
  322. 'seed_len': 192,
  323. 'seed_id': '1378FC64',
  324. 'ref_bw_seed_id': 'CE918388',
  325. 'addrfile_chk': {
  326. 'btc': ('8C17 A5FA 0470 6E89','0A59 C8CD 9439 8B81'),
  327. 'ltc': ('2B77 A009 D5D0 22AD','FCEC 0032 9EF9 B201'),
  328. },
  329. 'addrfile_segwit_chk': {
  330. 'btc': ('91C4 0414 89E4 2089','3BA6 7494 8E2B 858D'),
  331. 'ltc': ('8F12 FA7B 9F12 594C','E79E F55B 1536 56F2'),
  332. },
  333. 'addrfile_compressed_chk': {
  334. 'btc': ('2615 8401 2E98 7ECA','DF38 22AB AAB0 124E'),
  335. 'ltc': ('197C C48C 3C37 AB0F','5072 15DA 1A90 5E99'),
  336. },
  337. 'keyaddrfile_chk': {
  338. 'btc': ('9648 5132 B98E 3AD9','2F72 C83F 44C5 0FAC'),
  339. 'ltc': ('DBD4 FAB6 7E46 CD07','1DA9 C245 F669 670C'),
  340. },
  341. 'keyaddrfile_segwit_chk': {
  342. 'btc': ('C98B DF08 A3D5 204B','25F2 AEB6 AAAC 8BBE'),
  343. 'ltc': ('1829 7FE7 2567 CB91','1305 9007 E515 B66A'),
  344. },
  345. 'keyaddrfile_compressed_chk': {
  346. 'btc': ('6D6D 3D35 04FD B9C3','B345 9CD8 9EAE 5489'),
  347. 'ltc': ('F5DA 9D60 6798 C4E9','F928 113B C9D7 9DF5'),
  348. },
  349. 'passfile_chk': 'ADEA 0083 094D 489A',
  350. 'passfile32_chk': '2A28 C5C7 36EC 217A',
  351. 'wpasswd': 'reference password',
  352. 'ref_wallet': '1378FC64-6F0F9BB4[192,1].mmdat',
  353. 'ic_wallet': '1378FC64-2907DE97-F980D21F[192,1].mmincog',
  354. 'ic_wallet_hex': '1378FC64-4DCB5174-872806A7[192,1].mmincox',
  355. 'hic_wallet': '1378FC64-B55E9958-77256FC1[192,1].incog.offset123',
  356. 'hic_wallet_old': '1378FC64-B55E9958-D85FF20C[192,1].incog-old.offset123',
  357. 'tmpdir': os.path.join('test','tmp7'),
  358. 'kapasswd': '',
  359. 'addr_idx_list': '1010,500-501,31-33,1,33,500,1011', # 8 addresses
  360. 'pass_idx_list': '1,4,9-11,1100',
  361. 'dep_generators': {
  362. 'mmdat': 'refwalletgen2',
  363. pwfile: 'refwalletgen2',
  364. 'addrs': 'refaddrgen2',
  365. 'akeys.mmenc': 'refkeyaddrgen2'
  366. },
  367. 'segwit': get_segwit_val()
  368. },
  369. '8': {
  370. 'name': 'reference wallet check (256-bit)',
  371. 'seed_len': 256,
  372. 'seed_id': '98831F3A',
  373. 'ref_bw_seed_id': 'B48CD7FC',
  374. 'addrfile_chk': {
  375. 'btc': ('6FEF 6FB9 7B13 5D91','3C2C 8558 BB54 079E'),
  376. 'ltc': ('AD52 C3FE 8924 AAF0','5738 5C4F 167C F9AE'),
  377. },
  378. 'addrfile_segwit_chk': {
  379. 'btc': ('06C1 9C87 F25C 4EE6','58D1 7B6C E9F9 9C14'),
  380. 'ltc': ('63DF E42A 0827 21C3','1A3F 3016 2E2B F33A'),
  381. },
  382. 'addrfile_compressed_chk': {
  383. 'btc': ('A33C 4FDE F515 F5BC','5186 02C2 535E B7D5'),
  384. 'ltc': ('3FC0 8F03 C2D6 BD19','535E 5CDC 1CA7 08D5'),
  385. },
  386. 'keyaddrfile_chk': {
  387. 'btc': ('9F2D D781 1812 8BAD','7410 8F95 4B33 B4B2'),
  388. 'ltc': ('B804 978A 8796 3ED4','93A6 844C 8ECC BEF4'),
  389. },
  390. 'keyaddrfile_segwit_chk': {
  391. 'btc': ('A447 12C2 DD14 5A9B','0690 460D A600 D315'),
  392. 'ltc': ('E8A3 9F6E E164 A521','70ED 8557 5882 08A5'),
  393. },
  394. 'keyaddrfile_compressed_chk': {
  395. 'btc': ('420A 8EB5 A9E2 7814','3243 DD92 809E FE8D'),
  396. 'ltc': ('8D1C 781F EB7F 44BC','678E 8EF9 1396 B140'),
  397. },
  398. 'passfile_chk': '2D6D 8FBA 422E 1315',
  399. 'passfile32_chk': 'F6C1 CDFB 97D9 FCAE',
  400. 'wpasswd': 'reference password',
  401. 'ref_wallet': '98831F3A-{}[256,1].mmdat'.format(('27F2BF93','E2687906')[g.testnet]),
  402. 'ref_addrfile': '98831F3A{}[1,31-33,500-501,1010-1011]{}.addrs'.format(altcoin_pfx,tn_ext),
  403. 'ref_segwitaddrfile':'98831F3A{}-S[1,31-33,500-501,1010-1011]{}.addrs'.format(altcoin_pfx,tn_ext),
  404. 'ref_keyaddrfile': '98831F3A{}[1,31-33,500-501,1010-1011]{}.akeys.mmenc'.format(altcoin_pfx,tn_ext),
  405. 'ref_passwdfile': '98831F3A-фубар@crypto.org-b58-20[1,4,9-11,1100].pws',
  406. 'ref_addrfile_chksum': {
  407. 'btc': ('6FEF 6FB9 7B13 5D91','3C2C 8558 BB54 079E'),
  408. 'ltc': ('AD52 C3FE 8924 AAF0','5738 5C4F 167C F9AE'),
  409. },
  410. 'ref_segwitaddrfile_chksum': {
  411. 'btc': ('06C1 9C87 F25C 4EE6','58D1 7B6C E9F9 9C14'),
  412. 'ltc': ('63DF E42A 0827 21C3','1A3F 3016 2E2B F33A'),
  413. },
  414. 'ref_keyaddrfile_chksum': {
  415. 'btc': ('9F2D D781 1812 8BAD','7410 8F95 4B33 B4B2'),
  416. 'ltc': ('B804 978A 8796 3ED4','93A6 844C 8ECC BEF4'),
  417. },
  418. 'ref_passwdfile_chksum': 'A983 DAB9 5514 27FB',
  419. # 'ref_fake_unspent_data':'98831F3A_unspent.json',
  420. 'ref_tx_file': {
  421. 'btc': 'FFB367[1.234]{}.rawtx',
  422. 'bch': '99BE60-BCH[106.6789]{}.rawtx',
  423. 'ltc': '75F455-LTC[106.6789]{}.rawtx',
  424. },
  425. 'ic_wallet': '98831F3A-5482381C-18460FB1[256,1].mmincog',
  426. 'ic_wallet_hex': '98831F3A-1630A9F2-870376A9[256,1].mmincox',
  427. 'hic_wallet': '98831F3A-F59B07A0-559CEF19[256,1].incog.offset123',
  428. 'hic_wallet_old': '98831F3A-F59B07A0-848535F3[256,1].incog-old.offset123',
  429. 'tmpdir': os.path.join('test','tmp8'),
  430. 'kapasswd': '',
  431. 'addr_idx_list': '1010,500-501,31-33,1,33,500,1011', # 8 addresses
  432. 'pass_idx_list': '1,4,9-11,1100',
  433. 'dep_generators': {
  434. 'mmdat': 'refwalletgen3',
  435. pwfile: 'refwalletgen3',
  436. 'addrs': 'refaddrgen3',
  437. 'akeys.mmenc': 'refkeyaddrgen3'
  438. },
  439. 'segwit': get_segwit_val()
  440. },
  441. '9': {
  442. 'tmpdir': os.path.join('test','tmp9'),
  443. 'tool_enc_infn': 'tool_encrypt.in',
  444. # 'tool_enc_ref_infn': 'tool_encrypt_ref.in',
  445. 'wpasswd': 'reference password',
  446. 'dep_generators': {
  447. 'tool_encrypt.in': 'tool_encrypt',
  448. 'tool_encrypt.in.mmenc': 'tool_encrypt',
  449. # 'tool_encrypt_ref.in': 'tool_encrypt_ref',
  450. # 'tool_encrypt_ref.in.mmenc': 'tool_encrypt_ref',
  451. },
  452. },
  453. }
  454. from copy import deepcopy
  455. for a,b in (('6','11'),('7','12'),('8','13')):
  456. cfgs[b] = deepcopy(cfgs[a])
  457. cfgs[b]['tmpdir'] = os.path.join('test','tmp'+b)
  458. from collections import OrderedDict
  459. cmd_group = OrderedDict()
  460. cmd_group['help'] = OrderedDict([
  461. # test description depends
  462. ['helpscreens', (1,'help screens', [],1)],
  463. ['longhelpscreens', (1,'help screens (--longhelp)',[],1)],
  464. ])
  465. cmd_group['dfl_wallet'] = OrderedDict([
  466. ['walletgen_dfl_wallet', (15,'wallet generation (default wallet)',[[[],15]],1)],
  467. ['export_seed_dfl_wallet',(15,'seed export to mmseed format (default wallet)',[[[pwfile],15]],1)],
  468. ['addrgen_dfl_wallet',(15,'address generation (default wallet)',[[[pwfile],15]],1)],
  469. ['txcreate_dfl_wallet',(15,'transaction creation (default wallet)',[[['addrs'],15]],1)],
  470. ['txsign_dfl_wallet',(15,'transaction signing (default wallet)',[[['rawtx',pwfile],15]],1)],
  471. ['passchg_dfl_wallet',(16,'password, label and hash preset change (default wallet)',[[[pwfile],15]],1)],
  472. ['walletchk_newpass_dfl_wallet',(16,'wallet check with new pw, label and hash preset',[[[pwfile],16]],1)],
  473. ['delete_dfl_wallet',(15,'delete default wallet',[[[pwfile],15]],1)],
  474. ])
  475. cmd_group['main'] = OrderedDict([
  476. ['walletgen', (1,'wallet generation', [[['del_dw_run'],15]],1)],
  477. # ['walletchk', (1,'wallet check', [[['mmdat'],1]])],
  478. ['passchg', (5,'password, label and hash preset change',[[['mmdat',pwfile],1]],1)],
  479. ['walletchk_newpass',(5,'wallet check with new pw, label and hash preset',[[['mmdat',pwfile],5]],1)],
  480. ['addrgen', (1,'address generation', [[['mmdat',pwfile],1]],1)],
  481. ['addrimport', (1,'address import', [[['addrs'],1]],1)],
  482. ['txcreate', (1,'transaction creation', [[['addrs'],1]],1)],
  483. ['txbump', (1,'transaction fee bumping (no send)',[[['rawtx'],1]],1)],
  484. ['txsign', (1,'transaction signing', [[['mmdat','rawtx',pwfile,'txbump'],1]],1)],
  485. ['txsend', (1,'transaction sending', [[['sigtx'],1]])],
  486. # txdo must go after txsign
  487. ['txdo', (1,'online transaction', [[['sigtx','mmdat'],1]])],
  488. ['export_hex', (1,'seed export to hexadecimal format', [[['mmdat'],1]])],
  489. ['export_seed', (1,'seed export to mmseed format', [[['mmdat'],1]])],
  490. ['export_mnemonic', (1,'seed export to mmwords format', [[['mmdat'],1]])],
  491. ['export_incog', (1,'seed export to mmincog format', [[['mmdat'],1]])],
  492. ['export_incog_hex',(1,'seed export to mmincog hex format', [[['mmdat'],1]])],
  493. ['export_incog_hidden',(1,'seed export to hidden mmincog format', [[['mmdat'],1]])],
  494. ['addrgen_hex', (1,'address generation from mmhex file', [[['mmhex','addrs'],1]])],
  495. ['addrgen_seed', (1,'address generation from mmseed file', [[['mmseed','addrs'],1]])],
  496. ['addrgen_mnemonic',(1,'address generation from mmwords file',[[['mmwords','addrs'],1]])],
  497. ['addrgen_incog', (1,'address generation from mmincog file',[[['mmincog','addrs'],1]])],
  498. ['addrgen_incog_hex',(1,'address generation from mmincog hex file',[[['mmincox','addrs'],1]])],
  499. ['addrgen_incog_hidden',(1,'address generation from hidden mmincog file', [[[hincog_fn,'addrs'],1]])],
  500. ['keyaddrgen', (1,'key-address file generation', [[['mmdat',pwfile],1]])],
  501. ['txsign_keyaddr',(1,'transaction signing with key-address file', [[['akeys.mmenc','rawtx'],1]])],
  502. ['walletgen2',(2,'wallet generation (2), 128-bit seed', [[['del_dw_run'],15]])],
  503. ['addrgen2', (2,'address generation (2)', [[['mmdat'],2]])],
  504. ['txcreate2', (2,'transaction creation (2)', [[['addrs'],2]])],
  505. ['txsign2', (2,'transaction signing, two transactions',[[['mmdat','rawtx'],1],[['mmdat','rawtx'],2]])],
  506. ['export_mnemonic2', (2,'seed export to mmwords format (2)',[[['mmdat'],2]])],
  507. ['walletgen3',(3,'wallet generation (3)', [[['del_dw_run'],15]])],
  508. ['addrgen3', (3,'address generation (3)', [[['mmdat'],3]])],
  509. ['txcreate3', (3,'tx creation with inputs and outputs from two wallets', [[['addrs'],1],[['addrs'],3]])],
  510. ['txsign3', (3,'tx signing with inputs and outputs from two wallets',[[['mmdat'],1],[['mmdat','rawtx'],3]])],
  511. ['walletgen14', (14,'wallet generation (14)', [[['del_dw_run'],15]],14)],
  512. ['addrgen14', (14,'address generation (14)', [[['mmdat'],14]])],
  513. ['keyaddrgen14',(14,'key-address file generation (14)', [[['mmdat'],14]],14)],
  514. ['walletgen4',(4,'wallet generation (4) (brainwallet)', [[['del_dw_run'],15]])],
  515. ['addrgen4', (4,'address generation (4)', [[['mmdat'],4]])],
  516. ['txcreate4', (4,'tx creation with inputs and outputs from four seed sources, key-address file and non-MMGen inputs and outputs', [[['addrs'],1],[['addrs'],2],[['addrs'],3],[['addrs'],4],[['addrs','akeys.mmenc'],14]])],
  517. ['txsign4', (4,'tx signing with inputs and outputs from incog file, mnemonic file, wallet, brainwallet, key-address file and non-MMGen inputs and outputs', [[['mmincog'],1],[['mmwords'],2],[['mmdat'],3],[['mmbrain','rawtx'],4],[['akeys.mmenc'],14]])],
  518. ['txdo4', (4,'tx creation,signing and sending with inputs and outputs from four seed sources, key-address file and non-MMGen inputs and outputs', [[['addrs'],1],[['addrs'],2],[['addrs'],3],[['addrs'],4],[['addrs','akeys.mmenc'],14],[['mmincog'],1],[['mmwords'],2],[['mmdat'],3],[['mmbrain','rawtx'],4],[['akeys.mmenc'],14]])], # must go after txsign4
  519. ['txbump4', (4,'tx fee bump + send with inputs and outputs from four seed sources, key-address file and non-MMGen inputs and outputs', [[['akeys.mmenc'],14],[['mmincog'],1],[['mmwords'],2],[['mmdat'],3],[['akeys.mmenc'],14],[['mmbrain','sigtx','mmdat','txdo'],4]])], # must go after txsign4
  520. ])
  521. cmd_group['tool'] = OrderedDict([
  522. ['tool_encrypt', (9,"'mmgen-tool encrypt' (random data)", [],1)],
  523. ['tool_decrypt', (9,"'mmgen-tool decrypt' (random data)", [[[cfgs['9']['tool_enc_infn'],cfgs['9']['tool_enc_infn']+'.mmenc'],9]],1)],
  524. # ['tool_encrypt_ref', (9,"'mmgen-tool encrypt' (reference text)", [])],
  525. ['tool_find_incog_data', (9,"'mmgen-tool find_incog_data'", [[[hincog_fn],1],[[incog_id_fn],1]])],
  526. # ['pywallet', (9,"'mmgen-pywallet'", [],1)],
  527. ])
  528. # saved reference data
  529. cmd_group['ref'] = (
  530. # reading
  531. ('ref_wallet_chk', ([],'saved reference wallet')),
  532. ('ref_seed_chk', ([],'saved seed file')),
  533. ('ref_hex_chk', ([],'saved mmhex file')),
  534. ('ref_mn_chk', ([],'saved mnemonic file')),
  535. ('ref_hincog_chk', ([],'saved hidden incog reference wallet')),
  536. ('ref_brain_chk', ([],'saved brainwallet')),
  537. # generating new reference ('abc' brainwallet) files:
  538. ('refwalletgen', ([],'gen new refwallet')),
  539. ('refaddrgen', (['mmdat',pwfile],'new refwallet addr chksum')),
  540. ('refkeyaddrgen', (['mmdat',pwfile],'new refwallet key-addr chksum')),
  541. ('refaddrgen_compressed', (['mmdat',pwfile],'new refwallet addr chksum (compressed)')),
  542. ('refkeyaddrgen_compressed', (['mmdat',pwfile],'new refwallet key-addr chksum (compressed)')),
  543. ('refpasswdgen', (['mmdat',pwfile],'new refwallet passwd file chksum')),
  544. ('ref_b32passwdgen',(['mmdat',pwfile],'new refwallet passwd file chksum (base32)')),
  545. )
  546. # misc. saved reference data
  547. cmd_group['ref_other'] = (
  548. ('ref_addrfile_chk', 'saved reference address file'),
  549. ('ref_segwitaddrfile_chk','saved reference address file (segwit)'),
  550. ('ref_keyaddrfile_chk','saved reference key-address file'),
  551. ('ref_passwdfile_chk', 'saved reference password file'),
  552. # Create the fake inputs:
  553. # ('txcreate8', 'transaction creation (8)'),
  554. ('ref_tx_chk', 'saved reference tx file'),
  555. ('ref_brain_chk_spc3', 'saved brainwallet (non-standard spacing)'),
  556. ('ref_tool_decrypt', 'decryption of saved MMGen-encrypted file'),
  557. )
  558. # mmgen-walletconv:
  559. cmd_group['conv_in'] = ( # reading
  560. ('ref_wallet_conv', 'conversion of saved reference wallet'),
  561. ('ref_mn_conv', 'conversion of saved mnemonic'),
  562. ('ref_seed_conv', 'conversion of saved seed file'),
  563. ('ref_hex_conv', 'conversion of saved hexadecimal seed file'),
  564. ('ref_brain_conv', 'conversion of ref brainwallet'),
  565. ('ref_incog_conv', 'conversion of saved incog wallet'),
  566. ('ref_incox_conv', 'conversion of saved hex incog wallet'),
  567. ('ref_hincog_conv', 'conversion of saved hidden incog wallet'),
  568. ('ref_hincog_conv_old','conversion of saved hidden incog wallet (old format)')
  569. )
  570. cmd_group['conv_out'] = ( # writing
  571. ('ref_wallet_conv_out', 'ref seed conversion to wallet'),
  572. ('ref_mn_conv_out', 'ref seed conversion to mnemonic'),
  573. ('ref_hex_conv_out', 'ref seed conversion to hex seed'),
  574. ('ref_seed_conv_out', 'ref seed conversion to seed'),
  575. ('ref_incog_conv_out', 'ref seed conversion to incog data'),
  576. ('ref_incox_conv_out', 'ref seed conversion to hex incog data'),
  577. ('ref_hincog_conv_out', 'ref seed conversion to hidden incog data')
  578. )
  579. cmd_group['regtest'] = (
  580. ('regtest_setup', 'regtest (Bob and Alice) mode setup'),
  581. ('regtest_walletgen_bob', 'wallet generation (Bob)'),
  582. ('regtest_walletgen_alice', 'wallet generation (Alice)'),
  583. ('regtest_addrgen_bob', 'address generation (Bob)'),
  584. ('regtest_addrgen_alice', 'address generation (Alice)'),
  585. ('regtest_addrimport_bob', "importing Bob's addresses"),
  586. ('regtest_addrimport_alice', "importing Alice's addresses"),
  587. ('regtest_fund_bob', "funding Bob's wallet"),
  588. ('regtest_fund_alice', "funding Alice's wallet"),
  589. ('regtest_bob_bal1', "Bob's balance"),
  590. ('regtest_bob_split1', "splitting Bob's funds"),
  591. ('regtest_generate', 'mining a block'),
  592. ('regtest_bob_bal2', "Bob's balance"),
  593. ('regtest_bob_rbf_send', 'sending funds to Alice (RBF)'),
  594. ('regtest_get_mempool1', 'mempool (before RBF bump)'),
  595. ('regtest_bob_rbf_bump', 'bumping RBF transaction'),
  596. ('regtest_get_mempool2', 'mempool (after RBF bump)'),
  597. ('regtest_generate', 'mining a block'),
  598. ('regtest_bob_bal3', "Bob's balance"),
  599. ('regtest_bob_pre_import', 'sending to non-imported address'),
  600. ('regtest_generate', 'mining a block'),
  601. ('regtest_bob_import_addr', 'importing non-MMGen address with --rescan'),
  602. ('regtest_bob_bal4', "Bob's balance (after import with rescan)"),
  603. ('regtest_bob_import_list', 'importing flat address list'),
  604. ('regtest_bob_split2', "splitting Bob's funds"),
  605. ('regtest_generate', 'mining a block'),
  606. ('regtest_bob_bal5', "Bob's balance"),
  607. ('regtest_bob_send_non_mmgen', 'sending funds to Alice (from non-MMGen addrs)'),
  608. ('regtest_generate', 'mining a block'),
  609. ('regtest_bob_alice_bal', "Bob and Alice's balances"),
  610. ('regtest_alice_add_label1', 'adding a label'),
  611. ('regtest_alice_chk_label1', 'the label'),
  612. ('regtest_alice_add_label2', 'adding a label'),
  613. ('regtest_alice_chk_label2', 'the label'),
  614. ('regtest_alice_edit_label1', 'editing a label'),
  615. ('regtest_alice_chk_label3', 'the label'),
  616. ('regtest_alice_remove_label1','removing a label'),
  617. ('regtest_alice_chk_label4', 'the label'),
  618. ('regtest_stop', 'stopping regtest daemon'),
  619. )
  620. # undocumented admin cmds
  621. cmd_group_admin = OrderedDict()
  622. cmd_group_admin['create_ref_tx'] = (
  623. ('ref_tx_setup', 'regtest (Bob and Alice) mode setup'),
  624. ('ref_tx_addrgen_bob_ref_wallet', 'address generation (Bob - reference wallet)'),
  625. ('ref_tx_addrimport_bob_ref_wallet', "importing Bob's addresses (reference wallet)"),
  626. ('ref_tx_fund_bob', "funding Bob's wallet (reference wallet)"),
  627. ('ref_tx_bob_split', "splitting Bob's funds (reference wallet)"),
  628. ('ref_tx_generate', 'mining a block'),
  629. ('ref_tx_bob_create_tx', "creating reference transaction"),
  630. ('ref_tx_bob_modify_tx', "modifying reference transaction (testnet+mainnet)"),
  631. )
  632. cmd_list_admin = OrderedDict()
  633. cmd_data_admin = OrderedDict()
  634. for k in cmd_group_admin: cmd_list_admin[k] = []
  635. cmd_data_admin['info_create_ref_tx'] = 'create reference tx',[8]
  636. for a,b in cmd_group_admin['create_ref_tx']:
  637. cmd_list_admin['create_ref_tx'].append(a)
  638. cmd_data_admin[a] = (8,b,[[[],8]])
  639. # end undocumented admin commands
  640. cmd_list = OrderedDict()
  641. for k in cmd_group: cmd_list[k] = []
  642. cmd_data = OrderedDict()
  643. for k,v in (
  644. ('help', ('help screens',[])),
  645. ('dfl_wallet', ('basic operations with default wallet',[15,16])),
  646. ('main', ('basic operations',[1,2,3,4,5,15,16])),
  647. ('tool', ('tools',[9]))
  648. ):
  649. cmd_data['info_'+k] = v
  650. for i in cmd_group[k]:
  651. cmd_list[k].append(i)
  652. cmd_data[i] = cmd_group[k][i]
  653. cmd_data['info_ref'] = 'reference data',[6,7,8]
  654. for a,b in cmd_group['ref']:
  655. for i,j in ((1,128),(2,192),(3,256)):
  656. k = a+str(i)
  657. cmd_list['ref'].append(k)
  658. cmd_data[k] = (5+i,'%s (%s-bit)' % (b[1],j),[[b[0],5+i]])
  659. cmd_data['info_ref_other'] = 'other reference data',[8]
  660. for a,b in cmd_group['ref_other']:
  661. cmd_list['ref_other'].append(a)
  662. cmd_data[a] = (8,b,[[[],8]])
  663. cmd_data['info_conv_in'] = 'wallet conversion from reference data',[11,12,13]
  664. for a,b in cmd_group['conv_in']:
  665. for i,j in ((1,128),(2,192),(3,256)):
  666. k = a+str(i)
  667. cmd_list['conv_in'].append(k)
  668. cmd_data[k] = (10+i,'%s (%s-bit)' % (b,j),[[[],10+i]])
  669. cmd_data['info_conv_out'] = 'wallet conversion to reference data',[11,12,13]
  670. for a,b in cmd_group['conv_out']:
  671. for i,j in ((1,128),(2,192),(3,256)):
  672. k = a+str(i)
  673. cmd_list['conv_out'].append(k)
  674. cmd_data[k] = (10+i,'%s (%s-bit)' % (b,j),[[[],10+i]])
  675. cmd_data['info_regtest'] = 'regtest mode',[17]
  676. for a,b in cmd_group['regtest']:
  677. cmd_list['regtest'].append(a)
  678. cmd_data[a] = (17,b,[[[],17]])
  679. utils = {
  680. 'check_deps': 'check dependencies for specified command',
  681. 'clean': 'clean specified tmp dir(s) 1,2,3,4,5 or 6 (no arg = all dirs)',
  682. }
  683. addrs_per_wallet = 8
  684. meta_cmds = OrderedDict([
  685. ['ref1', ('refwalletgen1','refaddrgen1','refkeyaddrgen1')],
  686. ['ref2', ('refwalletgen2','refaddrgen2','refkeyaddrgen2')],
  687. ['ref3', ('refwalletgen3','refaddrgen3','refkeyaddrgen3')],
  688. ['gen', ('walletgen','addrgen')],
  689. ['pass', ('passchg','walletchk_newpass')],
  690. ['tx', ('addrimport','txcreate','txsign','txsend')],
  691. ['export', [k for k in cmd_data if k[:7] == 'export_' and cmd_data[k][0] == 1]],
  692. ['gen_sp', [k for k in cmd_data if k[:8] == 'addrgen_' and cmd_data[k][0] == 1]],
  693. ['online', ('keyaddrgen','txsign_keyaddr')],
  694. ['2', [k for k in cmd_data if cmd_data[k][0] == 2]],
  695. ['3', [k for k in cmd_data if cmd_data[k][0] == 3]],
  696. ['4', [k for k in cmd_data if cmd_data[k][0] == 4]],
  697. ['saved_ref1', [c[0]+'1' for c in cmd_group['ref']]],
  698. ['saved_ref2', [c[0]+'2' for c in cmd_group['ref']]],
  699. ['saved_ref3', [c[0]+'3' for c in cmd_group['ref']]],
  700. ['saved_ref_other', [c[0] for c in cmd_group['ref_other']]],
  701. ['saved_ref_conv_in1', [c[0]+'1' for c in cmd_group['conv_in']]],
  702. ['saved_ref_conv_in2', [c[0]+'2' for c in cmd_group['conv_in']]],
  703. ['saved_ref_conv_in3', [c[0]+'3' for c in cmd_group['conv_in']]],
  704. ['saved_ref_conv_out1', [c[0]+'1' for c in cmd_group['conv_out']]],
  705. ['saved_ref_conv_out2', [c[0]+'2' for c in cmd_group['conv_out']]],
  706. ['saved_ref_conv_out3', [c[0]+'3' for c in cmd_group['conv_out']]],
  707. ['regtest', dict(cmd_group['regtest']).keys()],
  708. ])
  709. del cmd_group
  710. if opt.profile: opt.names = True
  711. if opt.resume: opt.skip_deps = True
  712. if opt.log:
  713. log_fd = open(log_file,'a')
  714. log_fd.write('\nLog started: %s\n' % make_timestr())
  715. usr_rand_chars = (5,30)[bool(opt.usr_random)]
  716. usr_rand_arg = '-r%s' % usr_rand_chars
  717. cmd_total = 0
  718. # Disable color in spawned scripts so we can parse their output
  719. os.environ['MMGEN_DISABLE_COLOR'] = '1'
  720. os.environ['MMGEN_NO_LICENSE'] = '1'
  721. os.environ['MMGEN_MIN_URANDCHARS'] = '3'
  722. os.environ['MMGEN_BOGUS_SEND'] = '1'
  723. def get_segwit_arg(cfg): return ([],['--type','segwit'])[cfg['segwit']]
  724. # Tell spawned programs they're running in the test suite
  725. os.environ['MMGEN_TEST_SUITE'] = '1'
  726. if opt.debug_scripts: os.environ['MMGEN_DEBUG'] = '1'
  727. if opt.exact_output:
  728. def msg(s): pass
  729. vmsg = vmsg_r = msg_r = msg
  730. else:
  731. def msg(s): sys.stderr.write(s+'\n')
  732. def vmsg(s):
  733. if opt.verbose: sys.stderr.write(s+'\n')
  734. def msg_r(s): sys.stderr.write(s)
  735. def vmsg_r(s):
  736. if opt.verbose: sys.stderr.write(s)
  737. stderr_save = sys.stderr
  738. def silence():
  739. if not (opt.verbose or opt.exact_output):
  740. f = ('/dev/null','stderr.out')[g.platform=='win']
  741. sys.stderr = open(f,'a')
  742. def end_silence():
  743. if not (opt.verbose or opt.exact_output):
  744. sys.stderr = stderr_save
  745. def errmsg(s): stderr_save.write(s+'\n')
  746. def errmsg_r(s): stderr_save.write(s)
  747. if opt.list_cmds:
  748. fs = ' {:<{w}} - {}'
  749. Msg(green('AVAILABLE COMMANDS:'))
  750. w = max([len(i) for i in cmd_data])
  751. for cmd in cmd_data:
  752. if cmd[:5] == 'info_':
  753. m = capfirst(cmd_data[cmd][0])
  754. Msg(green(' %s:' % m))
  755. continue
  756. Msg(' '+fs.format(cmd,cmd_data[cmd][1],w=w))
  757. w = max([len(i) for i in meta_cmds])
  758. Msg(green('\nAVAILABLE METACOMMANDS:'))
  759. for cmd in meta_cmds:
  760. Msg(fs.format(cmd,' '.join(meta_cmds[cmd]),w=w))
  761. w = max([len(i) for i in cmd_list])
  762. Msg(green('\nAVAILABLE COMMAND GROUPS:'))
  763. for g in cmd_list:
  764. Msg(fs.format(g,' '.join(cmd_list[g]),w=w))
  765. Msg(green('\nAVAILABLE UTILITIES:'))
  766. w = max([len(i) for i in utils])
  767. for cmd in sorted(utils):
  768. Msg(fs.format(cmd,utils[cmd],w=w))
  769. sys.exit(0)
  770. NL = ('\r\n','\n')[g.platform=='linux' and bool(opt.popen_spawn)]
  771. def get_file_with_ext(ext,mydir,delete=True,no_dot=False,return_list=False):
  772. dot = ('.','')[bool(no_dot)]
  773. flist = [os.path.join(mydir,f) for f in os.listdir(mydir)
  774. if f == ext or f[-len(dot+ext):] == dot+ext]
  775. if not flist: return False
  776. if return_list: return flist
  777. if len(flist) > 1:
  778. if delete:
  779. if not opt.quiet:
  780. msg("Multiple *.{} files in '{}' - deleting".format(ext,mydir))
  781. for f in flist:
  782. msg(f)
  783. os.unlink(f)
  784. return False
  785. else:
  786. return flist[0]
  787. def find_generated_exts(cmd):
  788. out = []
  789. for k in cfgs:
  790. for ext,prog in cfgs[k]['dep_generators'].items():
  791. if prog == cmd:
  792. out.append((ext,cfgs[k]['tmpdir']))
  793. return out
  794. def get_addrfile_checksum(display=False):
  795. addrfile = get_file_with_ext('addrs',cfg['tmpdir'])
  796. silence()
  797. chk = AddrList(addrfile).chksum
  798. if opt.verbose and display: msg('Checksum: %s' % cyan(chk))
  799. end_silence()
  800. return chk
  801. def verify_checksum_or_exit(checksum,chk):
  802. if checksum != chk:
  803. errmsg(red('Checksum error: %s' % chk))
  804. sys.exit(1)
  805. vmsg(green('Checksums match: %s') % (cyan(chk)))
  806. from test.mmgen_pexpect import MMGenPexpect
  807. class MMGenExpect(MMGenPexpect):
  808. def __init__(self,name,mmgen_cmd,cmd_args=[],extra_desc='',no_output=False,msg_only=False):
  809. desc = (cmd_data[name][1],name)[bool(opt.names)] + (' ' + extra_desc).strip()
  810. passthru_args = ['testnet','rpc_host','rpc_port','regtest','coin']
  811. if not opt.system:
  812. os.environ['PYTHONPATH'] = repo_root
  813. mmgen_cmd = os.path.relpath(os.path.join(repo_root,'cmds',mmgen_cmd))
  814. elif g.platform == 'win':
  815. mmgen_cmd = os.path.join('/mingw64','opt','bin',mmgen_cmd)
  816. return MMGenPexpect.__init__(
  817. self,
  818. name,
  819. mmgen_cmd,
  820. cmd_args,
  821. desc,
  822. no_output=no_output,
  823. passthru_args=passthru_args,
  824. msg_only=msg_only)
  825. def create_fake_unspent_entry(coinaddr,al_id=None,idx=None,lbl=None,non_mmgen=False,segwit=False):
  826. if 'S' not in g.proto.mmtypes: segwit = False
  827. if lbl: lbl = ' ' + lbl
  828. spk1,spk2 = (('76a914','88ac'),('a914','87'))[segwit and coinaddr.addr_fmt=='p2sh']
  829. amt1,amt2 = {'btc':(10,40),'bch':(10,40),'ltc':(1000,4000)}[g.coin.lower()]
  830. return {
  831. 'account': '{}:{}'.format(g.proto.base_coin.lower(),coinaddr) if non_mmgen \
  832. else (u'{}:{}{}'.format(al_id,idx,lbl.decode('utf8'))),
  833. 'vout': int(getrandnum(4) % 8),
  834. 'txid': hexlify(os.urandom(32)).decode('utf8'),
  835. 'amount': g.proto.coin_amt('%s.%s' % (amt1+(getrandnum(4) % amt2), getrandnum(4) % 100000000)),
  836. 'address': coinaddr,
  837. 'spendable': False,
  838. 'scriptPubKey': '{}{}{}'.format(spk1,coinaddr.hex,spk2),
  839. 'confirmations': getrandnum(4) % 50000
  840. }
  841. labels = [
  842. "Automotive",
  843. "Travel expenses",
  844. "Healthcare",
  845. "Freelancing 1",
  846. "Freelancing 2",
  847. "Alice's allowance",
  848. "Bob's bequest",
  849. "House purchase",
  850. "Real estate fund",
  851. "Job 1",
  852. "XYZ Corp.",
  853. "Eddie's endowment",
  854. "Emergency fund",
  855. "Real estate fund",
  856. "Ian's inheritance",
  857. "",
  858. "Rainy day",
  859. "Fred's funds",
  860. "Job 2",
  861. "Carl's capital",
  862. ]
  863. label_iter = None
  864. def create_fake_unspent_data(adata,tx_data,non_mmgen_input=''):
  865. out = []
  866. for d in tx_data.values():
  867. al = adata.addrlist(d['al_id'])
  868. for n,(idx,coinaddr) in enumerate(al.addrpairs()):
  869. while True:
  870. try: lbl = next(label_iter)
  871. except: label_iter = iter(labels)
  872. else: break
  873. out.append(create_fake_unspent_entry(coinaddr,d['al_id'],idx,lbl,segwit=d['segwit']))
  874. if n == 0: # create a duplicate address. This means addrs_per_wallet += 1
  875. out.append(create_fake_unspent_entry(coinaddr,d['al_id'],idx,lbl,segwit=d['segwit']))
  876. if non_mmgen_input:
  877. privkey = PrivKey(os.urandom(32),compressed=True)
  878. coinaddr = AddrGenerator('p2pkh').to_addr(KeyGenerator().to_pubhex(privkey))
  879. of = os.path.join(cfgs[non_mmgen_input]['tmpdir'],non_mmgen_fn)
  880. write_data_to_file(of,privkey.wif+'\n','compressed {} key'.format(g.proto.name),silent=True)
  881. out.append(create_fake_unspent_entry(coinaddr,non_mmgen=True,segwit=False))
  882. # msg('\n'.join([repr(o) for o in out])); sys.exit(0)
  883. return out
  884. def write_fake_data_to_file(d):
  885. unspent_data_file = os.path.join(cfg['tmpdir'],'unspent.json')
  886. write_data_to_file(unspent_data_file,d,'Unspent outputs',silent=True)
  887. os.environ['MMGEN_BOGUS_WALLET_DATA'] = unspent_data_file
  888. bwd_msg = 'MMGEN_BOGUS_WALLET_DATA=%s' % unspent_data_file
  889. if opt.print_cmdline: msg(bwd_msg)
  890. if opt.log: log_fd.write(bwd_msg + ' ')
  891. if opt.verbose or opt.exact_output:
  892. sys.stderr.write("Fake transaction wallet data written to file '%s'\n" % unspent_data_file)
  893. def create_tx_data(sources):
  894. tx_data,ad = {},AddrData()
  895. for s in sources:
  896. afile = get_file_with_ext('addrs',cfgs[s]['tmpdir'])
  897. al = AddrList(afile)
  898. ad.add(al)
  899. aix = AddrIdxList(fmt_str=cfgs[s]['addr_idx_list'])
  900. if len(aix) != addrs_per_wallet:
  901. errmsg(red('Address index list length != %s: %s' %
  902. (addrs_per_wallet,repr(aix))))
  903. sys.exit(0)
  904. tx_data[s] = {
  905. 'addrfile': afile,
  906. 'chk': al.chksum,
  907. 'al_id': al.al_id,
  908. 'addr_idxs': aix[-2:],
  909. 'segwit': cfgs[s]['segwit']
  910. }
  911. return ad,tx_data
  912. def make_txcreate_cmdline(tx_data):
  913. privkey = PrivKey(os.urandom(32),compressed=True)
  914. t = ('p2pkh','segwit')['S' in g.proto.mmtypes]
  915. coinaddr = AddrGenerator(t).to_addr(KeyGenerator().to_pubhex(privkey))
  916. # total of two outputs must be < 10 BTC (<1000 LTC)
  917. mods = {'btc':(6,4),'bch':(6,4),'ltc':(600,400)}[g.coin.lower()]
  918. for k in cfgs:
  919. cfgs[k]['amts'] = [None,None]
  920. for idx,mod in enumerate(mods):
  921. cfgs[k]['amts'][idx] = '%s.%s' % ((getrandnum(4) % mod), str(getrandnum(4))[:5])
  922. cmd_args = ['-d',cfg['tmpdir']]
  923. for num in tx_data:
  924. s = tx_data[num]
  925. cmd_args += [
  926. '{}:{},{}'.format(s['al_id'],s['addr_idxs'][0],cfgs[num]['amts'][0]),
  927. ]
  928. # + one change address and one BTC address
  929. if num is tx_data.keys()[-1]:
  930. cmd_args += ['{}:{}'.format(s['al_id'],s['addr_idxs'][1])]
  931. cmd_args += ['{},{}'.format(coinaddr,cfgs[num]['amts'][1])]
  932. return cmd_args + [tx_data[num]['addrfile'] for num in tx_data]
  933. def add_comments_to_addr_file(addrfile,outfile):
  934. silence()
  935. msg(green("Adding comments to address file '%s'" % addrfile))
  936. a = AddrList(addrfile)
  937. for n,idx in enumerate(a.idxs(),1):
  938. if n % 2: a.set_comment(idx,'Test address %s' % n)
  939. a.format(enable_comments=True)
  940. write_data_to_file(outfile,a.fmt_data,silent=True)
  941. end_silence()
  942. def make_brainwallet_file(fn):
  943. # Print random words with random whitespace in between
  944. from mmgen.mn_tirosh import words
  945. wl = words.split()
  946. nwords,ws_list,max_spaces = 10,' \n',5
  947. def rand_ws_seq():
  948. nchars = getrandnum(1) % max_spaces + 1
  949. return ''.join([ws_list[getrandnum(1)%len(ws_list)] for i in range(nchars)])
  950. rand_pairs = [wl[getrandnum(4) % len(wl)] + rand_ws_seq() for i in range(nwords)]
  951. d = ''.join(rand_pairs).rstrip() + '\n'
  952. if opt.verbose: msg_r('Brainwallet password:\n%s' % cyan(d))
  953. write_data_to_file(fn,d,'brainwallet password',silent=True)
  954. def do_between():
  955. if opt.pause:
  956. if keypress_confirm(green('Continue?'),default_yes=True):
  957. if opt.verbose or opt.exact_output: sys.stderr.write('\n')
  958. else:
  959. errmsg('Exiting at user request')
  960. sys.exit(0)
  961. elif opt.verbose or opt.exact_output:
  962. sys.stderr.write('\n')
  963. rebuild_list = OrderedDict()
  964. def check_needs_rerun(
  965. ts,
  966. cmd,
  967. build=False,
  968. root=True,
  969. force_delete=False,
  970. dpy=False
  971. ):
  972. rerun = (False,True)[root] # force_delete is not passed to recursive call
  973. fns = []
  974. if force_delete or not root:
  975. # does cmd produce a needed dependency(ies)?
  976. ret = ts.get_num_exts_for_cmd(cmd,dpy)
  977. if ret:
  978. for ext in ret[1]:
  979. fn = get_file_with_ext(ext,cfgs[ret[0]]['tmpdir'],delete=build)
  980. if fn:
  981. if force_delete: os.unlink(fn)
  982. else: fns.append(fn)
  983. else: rerun = True
  984. fdeps = ts.generate_file_deps(cmd)
  985. cdeps = ts.generate_cmd_deps(fdeps)
  986. # print 'cmd,fdeps,cdeps,fns: ',cmd,fdeps,cdeps,fns # DEBUG
  987. for fn in fns:
  988. my_age = os.stat(fn).st_mtime
  989. for num,ext in fdeps:
  990. f = get_file_with_ext(ext,cfgs[num]['tmpdir'],delete=build)
  991. if f and os.stat(f).st_mtime > my_age:
  992. rerun = True
  993. for cdep in cdeps:
  994. if check_needs_rerun(ts,cdep,build=build,root=False,dpy=cmd):
  995. rerun = True
  996. if build:
  997. if rerun:
  998. for fn in fns:
  999. if not root: os.unlink(fn)
  1000. if not (dpy and opt.skip_deps):
  1001. ts.do_cmd(cmd)
  1002. if not root: do_between()
  1003. else:
  1004. # If prog produces multiple files:
  1005. if cmd not in rebuild_list or rerun == True:
  1006. rebuild_list[cmd] = (rerun,fns[0] if fns else '') # FIX
  1007. return rerun
  1008. def refcheck(desc,chk,refchk):
  1009. vmsg("Comparing %s '%s' to stored reference" % (desc,chk))
  1010. if chk == refchk:
  1011. ok()
  1012. else:
  1013. if not opt.verbose: errmsg('')
  1014. errmsg(red("""
  1015. Fatal error - %s '%s' does not match reference value '%s'. Aborting test
  1016. """.strip() % (desc,chk,refchk)))
  1017. sys.exit(3)
  1018. def check_deps(cmds):
  1019. if len(cmds) != 1:
  1020. die(1,'Usage: %s check_deps <command>' % g.prog_name)
  1021. cmd = cmds[0]
  1022. if cmd not in cmd_data:
  1023. die(1,"'%s': unrecognized command" % cmd)
  1024. if not opt.quiet:
  1025. msg("Checking dependencies for '%s'" % (cmd))
  1026. check_needs_rerun(ts,cmd,build=False)
  1027. w = max(len(i) for i in rebuild_list) + 1
  1028. for cmd in rebuild_list:
  1029. c = rebuild_list[cmd]
  1030. m = 'Rebuild' if (c[0] and c[1]) else 'Build' if c[0] else 'OK'
  1031. msg('cmd {:<{w}} {}'.format(cmd+':', m, w=w))
  1032. # mmsg(cmd,c)
  1033. def clean(usr_dirs=[]):
  1034. if opt.skip_deps: return
  1035. all_dirs = MMGenTestSuite().list_tmp_dirs()
  1036. dirs = (usr_dirs or all_dirs)
  1037. for d in sorted(dirs):
  1038. if str(d) in all_dirs:
  1039. cleandir(all_dirs[str(d)])
  1040. else:
  1041. die(1,'%s: invalid directory number' % d)
  1042. cleandir(os.path.join('test','data_dir'))
  1043. class MMGenTestSuite(object):
  1044. def __init__(self):
  1045. pass
  1046. def list_tmp_dirs(self):
  1047. d = {}
  1048. for k in cfgs: d[k] = cfgs[k]['tmpdir']
  1049. return d
  1050. def get_num_exts_for_cmd(self,cmd,dpy=False): # dpy ignored here
  1051. num = str(cmd_data[cmd][0])
  1052. dgl = cfgs[num]['dep_generators']
  1053. # mmsg(num,cmd,dgl)
  1054. if cmd in dgl.values():
  1055. exts = [k for k in dgl if dgl[k] == cmd]
  1056. return (num,exts)
  1057. else:
  1058. return None
  1059. def do_cmd(self,cmd):
  1060. # delete files produced by this cmd
  1061. # for ext,tmpdir in find_generated_exts(cmd):
  1062. # print cmd, get_file_with_ext(ext,tmpdir)
  1063. d = [(str(num),ext) for exts,num in cmd_data[cmd][2] for ext in exts]
  1064. # delete files depended on by this cmd
  1065. al = [get_file_with_ext(ext,cfgs[num]['tmpdir']) for num,ext in d]
  1066. global cfg
  1067. cfg = cfgs[str(cmd_data[cmd][0])]
  1068. if opt.resume:
  1069. if cmd == opt.resume:
  1070. msg(yellow("Resuming at '%s'" % cmd))
  1071. opt.resume = False
  1072. opt.skip_deps = False
  1073. else:
  1074. return
  1075. if opt.profile: start = time.time()
  1076. self.__class__.__dict__[cmd](*([self,cmd] + al))
  1077. if opt.profile:
  1078. msg('\r\033[50C{:.4f}'.format(time.time() - start))
  1079. global cmd_total
  1080. cmd_total += 1
  1081. def generate_file_deps(self,cmd):
  1082. return [(str(n),e) for exts,n in cmd_data[cmd][2] for e in exts]
  1083. def generate_cmd_deps(self,fdeps):
  1084. return [cfgs[str(n)]['dep_generators'][ext] for n,ext in fdeps]
  1085. def helpscreens(self,name,arg='--help'):
  1086. scripts = (
  1087. 'walletgen','walletconv','walletchk','txcreate','txsign','txsend','txdo','txbump',
  1088. 'addrgen','addrimport','keygen','passchg','tool','passgen','regtest')
  1089. for s in scripts:
  1090. t = MMGenExpect(name,('mmgen-'+s),[arg],extra_desc='(mmgen-%s)'%s,no_output=True)
  1091. t.read()
  1092. t.ok()
  1093. def longhelpscreens(self,name): self.helpscreens(name,arg='--longhelp')
  1094. def walletgen(self,name,del_dw_run='dummy',seed_len=None,gen_dfl_wallet=False):
  1095. write_to_tmpfile(cfg,pwfile,cfg['wpasswd']+'\n')
  1096. args = ['-d',cfg['tmpdir'],'-p1']
  1097. if seed_len: args += ['-l',str(seed_len)]
  1098. t = MMGenExpect(name,'mmgen-walletgen', args + [usr_rand_arg])
  1099. t.license()
  1100. t.usr_rand(usr_rand_chars)
  1101. t.passphrase_new('new MMGen wallet',cfg['wpasswd'])
  1102. t.label()
  1103. global have_dfl_wallet
  1104. if not have_dfl_wallet:
  1105. t.expect('move it to the data directory? (Y/n): ',('n','y')[gen_dfl_wallet])
  1106. if gen_dfl_wallet: have_dfl_wallet = True
  1107. t.written_to_file('MMGen wallet')
  1108. t.ok()
  1109. def walletgen_dfl_wallet(self,name,seed_len=None):
  1110. self.walletgen(name,seed_len=seed_len,gen_dfl_wallet=True)
  1111. def brainwalletgen_ref(self,name):
  1112. sl_arg = '-l%s' % cfg['seed_len']
  1113. hp_arg = '-p%s' % ref_wallet_hash_preset
  1114. label = "test.py ref. wallet (pw '%s', seed len %s)" \
  1115. % (ref_wallet_brainpass,cfg['seed_len'])
  1116. bf = 'ref.mmbrain'
  1117. args = ['-d',cfg['tmpdir'],hp_arg,sl_arg,'-ib','-L',label]
  1118. write_to_tmpfile(cfg,bf,ref_wallet_brainpass)
  1119. write_to_tmpfile(cfg,pwfile,cfg['wpasswd'])
  1120. t = MMGenExpect(name,'mmgen-walletconv', args + [usr_rand_arg])
  1121. t.license()
  1122. t.expect('Enter brainwallet: ', ref_wallet_brainpass+'\n')
  1123. t.passphrase_new('new MMGen wallet',cfg['wpasswd'])
  1124. t.usr_rand(usr_rand_chars)
  1125. sid = os.path.basename(t.written_to_file('MMGen wallet').split('-')[0])
  1126. refcheck('Seed ID',sid,cfg['seed_id'])
  1127. def refwalletgen(self,name): self.brainwalletgen_ref(name)
  1128. def passchg(self,name,wf,pf):
  1129. silence()
  1130. write_to_tmpfile(cfg,pwfile,get_data_from_file(pf))
  1131. end_silence()
  1132. t = MMGenExpect(name,'mmgen-passchg', [usr_rand_arg] +
  1133. ['-d',cfg['tmpdir'],'-p','2','-L','Changed label'] + ([],[wf])[bool(wf)])
  1134. t.license()
  1135. t.passphrase('MMGen wallet',cfgs['1']['wpasswd'],pwtype='old')
  1136. t.expect_getend('Hash preset changed to ')
  1137. t.passphrase('MMGen wallet',cfg['wpasswd'],pwtype='new') # reuse passphrase?
  1138. t.expect('Repeat passphrase: ',cfg['wpasswd']+'\n')
  1139. t.usr_rand(usr_rand_chars)
  1140. # t.expect('Enter a wallet label.*: ','Changed Label\n',regex=True)
  1141. t.expect_getend('Label changed to ')
  1142. # t.expect_getend('Key ID changed: ')
  1143. if not wf:
  1144. t.expect("Type uppercase 'YES' to confirm: ",'YES\n')
  1145. t.written_to_file('New wallet')
  1146. t.expect('Securely deleting old wallet')
  1147. # t.expect('Okay to WIPE 1 regular file ? (Yes/No)','Yes\n')
  1148. t.expect('Wallet passphrase has changed')
  1149. t.expect_getend('has been changed to ')
  1150. else:
  1151. t.written_to_file('MMGen wallet')
  1152. t.ok()
  1153. def passchg_dfl_wallet(self,name,pf):
  1154. return self.passchg(name=name,wf=None,pf=pf)
  1155. def walletchk(self,name,wf,pf,desc='MMGen wallet',add_args=[],sid=None,pw=False,extra_desc=''):
  1156. args = []
  1157. hp = cfg['hash_preset'] if 'hash_preset' in cfg else '1'
  1158. wf_arg = ([],[wf])[bool(wf)]
  1159. t = MMGenExpect(name,'mmgen-walletchk',
  1160. add_args+args+['-p',hp]+wf_arg,
  1161. extra_desc=extra_desc)
  1162. if desc != 'hidden incognito data':
  1163. t.expect("Getting %s from file '" % (desc))
  1164. if pw:
  1165. t.passphrase(desc,cfg['wpasswd'])
  1166. t.expect(
  1167. ['Passphrase is OK', 'Passphrase.* are correct'],
  1168. regex=True
  1169. )
  1170. chk = t.expect_getend('Valid %s for Seed ID ' % desc)[:8]
  1171. if sid: t.cmp_or_die(chk,sid)
  1172. else: t.ok()
  1173. def walletchk_newpass(self,name,wf,pf):
  1174. return self.walletchk(name,wf,pf,pw=True)
  1175. def walletchk_newpass_dfl_wallet(self,name,pf):
  1176. return self.walletchk_newpass(name,wf=None,pf=pf)
  1177. def delete_dfl_wallet(self,name,pf):
  1178. with open(os.path.join(cfg['tmpdir'],'del_dw_run'),'w') as f: pass
  1179. if opt.no_dw_delete: return True
  1180. for wf in [f for f in os.listdir(g.data_dir) if f[-6:]=='.mmdat']:
  1181. os.unlink(os.path.join(g.data_dir,wf))
  1182. MMGenExpect(name,'',msg_only=True)
  1183. global have_dfl_wallet
  1184. have_dfl_wallet = False
  1185. ok()
  1186. def addrgen(self,name,wf,pf=None,check_ref=False,ftype='addr',id_str=None,extra_args=[],mmtype=None):
  1187. if cfg['segwit'] and ftype[:4] != 'pass' and not mmtype: mmtype = 'segwit'
  1188. cmd_pfx = (ftype,'pass')[ftype[:4]=='pass']
  1189. t = MMGenExpect(name,'mmgen-{}gen'.format(cmd_pfx),
  1190. ['-d',cfg['tmpdir']] +
  1191. extra_args +
  1192. ([],['--type='+str(mmtype)])[bool(mmtype)] +
  1193. ([],[wf])[bool(wf)] +
  1194. ([],[id_str])[bool(id_str)] +
  1195. [cfg['{}_idx_list'.format(cmd_pfx)]],extra_desc=('','(segwit)')[mmtype=='segwit'])
  1196. t.license()
  1197. t.passphrase('MMGen wallet',cfg['wpasswd'])
  1198. t.expect('Passphrase is OK')
  1199. desc = ('address','password')[ftype[:4]=='pass']
  1200. chk = t.expect_getend(r'Checksum for {} data .*?: '.format(desc),regex=True)
  1201. if check_ref:
  1202. k = 'passfile32_chk' if ftype == 'pass32' \
  1203. else 'passfile_chk' if ftype == 'pass' \
  1204. else '{}file{}_chk'.format(ftype,'_'+mmtype if mmtype else '')
  1205. chk_ref = cfg[k] if ftype[:4] == 'pass' else cfg[k][fork][g.testnet]
  1206. refcheck('address data checksum',chk,chk_ref)
  1207. return
  1208. t.written_to_file('Addresses',oo=True)
  1209. t.ok()
  1210. def addrgen_dfl_wallet(self,name,pf=None,check_ref=False):
  1211. return self.addrgen(name,wf=None,pf=pf,check_ref=check_ref)
  1212. def refaddrgen(self,name,wf,pf):
  1213. self.addrgen(name,wf,pf=pf,check_ref=True)
  1214. def refaddrgen_compressed(self,name,wf,pf):
  1215. if opt.segwit:
  1216. msg('Skipping non-Segwit address generation'); return True
  1217. self.addrgen(name,wf,pf=pf,check_ref=True,mmtype='compressed')
  1218. def addrimport(self,name,addrfile):
  1219. outfile = os.path.join(cfg['tmpdir'],'addrfile_w_comments')
  1220. add_comments_to_addr_file(addrfile,outfile)
  1221. t = MMGenExpect(name,'mmgen-addrimport', [outfile])
  1222. t.expect_getend(r'Checksum for address data .*\[.*\]: ',regex=True)
  1223. t.expect("Type uppercase 'YES' to confirm: ",'\n')
  1224. vmsg('This is a simulation, so no addresses were actually imported into the tracking\nwallet')
  1225. t.ok(exit_val=1)
  1226. def txcreate_common(self,name,sources=['1'],non_mmgen_input='',do_label=False,txdo_args=[],add_args=[]):
  1227. if opt.verbose or opt.exact_output:
  1228. sys.stderr.write(green('Generating fake tracking wallet info\n'))
  1229. silence()
  1230. ad,tx_data = create_tx_data(sources)
  1231. dfake = create_fake_unspent_data(ad,tx_data,non_mmgen_input)
  1232. write_fake_data_to_file(repr(dfake))
  1233. cmd_args = make_txcreate_cmdline(tx_data)
  1234. end_silence()
  1235. if opt.verbose or opt.exact_output: sys.stderr.write('\n')
  1236. t = MMGenExpect(name,
  1237. 'mmgen-'+('txcreate','txdo')[bool(txdo_args)],
  1238. ([],['--rbf'])[g.proto.cap('rbf')] +
  1239. ['-f',tx_fee] + add_args + cmd_args + txdo_args)
  1240. t.license()
  1241. if txdo_args and add_args: # txdo4
  1242. t.hash_preset('key-address data','1')
  1243. t.passphrase('key-address data',cfgs['14']['kapasswd'])
  1244. t.expect('Check key-to-address validity? (y/N): ','y')
  1245. for num in tx_data:
  1246. t.expect_getend('Getting address data from file ')
  1247. chk=t.expect_getend(r'Checksum for address data .*?: ',regex=True)
  1248. verify_checksum_or_exit(tx_data[num]['chk'],chk)
  1249. # not in tracking wallet warning, (1 + num sources) times
  1250. if t.expect(['Continue anyway? (y/N): ',
  1251. 'Unable to connect to {}'.format(g.proto.daemon_name)]) == 0:
  1252. t.send('y')
  1253. else:
  1254. errmsg(red('Error: unable to connect to {}. Exiting'.format(g.proto.daemon_name)))
  1255. sys.exit(1)
  1256. for num in tx_data:
  1257. t.expect('Continue anyway? (y/N): ','y')
  1258. t.expect(r"'q'=quit view, .*?:.",'M', regex=True)
  1259. t.expect(r"'q'=quit view, .*?:.",'q', regex=True)
  1260. outputs_list = [(addrs_per_wallet+1)*i + 1 for i in range(len(tx_data))]
  1261. if non_mmgen_input: outputs_list.append(len(tx_data)*(addrs_per_wallet+1) + 1)
  1262. t.expect('outputs to spend: ',' '.join([str(i) for i in outputs_list])+'\n')
  1263. if non_mmgen_input and not txdo_args: t.expect('Accept? (y/N): ','y')
  1264. t.expect('OK? (Y/n): ','y') # fee OK?
  1265. t.expect('OK? (Y/n): ','y') # change OK?
  1266. if do_label:
  1267. t.expect('Add a comment to transaction? (y/N): ','y')
  1268. t.expect('Comment: ',ref_tx_label.encode('utf8')+'\n')
  1269. else:
  1270. t.expect('Add a comment to transaction? (y/N): ','\n')
  1271. t.tx_view()
  1272. if txdo_args: return t
  1273. t.expect('Save transaction? (y/N): ','y')
  1274. t.written_to_file('Transaction')
  1275. t.ok()
  1276. def txcreate(self,name,addrfile):
  1277. self.txcreate_common(name,sources=['1'])
  1278. def txbump(self,name,txfile,prepend_args=[],seed_args=[]):
  1279. if not g.proto.cap('rbf'):
  1280. msg('Skipping RBF'); return True
  1281. args = prepend_args + ['-q','-d',cfg['tmpdir'],txfile] + seed_args
  1282. t = MMGenExpect(name,'mmgen-txbump',args)
  1283. if seed_args:
  1284. t.hash_preset('key-address data','1')
  1285. t.passphrase('key-address data',cfgs['14']['kapasswd'])
  1286. t.expect('Check key-to-address validity? (y/N): ','y')
  1287. t.expect('deduct the fee from (Hit ENTER for the change output): ','1\n')
  1288. # Fee must be > tx_fee + network relay fee (currently 0.00001)
  1289. t.expect('OK? (Y/n): ','\n')
  1290. t.expect('Enter transaction fee: ',txbump_fee+'\n')
  1291. t.expect('OK? (Y/n): ','\n')
  1292. if seed_args: # sign and send
  1293. t.expect('Edit transaction comment? (y/N): ','\n')
  1294. for cnum,desc in (('1','incognito data'),('3','MMGen wallet'),('4','MMGen wallet')):
  1295. t.passphrase(('%s' % desc),cfgs[cnum]['wpasswd'])
  1296. t.expect("Type uppercase 'YES' to confirm: ",'YES\n')
  1297. else:
  1298. t.expect('Add a comment to transaction? (y/N): ','\n')
  1299. t.expect('Save transaction? (y/N): ','y')
  1300. t.written_to_file('Transaction')
  1301. os.unlink(txfile) # our tx file replaces the original
  1302. os.system('touch ' + os.path.join(cfg['tmpdir'],'txbump'))
  1303. t.ok()
  1304. def txdo(self,name,addrfile,wallet):
  1305. t = self.txcreate_common(name,sources=['1'],txdo_args=[wallet])
  1306. self.txsign(name,'','',pf='',save=True,has_label=False,txdo_handle=t)
  1307. self.txsend(name,'',txdo_handle=t)
  1308. def txcreate_dfl_wallet(self,name,addrfile):
  1309. self.txcreate_common(name,sources=['15'])
  1310. def txsign_end(self,t,tnum=None,has_label=False):
  1311. t.expect('Signing transaction')
  1312. cprompt = ('Add a comment to transaction','Edit transaction comment')[has_label]
  1313. t.expect('%s? (y/N): ' % cprompt,'\n')
  1314. t.expect('Save signed transaction.*?\? \(Y/n\): ','y',regex=True)
  1315. add = ' #' + tnum if tnum else ''
  1316. t.written_to_file('Signed transaction' + add, oo=True)
  1317. def txsign(self,name,txfile,wf,pf='',bumpf='',save=True,has_label=False,txdo_handle=None):
  1318. if txdo_handle:
  1319. t = txdo_handle
  1320. else:
  1321. t = MMGenExpect(name,'mmgen-txsign', ['-d',cfg['tmpdir'],txfile]+([],[wf])[bool(wf)])
  1322. t.license()
  1323. t.tx_view()
  1324. t.passphrase('MMGen wallet',cfg['wpasswd'])
  1325. if txdo_handle: return
  1326. if save:
  1327. self.txsign_end(t,has_label=has_label)
  1328. t.ok()
  1329. else:
  1330. cprompt = ('Add a comment to transaction','Edit transaction comment')[has_label]
  1331. t.expect('%s? (y/N): ' % cprompt,'\n')
  1332. t.expect('Save signed transaction? (Y/n): ','n')
  1333. t.ok(exit_val=1)
  1334. def txsign_dfl_wallet(self,name,txfile,pf='',save=True,has_label=False):
  1335. return self.txsign(name,txfile,wf=None,pf=pf,save=save,has_label=has_label)
  1336. def txsend(self,name,sigfile,txdo_handle=None):
  1337. if txdo_handle:
  1338. t = txdo_handle
  1339. else:
  1340. t = MMGenExpect(name,'mmgen-txsend', ['-d',cfg['tmpdir'],sigfile])
  1341. t.license()
  1342. t.tx_view()
  1343. t.expect('Add a comment to transaction? (y/N): ','\n')
  1344. t.expect('Are you sure you want to broadcast this')
  1345. m = 'YES, I REALLY WANT TO DO THIS'
  1346. t.expect("'%s' to confirm: " % m,m+'\n')
  1347. t.expect('BOGUS transaction NOT sent')
  1348. t.written_to_file('Sent transaction')
  1349. t.ok()
  1350. def walletconv_export(self,name,wf,desc,uargs=[],out_fmt='w',pf=None,out_pw=False):
  1351. opts = ['-d',cfg['tmpdir'],'-o',out_fmt] + uargs + \
  1352. ([],[wf])[bool(wf)] + ([],['-P',pf])[bool(pf)]
  1353. t = MMGenExpect(name,'mmgen-walletconv',opts)
  1354. t.license()
  1355. if not pf:
  1356. t.passphrase('MMGen wallet',cfg['wpasswd'])
  1357. if out_pw:
  1358. t.passphrase_new('new '+desc,cfg['wpasswd'])
  1359. t.usr_rand(usr_rand_chars)
  1360. if ' '.join(desc.split()[-2:]) == 'incognito data':
  1361. t.expect('Generating encryption key from OS random data ')
  1362. t.expect('Generating encryption key from OS random data ')
  1363. ic_id = t.expect_getend('New Incog Wallet ID: ')
  1364. t.expect('Generating encryption key from OS random data ')
  1365. if desc == 'hidden incognito data':
  1366. write_to_tmpfile(cfg,incog_id_fn,ic_id)
  1367. ret = t.expect(['Create? (Y/n): ',"'YES' to confirm: "])
  1368. if ret == 0:
  1369. t.send('\n')
  1370. t.expect('Enter file size: ',str(hincog_bytes)+'\n')
  1371. else:
  1372. t.send('YES\n')
  1373. if out_fmt == 'w': t.label()
  1374. return t.written_to_file(capfirst(desc),oo=True),t
  1375. def export_seed(self,name,wf,desc='seed data',out_fmt='seed',pf=None):
  1376. f,t = self.walletconv_export(name,wf,desc=desc,out_fmt=out_fmt,pf=pf)
  1377. silence()
  1378. msg('%s: %s' % (capfirst(desc),cyan(get_data_from_file(f,desc))))
  1379. end_silence()
  1380. t.ok()
  1381. def export_hex(self,name,wf,desc='hexadecimal seed data',out_fmt='hex',pf=None):
  1382. self.export_seed(name,wf,desc=desc,out_fmt=out_fmt,pf=pf)
  1383. def export_seed_dfl_wallet(self,name,pf,desc='seed data',out_fmt='seed'):
  1384. self.export_seed(name,wf=None,desc=desc,out_fmt=out_fmt,pf=pf)
  1385. def export_mnemonic(self,name,wf):
  1386. self.export_seed(name,wf,desc='mnemonic data',out_fmt='words')
  1387. def export_incog(self,name,wf,desc='incognito data',out_fmt='i',add_args=[]):
  1388. uargs = ['-p1',usr_rand_arg] + add_args
  1389. f,t = self.walletconv_export(name,wf,desc=desc,out_fmt=out_fmt,uargs=uargs,out_pw=True)
  1390. t.ok()
  1391. def export_incog_hex(self,name,wf):
  1392. self.export_incog(name,wf,desc='hex incognito data',out_fmt='xi')
  1393. # TODO: make outdir and hidden incog compatible (ignore --outdir and warn user?)
  1394. def export_incog_hidden(self,name,wf):
  1395. rf = os.path.join(cfg['tmpdir'],hincog_fn)
  1396. add_args = ['-J','%s,%s'%(rf,hincog_offset)]
  1397. self.export_incog(
  1398. name,wf,desc='hidden incognito data',out_fmt='hi',add_args=add_args)
  1399. def addrgen_seed(self,name,wf,foo,desc='seed data',in_fmt='seed'):
  1400. stdout = (False,True)[desc=='seed data'] #capture output to screen once
  1401. add_args = ([],['-S'])[bool(stdout)] + get_segwit_arg(cfg)
  1402. t = MMGenExpect(name,'mmgen-addrgen', add_args +
  1403. ['-i'+in_fmt,'-d',cfg['tmpdir'],wf,cfg['addr_idx_list']])
  1404. t.license()
  1405. t.expect_getend('Valid %s for Seed ID ' % desc)
  1406. vmsg('Comparing generated checksum with checksum from previous address file')
  1407. chk = t.expect_getend(r'Checksum for address data .*?: ',regex=True)
  1408. if stdout: t.read()
  1409. verify_checksum_or_exit(get_addrfile_checksum(),chk)
  1410. if in_fmt == 'seed':
  1411. t.ok()
  1412. else:
  1413. t.no_overwrite()
  1414. t.ok(exit_val=1)
  1415. def addrgen_hex(self,name,wf,foo,desc='hexadecimal seed data',in_fmt='hex'):
  1416. self.addrgen_seed(name,wf,foo,desc=desc,in_fmt=in_fmt)
  1417. def addrgen_mnemonic(self,name,wf,foo):
  1418. self.addrgen_seed(name,wf,foo,desc='mnemonic data',in_fmt='words')
  1419. def addrgen_incog(self,name,wf=[],foo='',in_fmt='i',desc='incognito data',args=[]):
  1420. t = MMGenExpect(name,'mmgen-addrgen', args + get_segwit_arg(cfg) + ['-i'+in_fmt,'-d',cfg['tmpdir']]+
  1421. ([],[wf])[bool(wf)] + [cfg['addr_idx_list']])
  1422. t.license()
  1423. t.expect_getend('Incog Wallet ID: ')
  1424. t.hash_preset(desc,'1')
  1425. t.passphrase('%s \w{8}' % desc, cfg['wpasswd'])
  1426. vmsg('Comparing generated checksum with checksum from address file')
  1427. chk = t.expect_getend(r'Checksum for address data .*?: ',regex=True)
  1428. verify_checksum_or_exit(get_addrfile_checksum(),chk)
  1429. t.no_overwrite()
  1430. t.ok(exit_val=1)
  1431. def addrgen_incog_hex(self,name,wf,foo):
  1432. self.addrgen_incog(name,wf,'',in_fmt='xi',desc='hex incognito data')
  1433. def addrgen_incog_hidden(self,name,wf,foo):
  1434. rf = os.path.join(cfg['tmpdir'],hincog_fn)
  1435. self.addrgen_incog(name,[],'',in_fmt='hi',desc='hidden incognito data',
  1436. args=['-H','%s,%s'%(rf,hincog_offset),'-l',str(hincog_seedlen)])
  1437. def keyaddrgen(self,name,wf,pf=None,check_ref=False,mmtype=None):
  1438. if cfg['segwit'] and not mmtype: mmtype = 'segwit'
  1439. args = ['-d',cfg['tmpdir'],usr_rand_arg,wf,cfg['addr_idx_list']]
  1440. t = MMGenExpect(name,'mmgen-keygen',
  1441. ([],['--type='+str(mmtype)])[bool(mmtype)] + args,extra_desc=('','(segwit)')[mmtype=='segwit'])
  1442. t.license()
  1443. t.passphrase('MMGen wallet',cfg['wpasswd'])
  1444. chk = t.expect_getend(r'Checksum for key-address data .*?: ',regex=True)
  1445. if check_ref:
  1446. k = 'keyaddrfile{}_chk'.format('_'+mmtype if mmtype else '')
  1447. refcheck('key-address data checksum',chk,cfg[k][fork][g.testnet])
  1448. return
  1449. t.expect('Encrypt key list? (y/N): ','y')
  1450. t.usr_rand(usr_rand_chars)
  1451. t.hash_preset('new key list','1')
  1452. # t.passphrase_new('new key list','kafile password')
  1453. t.passphrase_new('new key list',cfg['kapasswd'])
  1454. t.written_to_file('Encrypted secret keys',oo=True)
  1455. t.ok()
  1456. def refkeyaddrgen(self,name,wf,pf):
  1457. self.keyaddrgen(name,wf,pf,check_ref=True)
  1458. def refkeyaddrgen_compressed(self,name,wf,pf):
  1459. if opt.segwit:
  1460. msg('Skipping non-Segwit key-address generation'); return True
  1461. self.keyaddrgen(name,wf,pf,check_ref=True,mmtype='compressed')
  1462. def refpasswdgen(self,name,wf,pf):
  1463. self.addrgen(name,wf,pf,check_ref=True,ftype='pass',id_str='alice@crypto.org')
  1464. def ref_b32passwdgen(self,name,wf,pf):
  1465. ea = ['--base32','--passwd-len','17']
  1466. self.addrgen(name,wf,pf,check_ref=True,ftype='pass32',id_str='фубар@crypto.org',extra_args=ea)
  1467. def txsign_keyaddr(self,name,keyaddr_file,txfile):
  1468. t = MMGenExpect(name,'mmgen-txsign', ['-d',cfg['tmpdir'],'-M',keyaddr_file,txfile])
  1469. t.license()
  1470. t.hash_preset('key-address data','1')
  1471. t.passphrase('key-address data',cfg['kapasswd'])
  1472. t.expect('Check key-to-address validity? (y/N): ','y')
  1473. t.tx_view()
  1474. self.txsign_end(t)
  1475. t.ok()
  1476. def walletgen2(self,name,del_dw_run='dummy'):
  1477. self.walletgen(name,seed_len=128)
  1478. def addrgen2(self,name,wf):
  1479. self.addrgen(name,wf,pf='')
  1480. def txcreate2(self,name,addrfile):
  1481. self.txcreate_common(name,sources=['2'])
  1482. def txsign2(self,name,txf1,wf1,txf2,wf2):
  1483. t = MMGenExpect(name,'mmgen-txsign', ['-d',cfg['tmpdir'],txf1,wf1,txf2,wf2])
  1484. t.license()
  1485. for cnum in ('1','2'):
  1486. t.tx_view()
  1487. t.passphrase('MMGen wallet',cfgs[cnum]['wpasswd'])
  1488. self.txsign_end(t,cnum)
  1489. t.ok()
  1490. def export_mnemonic2(self,name,wf):
  1491. self.export_mnemonic(name,wf)
  1492. def walletgen3(self,name,del_dw_run='dummy'):
  1493. self.walletgen(name)
  1494. def addrgen3(self,name,wf):
  1495. self.addrgen(name,wf,pf='')
  1496. def txcreate3(self,name,addrfile1,addrfile2):
  1497. self.txcreate_common(name,sources=['1','3'])
  1498. def txsign3(self,name,wf1,wf2,txf2):
  1499. t = MMGenExpect(name,'mmgen-txsign', ['-d',cfg['tmpdir'],wf1,wf2,txf2])
  1500. t.license()
  1501. t.tx_view()
  1502. for cnum in ('1','3'):
  1503. # t.expect_getend('Getting MMGen wallet data from file ')
  1504. t.passphrase('MMGen wallet',cfgs[cnum]['wpasswd'])
  1505. self.txsign_end(t)
  1506. t.ok()
  1507. def walletgen4(self,name,del_dw_run='dummy'):
  1508. bwf = os.path.join(cfg['tmpdir'],cfg['bw_filename'])
  1509. make_brainwallet_file(bwf)
  1510. seed_len = str(cfg['seed_len'])
  1511. args = ['-d',cfg['tmpdir'],'-p1',usr_rand_arg,'-l'+seed_len,'-ib']
  1512. t = MMGenExpect(name,'mmgen-walletconv', args + [bwf])
  1513. t.license()
  1514. t.passphrase_new('new MMGen wallet',cfg['wpasswd'])
  1515. t.usr_rand(usr_rand_chars)
  1516. t.label()
  1517. t.written_to_file('MMGen wallet')
  1518. t.ok()
  1519. def addrgen4(self,name,wf):
  1520. self.addrgen(name,wf,pf='')
  1521. def txcreate4(self,name,f1,f2,f3,f4,f5,f6):
  1522. self.txcreate_common(name,sources=['1','2','3','4','14'],non_mmgen_input='4',do_label=1)
  1523. def txdo4(self,name,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12):
  1524. non_mm_fn = os.path.join(cfg['tmpdir'],non_mmgen_fn)
  1525. add_args = ['-d',cfg['tmpdir'],'-i','brain','-b'+cfg['bw_params'],'-p1','-k',non_mm_fn,'-M',f12]
  1526. t = self.txcreate_common(name,sources=['1','2','3','4','14'],non_mmgen_input='4',do_label=1,txdo_args=[f7,f8,f9,f10],add_args=add_args)
  1527. os.system('rm -f %s/*.sigtx' % cfg['tmpdir'])
  1528. self.txsign4(name,f7,f8,f9,f10,f11,f12,txdo_handle=t)
  1529. self.txsend(name,'',txdo_handle=t)
  1530. os.system('touch ' + os.path.join(cfg['tmpdir'],'txdo'))
  1531. def txbump4(self,name,f1,f2,f3,f4,f5,f6,f7,f8,f9): # f7:txfile,f9:'txdo'
  1532. non_mm_fn = os.path.join(cfg['tmpdir'],non_mmgen_fn)
  1533. self.txbump(name,f7,prepend_args=['-p1','-k',non_mm_fn,'-M',f1],seed_args=[f2,f3,f4,f5,f6,f8])
  1534. def txsign4(self,name,f1,f2,f3,f4,f5,f6,txdo_handle=None):
  1535. if txdo_handle:
  1536. t = txdo_handle
  1537. else:
  1538. non_mm_fn = os.path.join(cfg['tmpdir'],non_mmgen_fn)
  1539. a = ['-d',cfg['tmpdir'],'-i','brain','-b'+cfg['bw_params'],'-p1','-k',non_mm_fn,'-M',f6,f1,f2,f3,f4,f5]
  1540. t = MMGenExpect(name,'mmgen-txsign',a)
  1541. t.license()
  1542. t.hash_preset('key-address data','1')
  1543. t.passphrase('key-address data',cfgs['14']['kapasswd'])
  1544. t.expect('Check key-to-address validity? (y/N): ','y')
  1545. t.tx_view()
  1546. for cnum,desc in (('1','incognito data'),('3','MMGen wallet')):
  1547. t.passphrase(('%s' % desc),cfgs[cnum]['wpasswd'])
  1548. if txdo_handle: return
  1549. self.txsign_end(t,has_label=True)
  1550. t.ok()
  1551. def tool_encrypt(self,name,infile=''):
  1552. if infile:
  1553. infn = infile
  1554. else:
  1555. d = os.urandom(1033)
  1556. tmp_fn = cfg['tool_enc_infn']
  1557. write_to_tmpfile(cfg,tmp_fn,d,binary=True)
  1558. infn = get_tmpfile_fn(cfg,tmp_fn)
  1559. t = MMGenExpect(name,'mmgen-tool',['-d',cfg['tmpdir'],usr_rand_arg,'encrypt',infn])
  1560. t.usr_rand(usr_rand_chars)
  1561. t.hash_preset('user data','1')
  1562. t.passphrase_new('user data',tool_enc_passwd)
  1563. t.written_to_file('Encrypted data')
  1564. t.ok()
  1565. # Generate the reference mmenc file
  1566. # def tool_encrypt_ref(self,name):
  1567. # infn = get_tmpfile_fn(cfg,cfg['tool_enc_ref_infn'])
  1568. # write_data_to_file(infn,cfg['tool_enc_reftext'],silent=True)
  1569. # self.tool_encrypt(name,infn)
  1570. def tool_decrypt(self,name,f1,f2):
  1571. of = name + '.out'
  1572. pre = []
  1573. t = MMGenExpect(name,'mmgen-tool',
  1574. pre+['-d',cfg['tmpdir'],'decrypt',f2,'outfile='+of,'hash_preset=1'])
  1575. t.passphrase('user data',tool_enc_passwd)
  1576. t.written_to_file('Decrypted data')
  1577. d1 = read_from_file(f1,binary=True)
  1578. d2 = read_from_file(get_tmpfile_fn(cfg,of),binary=True)
  1579. cmp_or_die(d1,d2,skip_ok=False)
  1580. def tool_find_incog_data(self,name,f1,f2):
  1581. i_id = read_from_file(f2).rstrip()
  1582. vmsg('Incog ID: %s' % cyan(i_id))
  1583. t = MMGenExpect(name,'mmgen-tool',
  1584. ['-d',cfg['tmpdir'],'find_incog_data',f1,i_id])
  1585. o = t.expect_getend('Incog data for ID %s found at offset ' % i_id)
  1586. os.unlink(f1)
  1587. cmp_or_die(hincog_offset,int(o))
  1588. # Saved reference file tests
  1589. def ref_wallet_conv(self,name):
  1590. wf = os.path.join(ref_dir,cfg['ref_wallet'])
  1591. self.walletconv_in(name,wf,'MMGen wallet',pw=True,oo=True)
  1592. def ref_mn_conv(self,name,ext='mmwords',desc='Mnemonic data'):
  1593. wf = os.path.join(ref_dir,cfg['seed_id']+'.'+ext)
  1594. self.walletconv_in(name,wf,desc,oo=True)
  1595. def ref_seed_conv(self,name):
  1596. self.ref_mn_conv(name,ext='mmseed',desc='Seed data')
  1597. def ref_hex_conv(self,name):
  1598. self.ref_mn_conv(name,ext='mmhex',desc='Hexadecimal seed data')
  1599. def ref_brain_conv(self,name):
  1600. uopts = ['-i','b','-p','1','-l',str(cfg['seed_len'])]
  1601. self.walletconv_in(name,None,'brainwallet',uopts,oo=True)
  1602. def ref_incog_conv(self,name,wfk='ic_wallet',in_fmt='i',desc='incognito data'):
  1603. uopts = ['-i',in_fmt,'-p','1','-l',str(cfg['seed_len'])]
  1604. wf = os.path.join(ref_dir,cfg[wfk])
  1605. self.walletconv_in(name,wf,desc,uopts,oo=True,pw=True)
  1606. def ref_incox_conv(self,name):
  1607. self.ref_incog_conv(name,in_fmt='xi',wfk='ic_wallet_hex',desc='hex incognito data')
  1608. def ref_hincog_conv(self,name,wfk='hic_wallet',add_uopts=[]):
  1609. ic_f = os.path.join(ref_dir,cfg[wfk])
  1610. uopts = ['-i','hi','-p','1','-l',str(cfg['seed_len'])] + add_uopts
  1611. hi_opt = ['-H','%s,%s' % (ic_f,ref_wallet_incog_offset)]
  1612. self.walletconv_in(name,None,'hidden incognito data',uopts+hi_opt,oo=True,pw=True)
  1613. def ref_hincog_conv_old(self,name):
  1614. self.ref_hincog_conv(name,wfk='hic_wallet_old',add_uopts=['-O'])
  1615. def ref_wallet_conv_out(self,name):
  1616. self.walletconv_out(name,'MMGen wallet','w',pw=True)
  1617. def ref_mn_conv_out(self,name):
  1618. self.walletconv_out(name,'mnemonic data','mn')
  1619. def ref_seed_conv_out(self,name):
  1620. self.walletconv_out(name,'seed data','seed')
  1621. def ref_hex_conv_out(self,name):
  1622. self.walletconv_out(name,'hexadecimal seed data','hexseed')
  1623. def ref_incog_conv_out(self,name):
  1624. self.walletconv_out(name,'incognito data',out_fmt='i',pw=True)
  1625. def ref_incox_conv_out(self,name):
  1626. self.walletconv_out(name,'hex incognito data',out_fmt='xi',pw=True)
  1627. def ref_hincog_conv_out(self,name,extra_uopts=[]):
  1628. ic_f = os.path.join(cfg['tmpdir'],hincog_fn)
  1629. hi_parms = '%s,%s' % (ic_f,ref_wallet_incog_offset)
  1630. sl_parm = '-l' + str(cfg['seed_len'])
  1631. self.walletconv_out(name,
  1632. 'hidden incognito data', 'hi',
  1633. uopts=['-J',hi_parms,sl_parm] + extra_uopts,
  1634. uopts_chk=['-H',hi_parms,sl_parm],
  1635. pw=True
  1636. )
  1637. def ref_wallet_chk(self,name):
  1638. wf = os.path.join(ref_dir,cfg['ref_wallet'])
  1639. self.walletchk(name,wf,pf=None,pw=True,sid=cfg['seed_id'])
  1640. def ref_ss_chk(self,name,ss=None):
  1641. wf = os.path.join(ref_dir,'%s.%s' % (cfg['seed_id'],ss.ext))
  1642. self.walletchk(name,wf,pf=None,desc=ss.desc,sid=cfg['seed_id'])
  1643. def ref_seed_chk(self,name):
  1644. from mmgen.seed import SeedFile
  1645. self.ref_ss_chk(name,ss=SeedFile)
  1646. def ref_hex_chk(self,name):
  1647. from mmgen.seed import HexSeedFile
  1648. self.ref_ss_chk(name,ss=HexSeedFile)
  1649. def ref_mn_chk(self,name):
  1650. from mmgen.seed import Mnemonic
  1651. self.ref_ss_chk(name,ss=Mnemonic)
  1652. def ref_brain_chk(self,name,bw_file=ref_bw_file):
  1653. wf = os.path.join(ref_dir,bw_file)
  1654. add_args = ['-l%s' % cfg['seed_len'], '-p'+ref_bw_hash_preset]
  1655. self.walletchk(name,wf,pf=None,add_args=add_args,
  1656. desc='brainwallet',sid=cfg['ref_bw_seed_id'])
  1657. def ref_brain_chk_spc3(self,name):
  1658. self.ref_brain_chk(name,bw_file=ref_bw_file_spc)
  1659. def ref_hincog_chk(self,name,desc='hidden incognito data'):
  1660. for wtype,edesc,of_arg in ('hic_wallet','',[]), \
  1661. ('hic_wallet_old','(old format)',['-O']):
  1662. ic_arg = ['-H%s,%s' % (
  1663. os.path.join(ref_dir,cfg[wtype]),
  1664. ref_wallet_incog_offset
  1665. )]
  1666. slarg = ['-l%s ' % cfg['seed_len']]
  1667. hparg = ['-p1']
  1668. if wtype == 'hic_wallet_old' and opt.profile: msg('')
  1669. t = MMGenExpect(name,'mmgen-walletchk',
  1670. slarg + hparg + of_arg + ic_arg,
  1671. extra_desc=edesc)
  1672. t.passphrase(desc,cfg['wpasswd'])
  1673. if wtype == 'hic_wallet_old':
  1674. t.expect('Is the Seed ID correct? (Y/n): ','\n')
  1675. chk = t.expect_getend('Seed ID: ')
  1676. t.close()
  1677. cmp_or_die(cfg['seed_id'],chk)
  1678. def ref_addrfile_chk(self,name,ftype='addr'):
  1679. af_key = 'ref_{}file'.format(ftype)
  1680. af = os.path.join(ref_dir,(ref_subdir,'')[ftype=='passwd'],cfg[af_key])
  1681. t = MMGenExpect(name,'mmgen-tool',[ftype.replace('segwit','')+'file_chksum',af])
  1682. if ftype == 'keyaddr':
  1683. w = 'key-address data'
  1684. t.hash_preset(w,ref_kafile_hash_preset)
  1685. t.passphrase(w,ref_kafile_pass)
  1686. t.expect('Check key-to-address validity? (y/N): ','y')
  1687. o = t.read().strip().split('\n')[-1]
  1688. rc = cfg['ref_'+ftype+'file_chksum']
  1689. ref_chksum = rc if ftype == 'passwd' else rc[g.proto.base_coin.lower()][g.testnet]
  1690. cmp_or_die(ref_chksum,o)
  1691. def ref_keyaddrfile_chk(self,name):
  1692. self.ref_addrfile_chk(name,ftype='keyaddr')
  1693. def ref_passwdfile_chk(self,name):
  1694. self.ref_addrfile_chk(name,ftype='passwd')
  1695. def ref_segwitaddrfile_chk(self,name):
  1696. if not 'S' in g.proto.mmtypes:
  1697. msg_r('Skipping {} (not supported)'.format(name))
  1698. ok()
  1699. else:
  1700. self.ref_addrfile_chk(name,ftype='segwitaddr')
  1701. # def txcreate8(self,name,addrfile):
  1702. # self.txcreate_common(name,sources=['8'])
  1703. def ref_tx_chk(self,name):
  1704. tf = os.path.join(ref_dir,ref_subdir,cfg['ref_tx_file'][g.coin.lower()].format(tn_ext))
  1705. wf = os.path.join(ref_dir,cfg['ref_wallet'])
  1706. write_to_tmpfile(cfg,pwfile,cfg['wpasswd'])
  1707. pf = get_tmpfile_fn(cfg,pwfile)
  1708. self.txsign(name,tf,wf,pf,save=False,has_label=True)
  1709. def ref_tool_decrypt(self,name):
  1710. f = os.path.join(ref_dir,ref_enc_fn)
  1711. t = MMGenExpect(name,'mmgen-tool', ['-q','decrypt',f,'outfile=-','hash_preset=1'])
  1712. t.passphrase('user data',tool_enc_passwd)
  1713. # t.expect("Type uppercase 'YES' to confirm: ",'YES\n') # comment out with popen_spawn
  1714. t.expect(NL,nonl=True)
  1715. import re
  1716. o = re.sub('\r\n','\n',t.read())
  1717. cmp_or_die(sample_text,o)
  1718. # wallet conversion tests
  1719. def walletconv_in(self,name,infile,desc,uopts=[],pw=False,oo=False):
  1720. opts = ['-d',cfg['tmpdir'],'-o','words',usr_rand_arg]
  1721. if_arg = [infile] if infile else []
  1722. d = '(convert)'
  1723. t = MMGenExpect(name,'mmgen-walletconv',opts+uopts+if_arg,extra_desc=d)
  1724. t.license()
  1725. if desc == 'brainwallet':
  1726. t.expect('Enter brainwallet: ',ref_wallet_brainpass+'\n')
  1727. if pw:
  1728. t.passphrase(desc,cfg['wpasswd'])
  1729. if name[:19] == 'ref_hincog_conv_old':
  1730. t.expect('Is the Seed ID correct? (Y/n): ','\n')
  1731. else:
  1732. t.expect(['Passphrase is OK',' are correct'])
  1733. # Output
  1734. wf = t.written_to_file('Mnemonic data',oo=oo)
  1735. t.close()
  1736. t.ok()
  1737. # back check of result
  1738. if opt.profile: msg('')
  1739. self.walletchk(name,wf,pf=None,
  1740. desc='mnemonic data',
  1741. sid=cfg['seed_id'],
  1742. extra_desc='(check)'
  1743. )
  1744. def walletconv_out(self,name,desc,out_fmt='w',uopts=[],uopts_chk=[],pw=False):
  1745. opts = ['-d',cfg['tmpdir'],'-p1','-o',out_fmt] + uopts
  1746. infile = os.path.join(ref_dir,cfg['seed_id']+'.mmwords')
  1747. t = MMGenExpect(name,'mmgen-walletconv',[usr_rand_arg]+opts+[infile],extra_desc='(convert)')
  1748. add_args = ['-l%s' % cfg['seed_len']]
  1749. t.license()
  1750. if pw:
  1751. t.passphrase_new('new '+desc,cfg['wpasswd'])
  1752. t.usr_rand(usr_rand_chars)
  1753. if ' '.join(desc.split()[-2:]) == 'incognito data':
  1754. for i in (1,2,3):
  1755. t.expect('Generating encryption key from OS random data ')
  1756. if desc == 'hidden incognito data':
  1757. ret = t.expect(['Create? (Y/n): ',"'YES' to confirm: "])
  1758. if ret == 0:
  1759. t.send('\n')
  1760. t.expect('Enter file size: ',str(hincog_bytes)+'\n')
  1761. else:
  1762. t.send('YES\n')
  1763. if out_fmt == 'w': t.label()
  1764. wf = t.written_to_file(capfirst(desc),oo=True)
  1765. pf = None
  1766. t.ok()
  1767. if desc == 'hidden incognito data':
  1768. add_args += uopts_chk
  1769. wf = None
  1770. if opt.profile: msg('')
  1771. self.walletchk(name,wf,pf=pf,
  1772. desc=desc,sid=cfg['seed_id'],pw=pw,
  1773. add_args=add_args,
  1774. extra_desc='(check)')
  1775. def regtest_setup(self,name):
  1776. if g.testnet:
  1777. die(2,'--testnet option incompatible with regtest test suite')
  1778. try: shutil.rmtree(os.path.join(data_dir,'regtest'))
  1779. except: pass
  1780. os.environ['MMGEN_TEST_SUITE'] = '' # mnemonic is piped to stdin, so stop being a terminal
  1781. t = MMGenExpect(name,'mmgen-regtest',['-n','setup'])
  1782. os.environ['MMGEN_TEST_SUITE'] = '1'
  1783. for s in 'Starting setup','Creating','Mined','Creating','Creating','Setup complete':
  1784. t.expect(s)
  1785. t.ok()
  1786. def regtest_walletgen(self,name,user):
  1787. t = MMGenExpect(name,'mmgen-walletgen',['-q','-r0','-p1','--'+user])
  1788. t.passphrase_new('new MMGen wallet','abc')
  1789. t.label()
  1790. t.expect('move it to the data directory? (Y/n): ','y')
  1791. t.written_to_file('MMGen wallet')
  1792. t.ok()
  1793. def regtest_walletgen_bob(self,name): return self.regtest_walletgen(name,'bob')
  1794. def regtest_walletgen_alice(self,name): return self.regtest_walletgen(name,'alice')
  1795. @staticmethod
  1796. def regtest_user_dir(user):
  1797. return os.path.join(data_dir,'regtest',user)
  1798. def regtest_user_sid(self,user):
  1799. return os.path.basename(get_file_with_ext('mmdat',self.regtest_user_dir(user)))[:8]
  1800. def regtest_addrgen(self,name,user,wf=None,passwd='abc',addr_range='1-5'):
  1801. from mmgen.addr import MMGenAddrType
  1802. for mmtype in g.proto.mmtypes:
  1803. t = MMGenExpect(name,'mmgen-addrgen',
  1804. ['--quiet','--'+user,'--type='+mmtype,'--outdir={}'.format(self.regtest_user_dir(user))] +
  1805. ([],[wf])[bool(wf)] + [addr_range],
  1806. extra_desc='({})'.format(MMGenAddrType.mmtypes[mmtype]['name']))
  1807. t.passphrase('MMGen wallet',passwd)
  1808. t.written_to_file('Addresses')
  1809. t.ok()
  1810. def regtest_addrgen_bob(self,name): self.regtest_addrgen(name,'bob')
  1811. def regtest_addrgen_alice(self,name): self.regtest_addrgen(name,'alice')
  1812. def regtest_addrimport(self,name,user,sid=None,addr_range='1-5',num_addrs=5):
  1813. id_strs = { 'legacy':'', 'compressed':'-C', 'segwit':'-S' }
  1814. if not sid: sid = self.regtest_user_sid(user)
  1815. from mmgen.addr import MMGenAddrType
  1816. for mmtype in g.proto.mmtypes:
  1817. desc = MMGenAddrType.mmtypes[mmtype]['name']
  1818. fn = os.path.join(self.regtest_user_dir(user),
  1819. '{}{}{}[{}].addrs'.format(sid,altcoin_pfx,id_strs[desc],addr_range))
  1820. t = MMGenExpect(name,'mmgen-addrimport', ['--quiet','--'+user,'--batch',fn],extra_desc='('+desc+')')
  1821. t.expect('Importing')
  1822. t.expect('{} addresses imported'.format(num_addrs))
  1823. t.ok()
  1824. def regtest_addrimport_bob(self,name): self.regtest_addrimport(name,'bob')
  1825. def regtest_addrimport_alice(self,name): self.regtest_addrimport(name,'alice')
  1826. def regtest_fund_wallet(self,name,user,mmtype,amt,sid=None,addr_range='1-5'):
  1827. if not sid: sid = self.regtest_user_sid(user)
  1828. addr = self.get_addr_from_regtest_addrlist(user,sid,mmtype,0,addr_range=addr_range)
  1829. t = MMGenExpect(name,'mmgen-regtest', ['send',str(addr),str(amt)])
  1830. t.expect('Sending {} {}'.format(amt,g.coin))
  1831. t.expect('Mined 1 block')
  1832. t.ok()
  1833. def regtest_fund_bob(self,name): self.regtest_fund_wallet(name,'bob','C',rtFundAmt)
  1834. def regtest_fund_alice(self,name): self.regtest_fund_wallet(name,'alice',('L','S')[g.proto.cap('segwit')],rtFundAmt)
  1835. def regtest_user_bal(self,name,user,bal):
  1836. t = MMGenExpect(name,'mmgen-tool',['--'+user,'listaddresses','showempty=1'])
  1837. total = t.expect_getend('TOTAL: ')
  1838. cmp_or_die(total,'{} {}'.format(bal,g.coin))
  1839. def regtest_alice_bal1(self,name):
  1840. return self.regtest_user_bal(name,'alice',rtFundAmt)
  1841. def regtest_bob_bal1(self,name):
  1842. return self.regtest_user_bal(name,'bob',rtFundAmt)
  1843. def regtest_bob_bal2(self,name):
  1844. return self.regtest_user_bal(name,'bob',rtBals[0])
  1845. def regtest_bob_bal3(self,name):
  1846. return self.regtest_user_bal(name,'bob',rtBals[1])
  1847. def regtest_bob_bal4(self,name):
  1848. return self.regtest_user_bal(name,'bob',rtBals[2])
  1849. def regtest_bob_bal5(self,name):
  1850. return self.regtest_user_bal(name,'bob',rtBals[3])
  1851. def regtest_bob_alice_bal(self,name):
  1852. t = MMGenExpect(name,'mmgen-regtest',['get_balances'])
  1853. t.expect('Switching')
  1854. ret = t.expect_getend("Bob's balance:").strip()
  1855. cmp_or_die(ret,rtBals[4],skip_ok=True)
  1856. ret = t.expect_getend("Alice's balance:").strip()
  1857. cmp_or_die(ret,rtBals[5],skip_ok=True)
  1858. ret = t.expect_getend("Total balance:").strip()
  1859. cmp_or_die(ret,rtBals[6],skip_ok=True)
  1860. t.ok()
  1861. def regtest_user_txdo(self,name,user,fee,outputs_cl,outputs_prompt,extra_args=[],wf=None,pw='abc',no_send=False,do_label=False):
  1862. os.environ['MMGEN_BOGUS_SEND'] = ''
  1863. t = MMGenExpect(name,'mmgen-txdo',
  1864. ['-d',cfg['tmpdir'],'-B','--'+user,'--tx-fee='+fee]
  1865. + extra_args + ([],[wf])[bool(wf)] + outputs_cl)
  1866. os.environ['MMGEN_BOGUS_SEND'] = '1'
  1867. t.expect(r"'q'=quit view, .*?:.",'M',regex=True) # sort by mmid
  1868. t.expect(r"'q'=quit view, .*?:.",'q',regex=True)
  1869. t.expect('outputs to spend: ',outputs_prompt+'\n')
  1870. t.expect('OK? (Y/n): ','y') # fee OK?
  1871. t.expect('OK? (Y/n): ','y') # change OK?
  1872. if do_label:
  1873. t.expect('Add a comment to transaction? (y/N): ','y')
  1874. t.expect('Comment: ',ref_tx_label.encode('utf8')+'\n')
  1875. t.expect('View decoded transaction\? .*?: ','n',regex=True)
  1876. else:
  1877. t.expect('Add a comment to transaction? (y/N): ','\n')
  1878. t.expect('View decoded transaction\? .*?: ','t',regex=True)
  1879. t.expect('to continue: ','\n')
  1880. t.passphrase('MMGen wallet',pw)
  1881. t.written_to_file('Signed transaction')
  1882. if not no_send:
  1883. t.expect('to confirm: ','YES, I REALLY WANT TO DO THIS\n')
  1884. t.expect('Transaction sent')
  1885. t.read()
  1886. t.ok()
  1887. def regtest_bob_split1(self,name):
  1888. sid = self.regtest_user_sid('bob')
  1889. outputs_cl = [sid+':C:1,100', sid+':L:2,200',sid+':'+rtBobOp3]
  1890. return self.regtest_user_txdo(name,'bob',rtFee[0],outputs_cl,'1',do_label=True)
  1891. def get_addr_from_regtest_addrlist(self,user,sid,mmtype,idx,addr_range='1-5'):
  1892. id_str = { 'L':'', 'S':'-S', 'C':'-C' }[mmtype]
  1893. ext = '{}{}{}[{}].addrs'.format(sid,altcoin_pfx,id_str,addr_range)
  1894. fn = get_file_with_ext(ext,self.regtest_user_dir(user),no_dot=True)
  1895. silence()
  1896. psave = g.proto
  1897. g.proto = CoinProtocol(g.coin,True)
  1898. addr = AddrList(fn).data[idx].addr
  1899. g.proto = psave
  1900. end_silence()
  1901. return addr
  1902. def create_tx_outputs(self,user,data):
  1903. sid = self.regtest_user_sid(user)
  1904. return [self.get_addr_from_regtest_addrlist(user,sid,mmtype,idx-1)+amt_str for mmtype,idx,amt_str in data]
  1905. def regtest_bob_rbf_send(self,name):
  1906. outputs_cl = self.create_tx_outputs('alice',(('L',1,',60'),('C',1,',40'))) # alice_sid:L:1, alice_sid:C:1
  1907. outputs_cl += [self.regtest_user_sid('bob')+':'+rtBobOp3]
  1908. return self.regtest_user_txdo(name,'bob',rtFee[1],outputs_cl,'3',
  1909. extra_args=([],['--rbf'])[g.proto.cap('rbf')])
  1910. def regtest_bob_send_non_mmgen(self,name):
  1911. outputs_cl = self.create_tx_outputs('alice',(
  1912. (('L','S')[g.proto.cap('segwit')],2,',10'),
  1913. (('L','S')[g.proto.cap('segwit')],3,'')
  1914. )) # alice_sid:S:2, alice_sid:S:3
  1915. fn = os.path.join(cfg['tmpdir'],'non-mmgen.keys')
  1916. return self.regtest_user_txdo(name,'bob',rtFee[3],outputs_cl,'3-9',extra_args=['--keys-from-file='+fn])
  1917. def regtest_user_txbump(self,name,user,txfile,fee,red_op,no_send=False):
  1918. if not g.proto.cap('rbf'):
  1919. msg('Skipping RBF'); return True
  1920. os.environ['MMGEN_BOGUS_SEND'] = ''
  1921. t = MMGenExpect(name,'mmgen-txbump',
  1922. ['-d',cfg['tmpdir'],'--send','--'+user,'--tx-fee='+fee,'--output-to-reduce='+red_op] + [txfile])
  1923. os.environ['MMGEN_BOGUS_SEND'] = '1'
  1924. t.expect('OK? (Y/n): ','y') # output OK?
  1925. t.expect('OK? (Y/n): ','y') # fee OK?
  1926. t.expect('Add a comment to transaction? (y/N): ','n')
  1927. t.passphrase('MMGen wallet','abc')
  1928. t.written_to_file('Signed transaction')
  1929. if not no_send:
  1930. t.expect('to confirm: ','YES, I REALLY WANT TO DO THIS\n')
  1931. t.expect('Transaction sent')
  1932. t.written_to_file('Signed transaction')
  1933. t.read()
  1934. t.ok()
  1935. def regtest_bob_rbf_bump(self,name):
  1936. txfile = get_file_with_ext(',{}].sigtx'.format(rtFee[1][:-1]),cfg['tmpdir'],delete=False,no_dot=True)
  1937. return self.regtest_user_txbump(name,'bob',txfile,rtFee[2],'c')
  1938. def regtest_generate(self,name):
  1939. t = MMGenExpect(name,'mmgen-regtest',['generate'])
  1940. t.expect('Mined 1 block')
  1941. t.ok()
  1942. def regtest_get_mempool(self,name):
  1943. t = MMGenExpect(name,'mmgen-regtest',['show_mempool'])
  1944. return eval(t.read())
  1945. def regtest_get_mempool1(self,name):
  1946. mp = self.regtest_get_mempool(name)
  1947. if len(mp) != 1:
  1948. rdie(2,'Mempool has more or less than one TX!')
  1949. write_to_tmpfile(cfg,'rbf_txid',mp[0]+'\n')
  1950. ok()
  1951. def regtest_get_mempool2(self,name):
  1952. if not g.proto.cap('rbf'):
  1953. msg('Skipping post-RBF mempool check'); return True
  1954. mp = self.regtest_get_mempool(name)
  1955. if len(mp) != 1:
  1956. rdie(2,'Mempool has more or less than one TX!')
  1957. chk = read_from_tmpfile(cfg,'rbf_txid')
  1958. if chk.strip() == mp[0]:
  1959. rdie(2,'TX in mempool has not changed! RBF bump failed')
  1960. ok()
  1961. @staticmethod
  1962. def gen_pairs(n):
  1963. return [subprocess.check_output(
  1964. ['python',os.path.join('cmds','mmgen-tool'),'--testnet=1','-r0','randpair','compressed={}'.format((i+1)%2)]).split()
  1965. for i in range(n)]
  1966. def regtest_bob_pre_import(self,name):
  1967. pairs = self.gen_pairs(5)
  1968. write_to_tmpfile(cfg,'non-mmgen.keys','\n'.join([a[0] for a in pairs])+'\n')
  1969. write_to_tmpfile(cfg,'non-mmgen.addrs','\n'.join([a[1] for a in pairs])+'\n')
  1970. return self.regtest_user_txdo(name,'bob',rtFee[4],[pairs[0][1]],'3')
  1971. def regtest_user_import(self,name,user,args):
  1972. t = MMGenExpect(name,'mmgen-addrimport',['--quiet','--'+user]+args)
  1973. t.expect('Importing')
  1974. t.expect('OK')
  1975. t.ok()
  1976. def regtest_bob_import_addr(self,name):
  1977. addr = read_from_tmpfile(cfg,'non-mmgen.addrs').split()[0]
  1978. return self.regtest_user_import(name,'bob',['--rescan','--address='+addr])
  1979. def regtest_bob_import_list(self,name):
  1980. fn = os.path.join(cfg['tmpdir'],'non-mmgen.addrs')
  1981. return self.regtest_user_import(name,'bob',['--addrlist',fn])
  1982. def regtest_bob_split2(self,name):
  1983. addrs = read_from_tmpfile(cfg,'non-mmgen.addrs').split()
  1984. amts = (a for a in (1.12345678,2.87654321,3.33443344,4.00990099,5.43214321))
  1985. outputs1 = ['{},{}'.format(a,amts.next()) for a in addrs]
  1986. sid = self.regtest_user_sid('bob')
  1987. outputs2 = [sid+':C:2,6', sid+':L:3,7',sid+(':L:1',':S:3')[g.proto.cap('segwit')]]
  1988. return self.regtest_user_txdo(name,'bob',rtFee[5],outputs1+outputs2,'1-2')
  1989. def regtest_user_add_label(self,name,user,addr,label):
  1990. t = MMGenExpect(name,'mmgen-tool',['--'+user,'add_label',addr,label])
  1991. t.expect('Added label.*in tracking wallet',regex=True)
  1992. t.ok()
  1993. def regtest_user_remove_label(self,name,user,addr):
  1994. t = MMGenExpect(name,'mmgen-tool',['--'+user,'remove_label',addr])
  1995. t.expect('Removed label.*in tracking wallet',regex=True)
  1996. t.ok()
  1997. def regtest_alice_add_label1(self,name):
  1998. sid = self.regtest_user_sid('alice')
  1999. return self.regtest_user_add_label(name,'alice',sid+':C:1','Original Label')
  2000. def regtest_alice_add_label2(self,name):
  2001. sid = self.regtest_user_sid('alice')
  2002. return self.regtest_user_add_label(name,'alice',sid+':C:1','Replacement Label')
  2003. def regtest_alice_remove_label1(self,name):
  2004. sid = self.regtest_user_sid('alice')
  2005. return self.regtest_user_remove_label(name,'alice',sid+':C:1')
  2006. def regtest_user_chk_label(self,name,user,addr,label):
  2007. t = MMGenExpect(name,'mmgen-tool',['--'+user,'listaddresses','all_labels=1'])
  2008. t.expect('{}\s+\S{{30}}\S+\s+{}\s+'.format(addr,label),regex=True)
  2009. t.ok()
  2010. def regtest_alice_chk_label1(self,name):
  2011. sid = self.regtest_user_sid('alice')
  2012. return self.regtest_user_chk_label(name,'alice',sid+':C:1','Original Label')
  2013. def regtest_alice_chk_label2(self,name):
  2014. sid = self.regtest_user_sid('alice')
  2015. return self.regtest_user_chk_label(name,'alice',sid+':C:1','Replacement Label')
  2016. def regtest_alice_chk_label3(self,name):
  2017. sid = self.regtest_user_sid('alice')
  2018. return self.regtest_user_chk_label(name,'alice',sid+':C:1','Edited Label')
  2019. def regtest_alice_chk_label4(self,name):
  2020. sid = self.regtest_user_sid('alice')
  2021. return self.regtest_user_chk_label(name,'alice',sid+':C:1','-')
  2022. def regtest_user_edit_label(self,name,user,output,label):
  2023. t = MMGenExpect(name,'mmgen-txcreate',['-B','--'+user,'-i'])
  2024. t.expect(r"'q'=quit view, .*?:.",'M',regex=True)
  2025. t.expect(r"'q'=quit view, .*?:.",'l',regex=True)
  2026. t.expect(r"Enter unspent.*return to main menu\):.",output+'\n',regex=True)
  2027. t.expect(r"Enter label text.*return to main menu\):.",label+'\n',regex=True)
  2028. t.expect(r"'q'=quit view, .*?:.",'q',regex=True)
  2029. t.ok()
  2030. def regtest_alice_edit_label1(self,name):
  2031. return self.regtest_user_edit_label(name,'alice','1','Edited Label')
  2032. def regtest_stop(self,name):
  2033. t = MMGenExpect(name,'mmgen-regtest',['stop'])
  2034. t.ok()
  2035. # regtest undocumented admin commands
  2036. ref_tx_setup = regtest_setup
  2037. ref_tx_generate = regtest_generate
  2038. def ref_tx_addrgen_bob_ref_wallet(self,name):
  2039. wf = os.path.join(ref_dir,cfg['ref_wallet'])
  2040. self.regtest_addrgen(name,'bob',wf=wf,passwd=cfg['wpasswd'],addr_range='1-100')
  2041. def ref_tx_addrimport_bob_ref_wallet(self,name):
  2042. self.regtest_addrimport(name,'bob',sid=cfg['seed_id'],addr_range='1-100',num_addrs=100)
  2043. def ref_tx_fund_bob(self,name):
  2044. mmtype = g.proto.mmtypes[-1]
  2045. self.regtest_fund_wallet(name,'bob',mmtype,rtFundAmt,sid=cfg['seed_id'],addr_range='1-100')
  2046. def ref_tx_bob_split(self,name):
  2047. sid = cfg['seed_id']
  2048. outputs_cl = [sid+':C:1,100', sid+':L:2,200',sid+':'+rtBobOp3]
  2049. wf = os.path.join(ref_dir,cfg['ref_wallet'])
  2050. return self.regtest_user_txdo(name,'bob',rtFee[0],outputs_cl,'1',do_label=True,wf=wf,pw=cfg['wpasswd'])
  2051. def ref_tx_bob_create_tx(self,name):
  2052. sid = cfg['seed_id']
  2053. psave = g.proto
  2054. g.proto = CoinProtocol(g.coin,True)
  2055. privhex = PrivKey(os.urandom(32),compressed=True)
  2056. addr = AddrGenerator('p2pkh').to_addr(KeyGenerator().to_pubhex(privhex))
  2057. g.proto = psave
  2058. outputs_cl = [sid+':{}:3,1.1234'.format(g.proto.mmtypes[-1]), sid+':C:5,5.5555',sid+':L:4',addr+',100']
  2059. pw = cfg['wpasswd']
  2060. # create tx in cwd
  2061. t = MMGenExpect(name,'mmgen-txcreate',['-B','--bob','--tx-fee='+rtFee[0]] + outputs_cl)
  2062. # [os.path.join(ref_dir,cfg['ref_wallet'])])
  2063. t.expect(r"'q'=quit view, .*?:.",'M',regex=True) # sort by mmid
  2064. t.expect(r"'q'=quit view, .*?:.",'q',regex=True)
  2065. t.expect('outputs to spend: ','1 2 3\n')
  2066. t.expect('OK? (Y/n): ','y') # fee OK?
  2067. t.expect('OK? (Y/n): ','y') # change OK?
  2068. t.expect('Add a comment to transaction? (y/N): ','y')
  2069. t.expect('Comment: ',ref_tx_label.encode('utf8')+'\n')
  2070. t.expect('View decoded transaction\? .*?: ','n',regex=True)
  2071. t.expect('Save transaction? (y/N): ','y')
  2072. fn = t.written_to_file('Transaction')
  2073. write_to_tmpfile(cfg,'ref_tx_fn',fn)
  2074. t.ok()
  2075. def ref_tx_bob_modify_tx(self,name):
  2076. MMGenExpect(name,'',msg_only=True)
  2077. fn = read_from_tmpfile(cfg,'ref_tx_fn')
  2078. with open(fn) as f:
  2079. lines = f.read().splitlines()
  2080. from mmgen.obj import BTCAmt,LTCAmt,BCHAmt
  2081. tx = {}
  2082. for k,i in (('in',3),('out',4)):
  2083. tx[k] = eval(lines[i])
  2084. tx[k+'_addrs'] = [i['addr'] for i in tx[k]]
  2085. psave = g.proto
  2086. g.proto = CoinProtocol(g.coin,True)
  2087. from mmgen.obj import CoinAddr
  2088. for k in ('in_addrs','out_addrs'):
  2089. tx[k+'_hex'] = [(CoinAddr(a).hex,CoinAddr(a).addr_fmt) for a in tx[k]]
  2090. g.proto = psave
  2091. for k in ('in_addrs','out_addrs'):
  2092. tx[k+'_conv'] = [g.proto.hexaddr2addr(h,(False,True)[f=='p2sh']) for h,f in tx[k+'_hex']]
  2093. for k in ('in','out'):
  2094. for i in range(len(tx[k])):
  2095. tx[k][i]['addr'] = tx[k+'_addrs_conv'][i]
  2096. lines_tn = [lines[1].replace('REGTEST','TESTNET')] + lines[2:]
  2097. o_tn = '\n'.join([make_chksum_6(' '.join(lines_tn))] + lines_tn)+'\n'
  2098. fn_tn = fn.replace('.rawtx','.testnet.rawtx')
  2099. lines_mn = [lines[1].replace('REGTEST','MAINNET'),
  2100. lines[2],
  2101. repr(tx['in']),
  2102. repr(tx['out'])] + lines[5:]
  2103. o_mn = '\n'.join([make_chksum_6(' '.join(lines_mn))] + lines_mn)+'\n'
  2104. fn_mn = fn.replace('.rawtx','.mainnet.rawtx')
  2105. ok()
  2106. write_data_to_file(fn_tn,o_tn,'testnet TX data',ask_overwrite=False)
  2107. write_data_to_file(fn_mn,o_mn,'mainnet TX data',ask_overwrite=False)
  2108. # END methods
  2109. for k in (
  2110. 'ref_wallet_conv',
  2111. 'ref_mn_conv',
  2112. 'ref_seed_conv',
  2113. 'ref_hex_conv',
  2114. 'ref_brain_conv',
  2115. 'ref_incog_conv',
  2116. 'ref_incox_conv',
  2117. 'ref_hincog_conv',
  2118. 'ref_hincog_conv_old',
  2119. 'ref_wallet_conv_out',
  2120. 'ref_mn_conv_out',
  2121. 'ref_seed_conv_out',
  2122. 'ref_hex_conv_out',
  2123. 'ref_incog_conv_out',
  2124. 'ref_incox_conv_out',
  2125. 'ref_hincog_conv_out',
  2126. 'ref_wallet_chk',
  2127. 'refwalletgen',
  2128. 'ref_seed_chk',
  2129. 'ref_hex_chk',
  2130. 'ref_mn_chk',
  2131. 'ref_brain_chk',
  2132. 'ref_hincog_chk',
  2133. 'refaddrgen',
  2134. 'refkeyaddrgen',
  2135. 'refaddrgen_compressed',
  2136. 'refkeyaddrgen_compressed',
  2137. 'refpasswdgen',
  2138. 'ref_b32passwdgen'
  2139. ):
  2140. for i in ('1','2','3'):
  2141. locals()[k+i] = locals()[k]
  2142. for k in ('walletgen','addrgen','keyaddrgen'): locals()[k+'14'] = locals()[k]
  2143. # create temporary dirs
  2144. if not opt.resume and not opt.skip_deps:
  2145. if g.platform == 'win':
  2146. for cfg in sorted(cfgs):
  2147. mk_tmpdir(cfgs[cfg]['tmpdir'])
  2148. else:
  2149. for cfg in sorted(cfgs):
  2150. src = os.path.join(shm_dir,cfgs[cfg]['tmpdir'].split('/')[-1])
  2151. mk_tmpdir(src)
  2152. try:
  2153. os.unlink(cfgs[cfg]['tmpdir'])
  2154. except OSError as e:
  2155. if e.errno != 2: raise
  2156. finally:
  2157. os.symlink(src,cfgs[cfg]['tmpdir'])
  2158. have_dfl_wallet = False
  2159. # main()
  2160. if opt.pause:
  2161. import termios,atexit
  2162. fd = sys.stdin.fileno()
  2163. old = termios.tcgetattr(fd)
  2164. def at_exit():
  2165. termios.tcsetattr(fd, termios.TCSADRAIN, old)
  2166. atexit.register(at_exit)
  2167. start_time = int(time.time())
  2168. def end_msg():
  2169. t = int(time.time()) - start_time
  2170. m = '{} tests performed. Elapsed time: {:02d}:{:02d}\n'
  2171. sys.stderr.write(green(m.format(cmd_total,t/60,t%60)))
  2172. ts = MMGenTestSuite()
  2173. if cmd_args and cmd_args[0] == 'admin':
  2174. cmd_args.pop(0)
  2175. cmd_data = cmd_data_admin
  2176. cmd_list = cmd_list_admin
  2177. try:
  2178. if cmd_args:
  2179. for arg in cmd_args:
  2180. if arg in utils:
  2181. globals()[arg](cmd_args[cmd_args.index(arg)+1:])
  2182. sys.exit(0)
  2183. elif 'info_'+arg in cmd_data:
  2184. dirs = cmd_data['info_'+arg][1]
  2185. if dirs: clean(dirs)
  2186. for cmd in cmd_list[arg]:
  2187. check_needs_rerun(ts,cmd,build=True)
  2188. elif arg in meta_cmds:
  2189. for cmd in meta_cmds[arg]:
  2190. check_needs_rerun(ts,cmd,build=True)
  2191. elif arg in cmd_data:
  2192. check_needs_rerun(ts,arg,build=True)
  2193. else:
  2194. die(1,'%s: unrecognized command' % arg)
  2195. else:
  2196. clean()
  2197. for cmd in cmd_data:
  2198. if cmd == 'info_regtest': break # don't run these by default
  2199. if cmd[:5] == 'info_':
  2200. msg(green('%sTesting %s' % (('\n','')[bool(opt.resume)],cmd_data[cmd][0])))
  2201. continue
  2202. ts.do_cmd(cmd)
  2203. if cmd is not cmd_data.keys()[-1]: do_between()
  2204. except KeyboardInterrupt:
  2205. die(1,'\nExiting at user request')
  2206. except opt.traceback and Exception:
  2207. with open('my.err') as f:
  2208. t = f.readlines()
  2209. if t: msg_r('\n'+yellow(''.join(t[:-1]))+red(t[-1]))
  2210. die(1,blue('Test script exited with error'))
  2211. except:
  2212. sys.stderr = stderr_save
  2213. raise
  2214. end_msg()