ct_ethdev.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2024 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. test.cmdtest_py_d.ct_ethdev: Ethdev tests for the cmdtest.py test suite
  20. """
  21. import sys,os,re,shutil,asyncio,json
  22. from decimal import Decimal
  23. from collections import namedtuple
  24. from subprocess import run,PIPE,DEVNULL
  25. from mmgen.color import yellow,blue,cyan,set_vt100
  26. from mmgen.util import msg,rmsg,die
  27. from ..include.common import (
  28. cfg,
  29. check_solc_ver,
  30. omsg,
  31. imsg,
  32. imsg_r,
  33. joinpath,
  34. read_from_file,
  35. write_to_file,
  36. cmp_or_die,
  37. strip_ansi_escapes,
  38. silence,
  39. end_silence,
  40. gr_uc,
  41. stop_test_daemons
  42. )
  43. from .common import (
  44. ref_dir,
  45. dfl_words_file,
  46. tx_comment_jp,
  47. tx_comment_lat_cyr_gr,
  48. tw_comment_zh,
  49. tw_comment_lat_cyr_gr,
  50. get_file_with_ext,
  51. ok_msg,
  52. Ctrl_U
  53. )
  54. from .ct_base import CmdTestBase
  55. from .ct_shared import CmdTestShared
  56. del_addrs = ('4','1')
  57. dfl_sid = '98831F3A'
  58. # The OpenEthereum dev address with lots of coins. Create with "ethkey -b info ''":
  59. dfl_devaddr = '00a329c0648769a73afac7f9381e08fb43dbea72'
  60. dfl_devkey = '4d5db4107d237df6a3d58ee5f70ae63d73d7658d4026f2eefd2f204c81682cb7'
  61. burn_addr = 'deadbeef'*5
  62. burn_addr2 = 'beadcafe'*5
  63. amt1 = '999999.12345689012345678'
  64. amt2 = '888.111122223333444455'
  65. parity_devkey_fn = 'parity.devkey'
  66. def set_vbals(daemon_id):
  67. global vbal1, vbal2, vbal3, vbal4, vbal5, vbal6, vbal7, vbal9
  68. if daemon_id == 'geth':
  69. vbal1 = '1.2288347'
  70. vbal2 = '99.996561415'
  71. vbal3 = '1.23141825'
  72. vbal4 = '127.0287847'
  73. vbal5 = '1000126.14775300512345678'
  74. vbal6 = '1000126.14880300512345678'
  75. vbal7 = '1000124.91891830512345678'
  76. vbal9 = '1.22625235'
  77. else:
  78. vbal1 = '1.2288409'
  79. vbal2 = '99.997088755'
  80. vbal3 = '1.23142525'
  81. vbal4 = '127.0287909'
  82. vbal5 = '1000126.14828654512345678'
  83. vbal6 = '1000126.14933654512345678'
  84. vbal7 = '1000124.91944564512345678'
  85. vbal9 = '1.22626295'
  86. bals = lambda k: {
  87. '1': [ ('98831F3A:E:1','123.456')],
  88. '2': [ ('98831F3A:E:1','123.456'),('98831F3A:E:11','1.234')],
  89. '3': [ ('98831F3A:E:1','123.456'),('98831F3A:E:11','1.234'),('98831F3A:E:21','2.345')],
  90. '4': [ ('98831F3A:E:1','100'),
  91. ('98831F3A:E:2','23.45495'),
  92. ('98831F3A:E:11','1.234'),
  93. ('98831F3A:E:21','2.345')],
  94. '5': [ ('98831F3A:E:1','100'),
  95. ('98831F3A:E:2','23.45495'),
  96. ('98831F3A:E:11','1.234'),
  97. ('98831F3A:E:21','2.345'),
  98. (burn_addr + r'\s+non-MMGen',amt1)],
  99. '8': [ ('98831F3A:E:1','0'),
  100. ('98831F3A:E:2','23.45495'),
  101. ('98831F3A:E:11',vbal1,'a1'),
  102. ('98831F3A:E:12','99.99895'),
  103. ('98831F3A:E:21','2.345'),
  104. (burn_addr + r'\s+non-MMGen',amt1)],
  105. '9': [ ('98831F3A:E:1','0'),
  106. ('98831F3A:E:2','23.45495'),
  107. ('98831F3A:E:11',vbal1,'a1'),
  108. ('98831F3A:E:12',vbal2),
  109. ('98831F3A:E:21','2.345'),
  110. (burn_addr + r'\s+non-MMGen',amt1)],
  111. '10': [ ('98831F3A:E:1','0'),
  112. ('98831F3A:E:2','23.0218'),
  113. ('98831F3A:E:3','0.4321'),
  114. ('98831F3A:E:11',vbal1,'a1'),
  115. ('98831F3A:E:12',vbal2),
  116. ('98831F3A:E:21','2.345'),
  117. (burn_addr + r'\s+non-MMGen',amt1)]
  118. }[k]
  119. token_bals = lambda k: {
  120. '1': [ ('98831F3A:E:11','1000','1.234')],
  121. '2': [ ('98831F3A:E:11','998.76544',vbal3,'a1'),
  122. ('98831F3A:E:12','1.23456','0')],
  123. '3': [ ('98831F3A:E:11','110.654317776666555545',vbal1,'a1'),
  124. ('98831F3A:E:12','1.23456','0')],
  125. '4': [ ('98831F3A:E:11','110.654317776666555545',vbal1,'a1'),
  126. ('98831F3A:E:12','1.23456','0'),
  127. (burn_addr + r'\s+non-MMGen',amt2,amt1)],
  128. '5': [ ('98831F3A:E:11','110.654317776666555545',vbal1,'a1'),
  129. ('98831F3A:E:12','1.23456','99.99895'),
  130. (burn_addr + r'\s+non-MMGen',amt2,amt1)],
  131. '6': [ ('98831F3A:E:11','110.654317776666555545',vbal1,'a1'),
  132. ('98831F3A:E:12','0',vbal2),
  133. ('98831F3A:E:13','1.23456','0'),
  134. (burn_addr + r'\s+non-MMGen',amt2,amt1)],
  135. '7': [ ('98831F3A:E:11','67.444317776666555545',vbal9,'a2'),
  136. ('98831F3A:E:12','43.21',vbal2),
  137. ('98831F3A:E:13','1.23456','0'),
  138. (burn_addr + r'\s+non-MMGen',amt2,amt1)]
  139. }[k]
  140. token_bals_getbalance = lambda k: {
  141. '1': (vbal4,'999999.12345689012345678'),
  142. '2': ('111.888877776666555545','888.111122223333444455')
  143. }[k]
  144. coin = cfg.coin
  145. class CmdTestEthdev(CmdTestBase,CmdTestShared):
  146. 'Ethereum transacting, token deployment and tracking wallet operations'
  147. networks = ('eth','etc')
  148. passthru_opts = ('coin','daemon_id','http_timeout','rpc_backend')
  149. extra_spawn_args = ['--regtest=1']
  150. tmpdir_nums = [22]
  151. color = True
  152. cmd_group_in = (
  153. ('setup', f'dev mode tests for coin {coin} (start daemon)'),
  154. ('subgroup.misc', []),
  155. ('subgroup.init', []),
  156. ('subgroup.msg', ['init']),
  157. ('subgroup.main', ['init']),
  158. ('subgroup.contract', ['main']),
  159. ('subgroup.token', ['contract']),
  160. ('subgroup.twexport', ['token']),
  161. ('subgroup.cached', ['token']),
  162. ('subgroup.view', ['cached']),
  163. ('subgroup.label', ['cached']),
  164. ('subgroup.remove', ['cached']),
  165. ('stop', 'stopping daemon'),
  166. )
  167. cmd_subgroups = {
  168. 'misc': (
  169. 'miscellaneous commands',
  170. ('daemon_version', 'mmgen-tool daemon_version'),
  171. ),
  172. 'init': (
  173. 'initializing wallets',
  174. ('wallet_upgrade1', 'upgrading the tracking wallet (v1 -> v2)'),
  175. ('wallet_upgrade2', 'upgrading the tracking wallet (v2 -> v3)'),
  176. ('addrgen', 'generating addresses'),
  177. ('addrimport', 'importing addresses'),
  178. ('addrimport_dev_addr', "importing dev faucet address 'Ox00a329c..'"),
  179. ('fund_dev_address', 'funding the default (Parity dev) address'),
  180. ),
  181. 'msg': (
  182. 'message signing',
  183. ('msgsign_chk', "signing a message (low-level, check against 'eth_sign' RPC call)"),
  184. ('msgcreate', 'creating a message file'),
  185. ('msgsign', 'signing the message file'),
  186. ('msgverify', 'verifying the message file'),
  187. ('msgexport', 'exporting the message file data to JSON for third-party verifier'),
  188. ('msgverify_export', 'verifying the exported JSON data'),
  189. ('msgcreate_raw', 'creating a message file (--msghash-type=raw)'),
  190. ('msgsign_raw', 'signing the message file (msghash_type=raw)'),
  191. ('msgverify_raw', 'verifying the message file (msghash_type=raw)'),
  192. ('msgexport_raw', 'exporting the message file data to JSON (msghash_type=raw)'),
  193. ('msgverify_export_raw', 'verifying the exported JSON data (msghash_type=raw)'),
  194. ),
  195. 'main': (
  196. 'creating, signing, sending and bumping Ethereum transactions',
  197. ('txcreate1', 'creating a transaction (spend from dev address to address :1)'),
  198. ('txview1_raw', 'viewing the raw transaction'),
  199. ('txsign1', 'signing the transaction'),
  200. ('txview1_sig', 'viewing the signed transaction'),
  201. ('tx_status0_bad', 'getting the transaction status'),
  202. ('txsign1_ni', 'signing the transaction (non-interactive)'),
  203. ('txsend1', 'sending the transaction'),
  204. ('bal1', f'the {coin} balance'),
  205. ('txcreate2', 'creating a transaction (spend from dev address to address :11)'),
  206. ('txsign2', 'signing the transaction'),
  207. ('txsend2', 'sending the transaction'),
  208. ('bal2', f'the {coin} balance'),
  209. ('txcreate3', 'creating a transaction (spend from dev address to address :21)'),
  210. ('txsign3', 'signing the transaction'),
  211. ('txsend3', 'sending the transaction'),
  212. ('bal3', f'the {coin} balance'),
  213. ('tx_status1', 'getting the transaction status'),
  214. ('txcreate4', 'creating a transaction (spend from MMGen address, low TX fee)'),
  215. ('txbump', 'bumping the transaction fee'),
  216. ('txsign4', 'signing the transaction'),
  217. ('txsend4', 'sending the transaction'),
  218. ('tx_status1a', 'getting the transaction status'),
  219. ('bal4', f'the {coin} balance'),
  220. ('txcreate5', 'creating a transaction (fund burn address)'),
  221. ('txsign5', 'signing the transaction'),
  222. ('txsend5', 'sending the transaction'),
  223. ('addrimport_burn_addr', 'importing burn address'),
  224. ('bal5', f'the {coin} balance'),
  225. ('add_comment1', 'adding a UTF-8 label (zh)'),
  226. ('chk_comment1', 'checking the label'),
  227. ('add_comment2', 'adding a UTF-8 label (lat+cyr+gr)'),
  228. ('chk_comment2', 'checking the label'),
  229. ('remove_comment', 'removing the label'),
  230. ),
  231. 'contract': (
  232. 'creating and deploying ERC20 tokens',
  233. ('token_compile1', 'compiling ERC20 token #1'),
  234. ('token_deploy1a', 'deploying ERC20 token #1 (SafeMath)'),
  235. ('token_deploy1b', 'deploying ERC20 token #1 (Owned)'),
  236. ('token_deploy1c', 'deploying ERC20 token #1 (Token)'),
  237. ('tx_status2', 'getting the transaction status'),
  238. ('bal6', f'the {coin} balance'),
  239. ('token_compile2', 'compiling ERC20 token #2'),
  240. ('token_deploy2a', 'deploying ERC20 token #2 (SafeMath)'),
  241. ('token_deploy2b', 'deploying ERC20 token #2 (Owned)'),
  242. ('token_deploy2c', 'deploying ERC20 token #2 (Token)'),
  243. ('contract_deploy', 'deploying contract (create,sign,send)'),
  244. ),
  245. 'token': (
  246. 'creating, signing, sending and bumping ERC20 token transactions',
  247. ('token_fund_users', 'transferring token funds from dev to user'),
  248. ('token_user_bals', 'show balances after transfer'),
  249. ('token_addrgen', 'generating token addresses'),
  250. ('token_addrimport_badaddr1', 'importing token addresses (no token address)'),
  251. ('token_addrimport_badaddr2', 'importing token addresses (bad token address)'),
  252. ('token_addrimport_addr1', 'importing token addresses using token address (MM1)'),
  253. ('token_addrimport_addr2', 'importing token addresses using token address (MM2)'),
  254. ('token_addrimport_batch', 'importing token addresses (dummy batch mode) (MM1)'),
  255. ('token_addrimport_sym', 'importing token addresses using token symbol (MM2)'),
  256. ('bal7', f'the {coin} balance'),
  257. ('token_bal1', f'the {coin} balance and token balance'),
  258. ('token_txcreate1', 'creating a token transaction'),
  259. ('token_txview1_raw', 'viewing the raw transaction'),
  260. ('token_txsign1', 'signing the transaction'),
  261. ('token_txsend1', 'sending the transaction'),
  262. ('token_txview1_sig', 'viewing the signed transaction'),
  263. ('tx_status3', 'getting the transaction status'),
  264. ('token_bal2', f'the {coin} balance and token balance'),
  265. ('token_txcreate2', 'creating a token transaction (to burn address)'),
  266. ('token_txbump', 'bumping the transaction fee'),
  267. ('token_txsign2', 'signing the transaction'),
  268. ('token_txsend2', 'sending the transaction'),
  269. ('token_bal3', f'the {coin} balance and token balance'),
  270. ('del_dev_addr', 'deleting the dev address'),
  271. ('bal1_getbalance', f'the {coin} balance (getbalance)'),
  272. ('addrimport_token_burn_addr', 'importing the token burn address'),
  273. ('token_bal4', f'the {coin} balance and token balance'),
  274. ('token_bal_getbalance', 'the token balance (getbalance)'),
  275. ('txcreate_noamt', 'creating a transaction (full amount send)'),
  276. ('txsign_noamt', 'signing the transaction'),
  277. ('txsend_noamt', 'sending the transaction'),
  278. ('bal8', f'the {coin} balance'),
  279. ('token_bal5', 'the token balance'),
  280. ('token_txcreate_noamt', 'creating a token transaction (full amount send)'),
  281. ('token_txsign_noamt', 'signing the transaction'),
  282. ('token_txsend_noamt', 'sending the transaction'),
  283. ('bal9', f'the {coin} balance'),
  284. ('token_bal6', 'the token balance'),
  285. ('listaddresses1', 'listaddresses'),
  286. ('listaddresses2', 'listaddresses minconf=999999999 (ignored)'),
  287. ('listaddresses3', 'listaddresses sort=age (ignored)'),
  288. ('listaddresses4', 'listaddresses showempty=1 sort=age (ignored)'),
  289. ('token_listaddresses1', 'listaddresses --token=mm1'),
  290. ('token_listaddresses2', 'listaddresses --token=mm1 showempty=1'),
  291. ),
  292. 'twexport': (
  293. 'exporting and importing tracking wallet to JSON',
  294. ('twexport_noamt', 'exporting the tracking wallet (include_amts=0)'),
  295. ('twmove', 'moving the tracking wallet'),
  296. ('twimport', 'importing the tracking wallet'),
  297. ('twview7', 'twview (cached_balances=1)'),
  298. ('twview8', 'twview'),
  299. ('twexport', 'exporting the tracking wallet'),
  300. ('tw_chktotal', 'checking total value in tracking wallet dump'),
  301. ('twmove', 'moving the tracking wallet'),
  302. ('twimport', 'importing the tracking wallet'),
  303. ('twcompare', 'comparing imported tracking wallet with original'),
  304. ('edit_json_twdump', 'editing the tracking wallet JSON dump'),
  305. ('twmove', 'moving the tracking wallet'),
  306. ('twimport_nochksum', 'importing the edited tracking wallet JSON dump (ignore_checksum=1)'),
  307. ('token_listaddresses3', 'listaddresses --token=mm1 showempty=1'),
  308. ('token_listaddresses4', 'listaddresses --token=mm2 showempty=1'),
  309. ('twview9', 'twview (check balance)'),
  310. ),
  311. 'cached': (
  312. 'creating and sending transactions using cached balances',
  313. ('twview_cached_balances', 'twview (cached balances)'),
  314. ('token_twview_cached_balances', 'token twview (cached balances)'),
  315. ('txcreate_cached_balances', 'txcreate (cached balances)'),
  316. ('token_txcreate_cached_balances', 'token txcreate (cached balances)'),
  317. ('txdo_cached_balances', 'txdo (cached balances)'),
  318. ('txcreate_refresh_balances', 'refreshing balances'),
  319. ('bal10', f'the {coin} balance'),
  320. ('token_txdo_cached_balances', 'token txdo (cached balances)'),
  321. ('token_txcreate_refresh_balances', 'refreshing token balances'),
  322. ('token_bal7', 'the token balance'),
  323. ),
  324. 'view': (
  325. 'viewing addresses and unspent outputs',
  326. ('twview1', 'twview'),
  327. ('twview2', 'twview wide=1'),
  328. ('twview3', 'twview wide=1 sort=age (ignored)'),
  329. ('twview4', 'twview wide=1 minconf=999999999 (ignored)'),
  330. ('twview5', 'twview wide=1 minconf=0 (ignored)'),
  331. ('token_twview1', 'twview --token=mm1'),
  332. ('token_twview2', 'twview --token=mm1 wide=1'),
  333. ('token_twview3', 'twview --token=mm1 wide=1 sort=age (ignored)'),
  334. ),
  335. 'label': (
  336. 'creating, editing and removing labels',
  337. ('edit_comment1', f'adding label to addr #{del_addrs[0]} in {coin} tracking wallet (zh)'),
  338. ('edit_comment2', f'editing label for addr #{del_addrs[0]} in {coin} tracking wallet (zh)'),
  339. ('edit_comment3', f'adding label to addr #{del_addrs[1]} in {coin} tracking wallet (lat+cyr+gr)'),
  340. ('edit_comment4', f'removing label from addr #{del_addrs[0]} in {coin} tracking wallet'),
  341. ('token_edit_comment1', f'adding label to addr #{del_addrs[0]} in {coin} token tracking wallet'),
  342. ),
  343. 'remove': (
  344. 'removing addresses from tracking wallet',
  345. ('remove_addr1', f'removing addr #{del_addrs[0]} from {coin} tracking wallet'),
  346. ('twview6', 'twview (balance reduced after address removal)'),
  347. ('remove_addr2', f'removing addr #{del_addrs[1]} from {coin} tracking wallet'),
  348. ('token_remove_addr1', f'removing addr #{del_addrs[0]} from {coin} token tracking wallet'),
  349. ('token_remove_addr2', f'removing addr #{del_addrs[1]} from {coin} token tracking wallet'),
  350. ),
  351. }
  352. def __init__(self,trunner,cfgs,spawn):
  353. CmdTestBase.__init__(self,trunner,cfgs,spawn)
  354. if trunner is None:
  355. return
  356. self.txcreate_args = [f'--outdir={self.tmpdir}', '--quiet']
  357. self.eth_args = [f'--outdir={self.tmpdir}', '--quiet']
  358. self.eth_args_noquiet = [f'--outdir={self.tmpdir}']
  359. from mmgen.protocol import init_proto
  360. self.proto = init_proto( cfg, cfg.coin, network='regtest', need_amt=True )
  361. from mmgen.daemon import CoinDaemon
  362. self.daemon = CoinDaemon( cfg, self.proto.coin+'_rt', test_suite=True )
  363. set_vbals(self.daemon.id)
  364. self.using_solc = check_solc_ver()
  365. if not self.using_solc:
  366. omsg(yellow('Using precompiled contract data'))
  367. omsg(blue(f'Coin daemon {self.daemon.id!r} selected'))
  368. self.genesis_fn = joinpath(self.tmpdir,'genesis.json')
  369. self.keystore_dir = os.path.relpath(joinpath(self.daemon.datadir,'keystore'))
  370. write_to_file(
  371. joinpath(self.tmpdir,parity_devkey_fn),
  372. dfl_devkey+'\n' )
  373. self.message = 'attack at dawn'
  374. self.spawn_env['MMGEN_BOGUS_SEND'] = ''
  375. @property
  376. async def rpc(self):
  377. from mmgen.rpc import rpc_init
  378. return await rpc_init(cfg,self.proto)
  379. async def setup(self):
  380. self.spawn('',msg_only=True)
  381. if not self.using_solc:
  382. srcdir = os.path.join(self.tr.repo_root,'test','ref','ethereum','bin')
  383. from shutil import copytree
  384. for d in ('mm1','mm2'):
  385. copytree(os.path.join(srcdir,d),os.path.join(self.tmpdir,d))
  386. d = self.daemon
  387. if d.id in ('geth','erigon'):
  388. self.genesis_setup(d)
  389. set_vt100()
  390. if d.id == 'erigon':
  391. self.write_to_tmpfile('signer_key',self.keystore_data['key']+'\n')
  392. d.usr_coind_args = [
  393. '--miner.sigfile={}'.format(os.path.join(self.tmpdir,'signer_key')),
  394. '--miner.etherbase={}'.format(self.keystore_data['address']) ]
  395. if d.id in ('geth','erigon'):
  396. imsg(' {:19} {}'.format('Cmdline:',' '.join(e for e in d.start_cmd if not 'verbosity' in e)))
  397. if not cfg.no_daemon_autostart:
  398. if not d.id in ('geth','erigon'):
  399. d.stop(silent=True)
  400. d.remove_datadir()
  401. d.start( silent = not (cfg.verbose or cfg.exact_output) )
  402. rpc = await self.rpc
  403. imsg(f'Daemon: {rpc.daemon.coind_name} v{rpc.daemon_version_str}')
  404. return 'ok'
  405. @property
  406. def keystore_data(self):
  407. if not hasattr(self,'_keystore_data'):
  408. wallet_fn = os.path.join( self.keystore_dir, os.listdir(self.keystore_dir)[0] )
  409. from mmgen.proto.eth.misc import decrypt_geth_keystore
  410. key = decrypt_geth_keystore(
  411. cfg = cfg,
  412. wallet_fn = wallet_fn,
  413. passwd = b'' )
  414. with open(wallet_fn) as fh:
  415. res = json.loads(fh.read())
  416. res.update( { 'key': key.hex() } )
  417. self._keystore_data = res
  418. return self._keystore_data
  419. def genesis_setup(self,d):
  420. def make_key():
  421. pwfile = joinpath(self.tmpdir,'account_passwd')
  422. write_to_file(pwfile,'')
  423. run(['rm','-rf',self.keystore_dir])
  424. cmd = f'geth account new --password={pwfile} --lightkdf --keystore {self.keystore_dir}'
  425. cp = run(cmd.split(),stdout=PIPE,stderr=PIPE)
  426. if cp.returncode:
  427. die(1,cp.stderr.decode())
  428. def make_genesis(signer_addr,prealloc_addr):
  429. return {
  430. 'config': {
  431. 'chainId': 1337, # TODO: replace constant with var
  432. 'homesteadBlock': 0,
  433. 'eip150Block': 0,
  434. 'eip155Block': 0,
  435. 'eip158Block': 0,
  436. 'byzantiumBlock': 0,
  437. 'constantinopleBlock': 0,
  438. 'petersburgBlock': 0,
  439. 'istanbulBlock': 0,
  440. 'muirGlacierBlock': 0,
  441. 'berlinBlock': 0,
  442. 'londonBlock': 0,
  443. 'arrowGlacierBlock': 0,
  444. 'grayGlacierBlock': 0,
  445. 'shanghaiTime': 0,
  446. 'terminalTotalDifficulty': 0,
  447. 'terminalTotalDifficultyPassed': True,
  448. 'isDev': True
  449. },
  450. 'nonce': '0x0',
  451. 'timestamp': '0x0',
  452. 'extraData': '0x',
  453. 'gasLimit': '0xaf79e0',
  454. 'difficulty': '0x1',
  455. 'mixHash': '0x0000000000000000000000000000000000000000000000000000000000000000',
  456. 'coinbase': '0x0000000000000000000000000000000000000000',
  457. 'number': '0x0',
  458. 'gasUsed': '0x0',
  459. 'parentHash': '0x0000000000000000000000000000000000000000000000000000000000000000',
  460. 'baseFeePerGas': '0x3b9aca00',
  461. 'excessBlobGas': None,
  462. 'blobGasUsed': None,
  463. 'alloc': {
  464. prealloc_addr: { 'balance': hex(prealloc_amt.toWei()) }
  465. }
  466. }
  467. def init_genesis(fn):
  468. cmd = f'{d.exec_fn} init --datadir {d.datadir} {fn}'
  469. cp = run( cmd.split(), stdout=PIPE, stderr=PIPE )
  470. if cp.returncode:
  471. die(1,cp.stderr.decode())
  472. d.stop(quiet=True)
  473. d.remove_datadir()
  474. imsg(cyan('Initializing Genesis Block:'))
  475. prealloc_amt = self.proto.coin_amt('1_000_000_000')
  476. make_key()
  477. signer_addr = self.keystore_data['address']
  478. self.write_to_tmpfile( 'signer_addr', signer_addr + '\n' )
  479. imsg(f' Keystore: {self.keystore_dir}')
  480. imsg(f' Signer key: {self.keystore_data["key"]}')
  481. imsg(f' Signer address: {signer_addr}')
  482. imsg(f' Faucet: {dfl_devaddr} ({prealloc_amt} ETH)')
  483. imsg(f' Genesis block data: {self.genesis_fn}')
  484. genesis_data = make_genesis(signer_addr,dfl_devaddr)
  485. write_to_file( self.genesis_fn, json.dumps(genesis_data,indent=' ')+'\n' )
  486. init_genesis(self.genesis_fn)
  487. def wallet_upgrade(self,src_file):
  488. if self.proto.coin == 'ETC':
  489. msg(f'skipping test {self.test_name!r} for ETC')
  490. return 'skip'
  491. src_dir = joinpath(ref_dir,'ethereum')
  492. dest_dir = joinpath(self.tr.data_dir,'altcoins',self.proto.coin.lower())
  493. w_from = joinpath(src_dir,src_file)
  494. w_to = joinpath(dest_dir,'tracking-wallet.json')
  495. os.makedirs(dest_dir,mode=0o750,exist_ok=True)
  496. dest = shutil.copy2(w_from,w_to)
  497. assert dest == w_to, dest
  498. t = self.spawn('mmgen-tool', self.eth_args + ['twview'])
  499. t.read()
  500. os.unlink(w_to)
  501. return t
  502. def daemon_version(self):
  503. t = self.spawn('mmgen-tool', self.eth_args + ['daemon_version'])
  504. t.expect('version')
  505. return t
  506. def wallet_upgrade1(self):
  507. return self.wallet_upgrade('tracking-wallet-v1.json')
  508. def wallet_upgrade2(self):
  509. return self.wallet_upgrade('tracking-wallet-v2.json')
  510. def addrgen(self,addrs='1-3,11-13,21-23'):
  511. t = self.spawn('mmgen-addrgen', self.eth_args + [dfl_words_file,addrs])
  512. t.written_to_file('Addresses')
  513. return t
  514. def addrimport(self,ext='21-23]{}.regtest.addrs',expect='9/9',add_args=[],bad_input=False):
  515. ext = ext.format('-α' if cfg.debug_utf8 else '')
  516. fn = self.get_file_with_ext(ext,no_dot=True,delete=False)
  517. t = self.spawn('mmgen-addrimport', self.eth_args[1:-1] + add_args + [fn])
  518. if bad_input:
  519. return t
  520. t.expect('Importing')
  521. t.expect(expect)
  522. return t
  523. def addrimport_one_addr(self,addr=None,extra_args=[]):
  524. t = self.spawn('mmgen-addrimport', self.eth_args[1:] + extra_args + ['--address='+addr])
  525. t.expect('OK')
  526. return t
  527. def addrimport_dev_addr(self):
  528. return self.addrimport_one_addr(addr=dfl_devaddr)
  529. def addrimport_burn_addr(self):
  530. return self.addrimport_one_addr(addr=burn_addr)
  531. def txcreate(
  532. self,
  533. args = [],
  534. menu = [],
  535. acct = '1',
  536. caller = 'txcreate',
  537. interactive_fee = '50G',
  538. fee_info_data = ('0.00105','50'),
  539. no_read = False,
  540. tweaks = []):
  541. fee_info_pat = r'\D{}\D.*{c} .*\D{}\D.*gas price in Gwei'.format( *fee_info_data, c=self.proto.coin )
  542. t = self.spawn('mmgen-'+caller, self.txcreate_args + ['-B'] + args)
  543. t.expect(r'add \[l\]abel, .*?:.','p', regex=True)
  544. t.written_to_file('Account balances listing')
  545. t = self.txcreate_ui_common(
  546. t,
  547. menu = menu,
  548. caller = caller,
  549. input_sels_prompt = 'to spend from',
  550. inputs = acct,
  551. file_desc = 'transaction',
  552. bad_input_sels = True,
  553. interactive_fee = interactive_fee,
  554. fee_info_pat = fee_info_pat,
  555. fee_desc = 'transaction fee or gas price',
  556. add_comment = tx_comment_jp,
  557. tweaks = tweaks)
  558. if not no_read:
  559. t.read()
  560. return t
  561. def txsign(self,ni=False,ext='{}.regtest.rawtx',add_args=[],dev_send=False):
  562. ext = ext.format('-α' if cfg.debug_utf8 else '')
  563. keyfile = joinpath(self.tmpdir,parity_devkey_fn)
  564. txfile = self.get_file_with_ext(ext,no_dot=True)
  565. t = self.spawn(
  566. 'mmgen-txsign',
  567. self.eth_args
  568. + [f'--coin={self.proto.coin}']
  569. + ['--rpc-host=bad_host'] # ETH signing must work without RPC
  570. + add_args
  571. + ([],['--yes'])[ni]
  572. + ([f'--keys-from-file={keyfile}'] if dev_send else [])
  573. + [txfile, dfl_words_file])
  574. return self.txsign_ui_common(t,ni=ni,has_label=True)
  575. def txsend(self,ext='{}.regtest.sigtx',add_args=[]):
  576. ext = ext.format('-α' if cfg.debug_utf8 else '')
  577. txfile = self.get_file_with_ext(ext,no_dot=True)
  578. t = self.spawn('mmgen-txsend', self.eth_args + add_args + [txfile])
  579. self.txsend_ui_common(
  580. t,
  581. quiet = not cfg.debug,
  582. bogus_send = False,
  583. has_label = True)
  584. return t
  585. def txview(self,ext_fs):
  586. ext = ext_fs.format('-α' if cfg.debug_utf8 else '')
  587. txfile = self.get_file_with_ext(ext,no_dot=True)
  588. return self.spawn( 'mmgen-tool',['--verbose','txview',txfile] )
  589. def fund_dev_address(self):
  590. """
  591. For Erigon, fund the default (Parity) dev address from the Erigon dev address
  592. For the others, send a junk TX to keep block counts equal for all daemons
  593. """
  594. dt = namedtuple('data',['devkey_fn','dest','amt'])
  595. d = dt( parity_devkey_fn, burn_addr2, '1' )
  596. t = self.txcreate(
  597. args = [
  598. f'--keys-from-file={joinpath(self.tmpdir,d.devkey_fn)}',
  599. f'{d.dest},{d.amt}',
  600. ],
  601. menu = ['a','r'],
  602. caller = 'txdo',
  603. acct = '1',
  604. no_read = True )
  605. self._do_confirm_send(t,quiet=not cfg.debug,sure=False)
  606. t.read()
  607. self.get_file_with_ext('sigtx',delete_all=True)
  608. return t
  609. def txcreate1(self):
  610. # include one invalid keypress 'X' -- see EthereumTwUnspentOutputs.key_mappings
  611. menu = ['a','d','r','M','X','e','m','m']
  612. args = ['98831F3A:E:1,123.456']
  613. return self.txcreate(args=args,menu=menu,acct='1',tweaks=['confirm_non_mmgen'])
  614. def txview1_raw(self):
  615. return self.txview(ext_fs='{}.regtest.rawtx')
  616. def txsign1(self):
  617. return self.txsign(add_args=['--use-internal-keccak-module'],dev_send=True)
  618. def tx_status0_bad(self):
  619. return self.tx_status(ext='{}.regtest.sigtx',expect_str='neither in mempool nor blockchain',exit_val=1)
  620. def txsign1_ni(self):
  621. return self.txsign(ni=True,dev_send=True)
  622. def txsend1(self):
  623. return self.txsend()
  624. def txview1_sig(self): # do after send so that TxID is displayed
  625. return self.txview(ext_fs='{}.regtest.sigtx')
  626. def bal1(self):
  627. return self.bal(n='1')
  628. def txcreate2(self):
  629. args = ['98831F3A:E:11,1.234']
  630. return self.txcreate(args=args,acct='10',tweaks=['confirm_non_mmgen'])
  631. def txsign2(self):
  632. return self.txsign(ni=True,ext='1.234,50000]{}.regtest.rawtx',dev_send=True)
  633. def txsend2(self):
  634. return self.txsend(ext='1.234,50000]{}.regtest.sigtx')
  635. def bal2(self):
  636. return self.bal(n='2')
  637. def txcreate3(self):
  638. args = ['98831F3A:E:21,2.345']
  639. return self.txcreate(args=args,acct='10',tweaks=['confirm_non_mmgen'])
  640. def txsign3(self):
  641. return self.txsign(ni=True,ext='2.345,50000]{}.regtest.rawtx',dev_send=True)
  642. def txsend3(self):
  643. return self.txsend(ext='2.345,50000]{}.regtest.sigtx')
  644. def bal3(self):
  645. return self.bal(n='3')
  646. def tx_status(self,ext,expect_str,expect_str2='',add_args=[],exit_val=0):
  647. ext = ext.format('-α' if cfg.debug_utf8 else '')
  648. txfile = self.get_file_with_ext(ext,no_dot=True)
  649. t = self.spawn('mmgen-txsend', self.eth_args + add_args + ['--status',txfile])
  650. t.expect(expect_str)
  651. if expect_str2:
  652. t.expect(expect_str2)
  653. t.req_exit_val = exit_val
  654. return t
  655. def tx_status1(self):
  656. return self.tx_status(ext='2.345,50000]{}.regtest.sigtx',expect_str='has 1 confirmation')
  657. def tx_status1a(self):
  658. return self.tx_status(ext='2.345,50000]{}.regtest.sigtx',expect_str='has 2 confirmations')
  659. async def msgsign_chk(self): # NB: Geth only!
  660. def create_signature_mmgen():
  661. key = self.keystore_data['key']
  662. imsg(f'Key: {key}')
  663. from mmgen.proto.eth.misc import ec_sign_message_with_privkey
  664. return ec_sign_message_with_privkey(cfg,self.message,bytes.fromhex(key),'eth_sign')
  665. async def create_signature_rpc():
  666. addr = self.read_from_tmpfile('signer_addr').strip()
  667. imsg(f'Address: {addr}')
  668. rpc = await self.rpc
  669. return await rpc.call(
  670. 'eth_sign',
  671. '0x' + addr,
  672. '0x' + self.message.encode().hex() )
  673. if not self.daemon.id == 'geth':
  674. return 'skip'
  675. self.spawn('',msg_only=True)
  676. sig = '0x' + create_signature_mmgen()
  677. sig_chk = await create_signature_rpc()
  678. # Compare signatures
  679. imsg(f'Message: {self.message}')
  680. imsg(f'Signature: {sig}')
  681. cmp_or_die(sig,sig_chk,'message signatures')
  682. imsg('Geth and MMGen signatures match')
  683. return 'ok'
  684. def msgcreate(self,add_args=[]):
  685. t = self.spawn('mmgen-msg', self.eth_args_noquiet + add_args + [ 'create', self.message, '98831F3A:E:1' ])
  686. t.written_to_file('Unsigned message data')
  687. return t
  688. def msgsign(self):
  689. fn = get_file_with_ext(self.tmpdir,'rawmsg.json')
  690. t = self.spawn('mmgen-msg', self.eth_args_noquiet + [ 'sign', fn, dfl_words_file ])
  691. t.written_to_file('Signed message data')
  692. return t
  693. def msgverify(self,fn=None,msghash_type='eth_sign'):
  694. fn = fn or get_file_with_ext(self.tmpdir,'sigmsg.json')
  695. t = self.spawn('mmgen-msg', self.eth_args_noquiet + [ 'verify', fn ])
  696. t.expect(msghash_type)
  697. t.expect('1 signature verified')
  698. return t
  699. def msgexport(self):
  700. fn = get_file_with_ext(self.tmpdir,'sigmsg.json')
  701. t = self.spawn('mmgen-msg', self.eth_args_noquiet + [ 'export', fn ])
  702. t.written_to_file('Signature data')
  703. return t
  704. def msgverify_export(self):
  705. return self.msgverify(
  706. fn = os.path.join(self.tmpdir,'signatures.json') )
  707. def msgcreate_raw(self):
  708. get_file_with_ext(self.tmpdir,'rawmsg.json',delete_all=True)
  709. return self.msgcreate(add_args=['--msghash-type=raw'])
  710. def msgsign_raw(self):
  711. get_file_with_ext(self.tmpdir,'sigmsg.json',delete_all=True)
  712. return self.msgsign()
  713. def msgverify_raw(self):
  714. return self.msgverify(msghash_type='raw')
  715. def msgexport_raw(self):
  716. get_file_with_ext(self.tmpdir,'signatures.json',no_dot=True,delete_all=True)
  717. return self.msgexport()
  718. def msgverify_export_raw(self):
  719. return self.msgverify(
  720. fn = os.path.join(self.tmpdir,'signatures.json'),
  721. msghash_type = 'raw' )
  722. def txcreate4(self):
  723. return self.txcreate(
  724. args = ['98831F3A:E:2,23.45495'],
  725. acct = '1',
  726. interactive_fee = '40G',
  727. fee_info_data = ('0.00084','40') )
  728. def txbump(self,ext=',40000]{}.regtest.rawtx',fee='50G',add_args=[]):
  729. ext = ext.format('-α' if cfg.debug_utf8 else '')
  730. txfile = self.get_file_with_ext(ext,no_dot=True)
  731. t = self.spawn('mmgen-txbump', self.eth_args + add_args + ['--yes',txfile])
  732. t.expect('or gas price: ',fee+'\n')
  733. return t
  734. def txsign4(self):
  735. return self.txsign(ni=True,ext='.45495,50000]{}.regtest.rawtx',dev_send=True)
  736. def txsend4(self):
  737. return self.txsend(ext='.45495,50000]{}.regtest.sigtx')
  738. def bal4(self):
  739. return self.bal(n='4')
  740. def txcreate5(self):
  741. args = [burn_addr + ','+amt1]
  742. return self.txcreate(args=args,acct='10',tweaks=['confirm_non_mmgen'])
  743. def txsign5(self):
  744. return self.txsign(ni=True,ext=amt1+',50000]{}.regtest.rawtx',dev_send=True)
  745. def txsend5(self):
  746. return self.txsend(ext=amt1+',50000]{}.regtest.sigtx')
  747. def bal5(self):
  748. return self.bal(n='5')
  749. #bal_corr = Decimal('0.0000032') # gas use for token sends varies between ETH and ETC!
  750. bal_corr = Decimal('0.0000000') # update: OpenEthereum team seems to have corrected this
  751. def bal(self,n):
  752. t = self.spawn('mmgen-tool', self.eth_args + ['twview','wide=1'])
  753. text = t.read(strip_color=True)
  754. for b in bals(n):
  755. addr,amt,adj = b if len(b) == 3 else b + (False,)
  756. if adj and self.proto.coin == 'ETC':
  757. amt = str(Decimal(amt) + Decimal(adj[1]) * self.bal_corr)
  758. pat = r'\D{}\D.*\D{}\D'.format( addr, amt.replace('.',r'\.') )
  759. assert re.search(pat,text), pat
  760. ss = f'Total {self.proto.coin}:'
  761. assert re.search(ss,text),ss
  762. return t
  763. def token_bal(self,n=None):
  764. t = self.spawn('mmgen-tool', self.eth_args + ['--token=mm1','twview','wide=1'])
  765. text = t.read(strip_color=True)
  766. for b in token_bals(n):
  767. addr,_amt1,_amt2,adj = b if len(b) == 4 else b + (False,)
  768. if adj and self.proto.coin == 'ETC':
  769. _amt2 = str(Decimal(_amt2) + Decimal(adj[1]) * self.bal_corr)
  770. pat = fr'{addr}\b.*\D{_amt1}\D.*\b{_amt2}\D'
  771. assert re.search(pat,text), pat
  772. ss = 'Total MM1:'
  773. assert re.search(ss,text),ss
  774. return t
  775. def bal_getbalance(self,sid,idx,etc_adj=False,extra_args=[]):
  776. bal1 = token_bals_getbalance(idx)[0]
  777. bal2 = token_bals_getbalance(idx)[1]
  778. bal1 = Decimal(bal1)
  779. if etc_adj and self.proto.coin == 'ETC':
  780. bal1 += self.bal_corr
  781. t = self.spawn('mmgen-tool', self.eth_args + extra_args + ['getbalance'])
  782. t.expect(rf'{sid}:.*'+str(bal1),regex=True)
  783. t.expect(r'Non-MMGen:.*'+bal2,regex=True)
  784. total = strip_ansi_escapes(t.expect_getend(rf'TOTAL {self.proto.coin}')).split()[0]
  785. assert Decimal(bal1) + Decimal(bal2) == Decimal(total)
  786. return t
  787. def add_comment(self,comment,addr='98831F3A:E:3'):
  788. t = self.spawn('mmgen-tool', self.eth_args + ['add_label',addr,comment])
  789. t.expect('Added label.*in tracking wallet',regex=True)
  790. return t
  791. def chk_comment(self,comment_pat,addr='98831F3A:E:3'):
  792. t = self.spawn('mmgen-tool', self.eth_args + ['listaddresses','all_labels=1'])
  793. t.expect(fr'{addr}\b.*{comment_pat}',regex=True)
  794. return t
  795. def add_comment1(self):
  796. return self.add_comment(comment=tw_comment_zh)
  797. def chk_comment1(self):
  798. return self.chk_comment(comment_pat=tw_comment_zh[:3])
  799. def add_comment2(self):
  800. return self.add_comment(comment=tw_comment_lat_cyr_gr)
  801. def chk_comment2(self):
  802. return self.chk_comment(comment_pat=tw_comment_lat_cyr_gr[:3])
  803. def remove_comment(self,addr='98831F3A:E:3'):
  804. t = self.spawn('mmgen-tool', self.eth_args + ['remove_label',addr])
  805. t.expect('Removed label.*in tracking wallet',regex=True)
  806. return t
  807. def token_compile(self,token_data={}):
  808. odir = joinpath(self.tmpdir,token_data['symbol'].lower())
  809. if not self.using_solc:
  810. imsg(f'Using precompiled contract data in {odir}')
  811. return 'skip' if os.path.exists(odir) else False
  812. self.spawn('',msg_only=True)
  813. cmd_args = [f'--{k}={v}' for k,v in list(token_data.items())]
  814. imsg("Compiling solidity token contract '{}' with 'solc'".format( token_data['symbol'] ))
  815. try:
  816. os.mkdir(odir)
  817. except:
  818. pass
  819. cmd = [
  820. 'python3',
  821. 'scripts/create-token.py',
  822. '--coin=' + self.proto.coin,
  823. '--outdir=' + odir
  824. ] + cmd_args + [self.proto.checksummed_addr(dfl_devaddr)]
  825. imsg('Executing: {}'.format( ' '.join(cmd) ))
  826. cp = run(cmd,stdout=DEVNULL,stderr=PIPE)
  827. if cp.returncode != 0:
  828. rmsg('solc failed with the following output:')
  829. die(2,cp.stderr.decode())
  830. imsg('ERC20 token {!r} compiled'.format( token_data['symbol'] ))
  831. return 'ok'
  832. def token_compile1(self):
  833. token_data = { 'name':'MMGen Token 1', 'symbol':'MM1', 'supply':10**26, 'decimals':18 }
  834. return self.token_compile(token_data)
  835. def token_compile2(self):
  836. token_data = { 'name':'MMGen Token 2', 'symbol':'MM2', 'supply':10**18, 'decimals':10 }
  837. return self.token_compile(token_data)
  838. async def get_tx_receipt(self,txid):
  839. from mmgen.tx import NewTX
  840. tx = await NewTX(cfg=cfg,proto=self.proto)
  841. tx.rpc = await self.rpc
  842. res = await tx.get_receipt(txid)
  843. imsg(f'Gas sent: {res.gas_sent.hl():<9} {(res.gas_sent*res.gas_price).hl2(encl="()")}')
  844. imsg(f'Gas used: {res.gas_used.hl():<9} {(res.gas_used*res.gas_price).hl2(encl="()")}')
  845. imsg(f'Gas price: {res.gas_price.hl()}')
  846. if res.gas_used == res.gas_sent:
  847. omsg(yellow('Warning: all gas was used!'))
  848. return res
  849. async def token_deploy(self,num,key,gas,mmgen_cmd='txdo',tx_fee='8G'):
  850. keyfile = joinpath(self.tmpdir,parity_devkey_fn)
  851. fn = joinpath(self.tmpdir,'mm'+str(num),key+'.bin')
  852. args = [
  853. '-B',
  854. f'--fee={tx_fee}',
  855. f'--gas={gas}',
  856. f'--contract-data={fn}',
  857. f'--inputs={dfl_devaddr}',
  858. '--yes',
  859. ]
  860. if mmgen_cmd == 'txdo':
  861. args += ['-k',keyfile]
  862. t = self.spawn( 'mmgen-'+mmgen_cmd, self.eth_args + args)
  863. if mmgen_cmd == 'txcreate':
  864. t.written_to_file('transaction')
  865. ext = '[0,8000]{}.regtest.rawtx'.format('-α' if cfg.debug_utf8 else '')
  866. txfile = self.get_file_with_ext(ext,no_dot=True)
  867. t = self.spawn('mmgen-txsign', self.eth_args + ['--yes','-k',keyfile,txfile],no_msg=True)
  868. self.txsign_ui_common(t,ni=True)
  869. txfile = txfile.replace('.rawtx','.sigtx')
  870. t = self.spawn('mmgen-txsend', self.eth_args + [txfile],no_msg=True)
  871. txid = self.txsend_ui_common(t,
  872. caller = mmgen_cmd,
  873. quiet = mmgen_cmd == 'txdo' or not cfg.debug,
  874. bogus_send = False )
  875. addr = strip_ansi_escapes(t.expect_getend('Contract address: '))
  876. if (await self.get_tx_receipt(txid)).status == 0:
  877. die(2,f'Contract {num}:{key} failed to execute. Aborting')
  878. if key == 'Token':
  879. self.write_to_tmpfile( f'token_addr{num}', addr+'\n' )
  880. imsg(f'\nToken MM{num} deployed!')
  881. return t
  882. async def token_deploy1a(self):
  883. return await self.token_deploy(num=1,key='SafeMath',gas=500_000)
  884. async def token_deploy1b(self):
  885. return await self.token_deploy(num=1,key='Owned', gas=1_000_000)
  886. async def token_deploy1c(self):
  887. return await self.token_deploy(num=1,key='Token', gas=4_000_000,tx_fee='7G')
  888. def tx_status2(self):
  889. return self.tx_status(
  890. ext = self.proto.coin+'[0,7000]{}.regtest.sigtx',
  891. expect_str = 'successfully executed')
  892. def bal6(self):
  893. return self.bal5()
  894. async def token_deploy2a(self):
  895. return await self.token_deploy(num=2,key='SafeMath',gas=500_000)
  896. async def token_deploy2b(self):
  897. return await self.token_deploy(num=2,key='Owned', gas=1_000_000)
  898. async def token_deploy2c(self):
  899. return await self.token_deploy(num=2,key='Token', gas=4_000_000)
  900. async def contract_deploy(self): # test create,sign,send
  901. return await self.token_deploy(num=2,key='SafeMath',gas=500_000,mmgen_cmd='txcreate')
  902. async def token_transfer_ops(self,op,amt=1000,num_tokens=2):
  903. self.spawn('',msg_only=True)
  904. sid = dfl_sid
  905. from mmgen.tool.wallet import tool_cmd
  906. usr_mmaddrs = [f'{sid}:E:{i}' for i in (11,21)][:num_tokens]
  907. from mmgen.proto.eth.contract import ResolvedToken
  908. async def do_transfer(rpc):
  909. for i in range(num_tokens):
  910. tk = await ResolvedToken(
  911. cfg,
  912. self.proto,
  913. rpc,
  914. self.read_from_tmpfile(f'token_addr{i+1}').strip() )
  915. imsg_r( '\n' + await tk.info() )
  916. imsg('dev token balance (pre-send): {}'.format( await tk.get_balance(dfl_devaddr) ))
  917. imsg(f'Sending {amt} {self.proto.dcoin} to address {usr_addrs[i]} ({usr_mmaddrs[i]})')
  918. txid = await tk.transfer(
  919. dfl_devaddr,
  920. usr_addrs[i],
  921. amt,
  922. dfl_devkey,
  923. start_gas = self.proto.coin_amt(60000,'wei'),
  924. gasPrice = self.proto.coin_amt(8,'Gwei') )
  925. if self.daemon.id == 'geth': # yet another Geth bug
  926. await asyncio.sleep(0.5)
  927. if (await self.get_tx_receipt(txid)).status == 0:
  928. die(2,'Transfer of token funds failed. Aborting')
  929. async def show_bals(rpc):
  930. for i in range(num_tokens):
  931. tk = await ResolvedToken(
  932. cfg,
  933. self.proto,
  934. rpc,
  935. self.read_from_tmpfile(f'token_addr{i+1}').strip() )
  936. imsg('Token: {}'.format( await tk.get_symbol() ))
  937. imsg(f'dev token balance: {await tk.get_balance(dfl_devaddr)}')
  938. imsg('usr token balance: {} ({} {})'.format(
  939. await tk.get_balance(usr_addrs[i]),
  940. usr_mmaddrs[i],
  941. usr_addrs[i] ))
  942. def gen_addr(addr):
  943. return tool_cmd(cfg,cmdname='gen_addr',proto=self.proto).gen_addr(addr,dfl_words_file)
  944. silence()
  945. usr_addrs = list(map(gen_addr,usr_mmaddrs))
  946. if op == 'show_bals':
  947. await show_bals(await self.rpc)
  948. elif op == 'do_transfer':
  949. await do_transfer(await self.rpc)
  950. end_silence()
  951. return 'ok'
  952. def token_fund_users(self):
  953. return self.token_transfer_ops(op='do_transfer')
  954. def token_user_bals(self):
  955. return self.token_transfer_ops(op='show_bals')
  956. def token_addrgen(self,num_tokens=2):
  957. t = self.addrgen(addrs='11-13')
  958. if num_tokens == 1:
  959. return t
  960. ok_msg()
  961. return self.addrgen(addrs='21-23')
  962. def token_addrimport_badaddr1(self):
  963. t = self.addrimport(ext='[11-13]{}.regtest.addrs',add_args=['--token=abc'],bad_input=True)
  964. t.expect('could not be resolved')
  965. t.req_exit_val = 2
  966. return t
  967. def token_addrimport_badaddr2(self):
  968. t = self.addrimport(ext='[11-13]{}.regtest.addrs',add_args=['--token='+'00deadbeef'*4],bad_input=True)
  969. t.expect('could not be resolved')
  970. t.req_exit_val = 2
  971. return t
  972. def token_addrimport(self,addr_file,addr_range,expect,extra_args=[]):
  973. token_addr = self.read_from_tmpfile(addr_file).strip()
  974. return self.addrimport(
  975. ext = f'[{addr_range}]{{}}.regtest.addrs',
  976. expect = expect,
  977. add_args = ['--token-addr='+token_addr]+extra_args )
  978. def token_addrimport_addr1(self):
  979. return self.token_addrimport('token_addr1','11-13',expect='3/3')
  980. def token_addrimport_addr2(self):
  981. return self.token_addrimport('token_addr2','21-23',expect='3/3')
  982. def token_addrimport_batch(self):
  983. return self.token_addrimport('token_addr1','11-13',expect='3 addresses',extra_args=['--batch'])
  984. def token_addrimport_sym(self):
  985. return self.addrimport(
  986. ext = '[21-23]{}.regtest.addrs',
  987. expect = '3/3',
  988. add_args = ['--token=MM2'] )
  989. def bal7(self):
  990. return self.bal5()
  991. def token_bal1(self):
  992. return self.token_bal(n='1')
  993. def token_txcreate(self,args=[],token='',inputs='1',fee='50G',file_desc='Unsigned transaction'):
  994. return self.txcreate_ui_common(
  995. self.spawn('mmgen-txcreate', self.txcreate_args + ['--token='+token,'-B','--fee='+fee] + args),
  996. menu = [],
  997. inputs = inputs,
  998. input_sels_prompt = 'to spend from',
  999. add_comment = tx_comment_lat_cyr_gr,
  1000. file_desc = file_desc)
  1001. def token_txsign(self,ext='',token=''):
  1002. return self.txsign(ni=True,ext=ext,add_args=['--token='+token])
  1003. def token_txsend(self,ext='',token=''):
  1004. return self.txsend(ext=ext,add_args=['--token='+token])
  1005. def token_txcreate1(self):
  1006. return self.token_txcreate(args=['98831F3A:E:12,1.23456'],token='mm1')
  1007. def token_txview1_raw(self):
  1008. return self.txview(ext_fs='1.23456,50000]{}.regtest.rawtx')
  1009. def token_txsign1(self):
  1010. return self.token_txsign(ext='1.23456,50000]{}.regtest.rawtx',token='mm1')
  1011. def token_txsend1(self):
  1012. return self.token_txsend(ext='1.23456,50000]{}.regtest.sigtx',token='mm1')
  1013. def token_txview1_sig(self):
  1014. return self.txview(ext_fs='1.23456,50000]{}.regtest.sigtx')
  1015. def tx_status3(self):
  1016. return self.tx_status(
  1017. ext = '1.23456,50000]{}.regtest.sigtx',
  1018. add_args = ['--token=mm1'],
  1019. expect_str = 'successfully executed',
  1020. expect_str2 = 'has 1 confirmation' )
  1021. def token_bal2(self):
  1022. return self.token_bal(n='2')
  1023. def twview(self,args=[],expect_str='',tool_args=[]):
  1024. t = self.spawn('mmgen-tool', self.eth_args + args + ['twview'] + tool_args)
  1025. if expect_str:
  1026. t.expect(expect_str,regex=True)
  1027. return t
  1028. def token_txcreate2(self):
  1029. return self.token_txcreate(args=[burn_addr+','+amt2],token='mm1')
  1030. def token_txbump(self):
  1031. return self.txbump(ext=amt2+',50000]{}.regtest.rawtx',fee='56G',add_args=['--token=mm1'])
  1032. def token_txsign2(self):
  1033. return self.token_txsign(ext=amt2+',50000]{}.regtest.rawtx',token='mm1')
  1034. def token_txsend2(self):
  1035. return self.token_txsend(ext=amt2+',50000]{}.regtest.sigtx',token='mm1')
  1036. def token_bal3(self):
  1037. return self.token_bal(n='3')
  1038. def del_dev_addr(self):
  1039. t = self.spawn('mmgen-tool', self.eth_args + ['remove_address', dfl_devaddr])
  1040. t.expect(f"'{dfl_devaddr}' deleted")
  1041. return t
  1042. def bal1_getbalance(self):
  1043. return self.bal_getbalance(dfl_sid,'1',etc_adj=True)
  1044. def addrimport_token_burn_addr(self):
  1045. return self.addrimport_one_addr(addr=burn_addr,extra_args=['--token=mm1'])
  1046. def token_bal4(self):
  1047. return self.token_bal(n='4')
  1048. def token_bal_getbalance(self):
  1049. return self.bal_getbalance(dfl_sid,'2',extra_args=['--token=mm1'])
  1050. def txcreate_noamt(self):
  1051. return self.txcreate(args=['98831F3A:E:12'])
  1052. def txsign_noamt(self):
  1053. return self.txsign(ext='99.99895,50000]{}.regtest.rawtx')
  1054. def txsend_noamt(self):
  1055. return self.txsend(ext='99.99895,50000]{}.regtest.sigtx')
  1056. def bal8(self):
  1057. return self.bal(n='8')
  1058. def token_bal5(self):
  1059. return self.token_bal(n='5')
  1060. def token_txcreate_noamt(self):
  1061. return self.token_txcreate(args=['98831F3A:E:13'],token='mm1',inputs='2',fee='51G')
  1062. def token_txsign_noamt(self):
  1063. return self.token_txsign(ext='1.23456,51000]{}.regtest.rawtx',token='mm1')
  1064. def token_txsend_noamt(self):
  1065. return self.token_txsend(ext='1.23456,51000]{}.regtest.sigtx',token='mm1')
  1066. def bal9(self):
  1067. return self.bal(n='9')
  1068. def token_bal6(self):
  1069. return self.token_bal(n='6')
  1070. def listaddresses(self,args=[],tool_args=['all_labels=1']):
  1071. return self.spawn('mmgen-tool', self.eth_args + args + ['listaddresses'] + tool_args)
  1072. def listaddresses1(self):
  1073. return self.listaddresses()
  1074. def listaddresses2(self):
  1075. return self.listaddresses(tool_args=['minconf=999999999'])
  1076. def listaddresses3(self):
  1077. return self.listaddresses(tool_args=['sort=amt','reverse=1'])
  1078. def listaddresses4(self):
  1079. return self.listaddresses(tool_args=['sort=age','showempty=0'])
  1080. def token_listaddresses1(self):
  1081. return self.listaddresses(args=['--token=mm1'])
  1082. def token_listaddresses2(self):
  1083. return self.listaddresses(args=['--token=mm1'],tool_args=['showempty=1'])
  1084. def token_listaddresses3(self):
  1085. return self.listaddresses(args=['--token=mm1'],tool_args=['showempty=0'])
  1086. def token_listaddresses4(self):
  1087. return self.listaddresses(args=['--token=mm2'],tool_args=['sort=age','reverse=1'])
  1088. def twview_cached_balances(self):
  1089. return self.twview(args=['--cached-balances'])
  1090. def token_twview_cached_balances(self):
  1091. return self.twview(args=['--token=mm1','--cached-balances'])
  1092. def txcreate_cached_balances(self):
  1093. args = ['--fee=20G','--cached-balances','98831F3A:E:3,0.1276']
  1094. return self.txcreate(args=args,acct='2')
  1095. def token_txcreate_cached_balances(self):
  1096. args=['--cached-balances','--fee=12G','98831F3A:E:12,1.2789']
  1097. return self.token_txcreate(args=args,token='mm1')
  1098. def txdo_cached_balances(
  1099. self,
  1100. acct = '2',
  1101. fee_info_data = ('0.00105','50'),
  1102. add_args = ['98831F3A:E:3,0.4321']):
  1103. t = self.txcreate(
  1104. args = ['--fee=20G','--cached-balances'] + add_args + [dfl_words_file],
  1105. acct = acct,
  1106. caller = 'txdo',
  1107. fee_info_data = fee_info_data,
  1108. no_read = True)
  1109. self._do_confirm_send(t,quiet=not cfg.debug,sure=False)
  1110. return t
  1111. def txcreate_refresh_balances(self):
  1112. return self._txcreate_refresh_balances(
  1113. bals = ['2','3'],
  1114. args = ['-B','--cached-balances','-i'],
  1115. total = vbal5,
  1116. adj_total = True,
  1117. total_coin = None)
  1118. def _txcreate_refresh_balances(self,bals,args,total,adj_total,total_coin):
  1119. if total_coin is None:
  1120. total_coin = self.proto.coin
  1121. if self.proto.coin == 'ETC' and adj_total:
  1122. total = str(Decimal(total) + self.bal_corr)
  1123. t = self.spawn('mmgen-txcreate', self.txcreate_args + args)
  1124. for n in bals:
  1125. t.expect('[R]efresh balance:\b','R')
  1126. t.expect(' main menu): ',n+'\n')
  1127. t.expect('Is this what you want? (y/N): ','y')
  1128. t.expect('[R]efresh balance:\b','q')
  1129. t.expect(rf'Total unspent:.*\D{total}\D.*{total_coin}',regex=True)
  1130. return t
  1131. def bal10(self):
  1132. return self.bal(n='10')
  1133. def token_txdo_cached_balances(self):
  1134. return self.txdo_cached_balances(
  1135. acct = '1',
  1136. fee_info_data = ('0.0026','50'),
  1137. add_args = ['--token=mm1','98831F3A:E:12,43.21'] )
  1138. def token_txcreate_refresh_balances(self):
  1139. return self._txcreate_refresh_balances(
  1140. bals = ['1','2'],
  1141. args = ['--token=mm1','-B','--cached-balances','-i'],
  1142. total = '1000',
  1143. adj_total = False,
  1144. total_coin = 'MM1' )
  1145. def token_bal7(self):
  1146. return self.token_bal(n='7')
  1147. def twview1(self):
  1148. return self.twview()
  1149. def twview2(self):
  1150. return self.twview(tool_args=['wide=1'])
  1151. def twview3(self):
  1152. return self.twview(tool_args=['wide=1','sort=age'])
  1153. def twview4(self):
  1154. return self.twview(tool_args=['wide=1','minconf=999999999'])
  1155. def twview5(self):
  1156. return self.twview(tool_args=['wide=1','minconf=0'])
  1157. def twview6(self):
  1158. return self.twview(expect_str=vbal7)
  1159. def twview7(self):
  1160. return self.twview(args=['--cached-balances'])
  1161. def twview8(self):
  1162. return self.twview()
  1163. def twview9(self):
  1164. return self.twview(args=['--cached-balances'],expect_str=vbal6)
  1165. def token_twview1(self):
  1166. return self.twview(args=['--token=mm1'])
  1167. def token_twview2(self):
  1168. return self.twview(args=['--token=mm1'],tool_args=['wide=1'])
  1169. def token_twview3(self):
  1170. return self.twview(args=['--token=mm1'],tool_args=['wide=1','sort=age'])
  1171. def edit_comment(
  1172. self,
  1173. out_num,
  1174. args = [],
  1175. action = 'l',
  1176. comment_text = None,
  1177. changed = False,
  1178. pexpect_spawn = None):
  1179. t = self.spawn('mmgen-txcreate', self.txcreate_args + args + ['-B','-i'],pexpect_spawn=pexpect_spawn)
  1180. menu_prompt = 'efresh balance:\b'
  1181. t.expect(menu_prompt,'M')
  1182. t.expect(menu_prompt,action)
  1183. t.expect(r'return to main menu): ',out_num+'\n')
  1184. for p,r in (
  1185. ('Enter label text.*: ',comment_text+'\n') if comment_text is not None else (r'\(y/N\): ','y'),
  1186. (r'\(y/N\): ','y') if comment_text == Ctrl_U else (None,None),
  1187. ):
  1188. if p:
  1189. t.expect(p,r,regex=True)
  1190. m = (
  1191. 'Label for account #{} edited' if changed else
  1192. 'Account #{} removed' if action == 'D' else
  1193. 'Label added to account #{}' if comment_text and comment_text != Ctrl_U else
  1194. 'Label removed from account #{}' )
  1195. t.expect(m.format(out_num))
  1196. t.expect(menu_prompt,'M')
  1197. t.expect(menu_prompt,'q')
  1198. t.expect('Total unspent:')
  1199. return t
  1200. def edit_comment1(self):
  1201. return self.edit_comment(out_num=del_addrs[0],comment_text=tw_comment_zh[:3])
  1202. def edit_comment2(self):
  1203. spawn = not sys.platform == 'win32'
  1204. return self.edit_comment(
  1205. out_num = del_addrs[0],
  1206. comment_text = tw_comment_zh[3:],
  1207. changed = True,
  1208. pexpect_spawn = spawn)
  1209. def edit_comment3(self):
  1210. return self.edit_comment(out_num=del_addrs[1],comment_text=tw_comment_lat_cyr_gr)
  1211. def edit_comment4(self):
  1212. if self.skip_for_win():
  1213. return 'skip'
  1214. return self.edit_comment(out_num=del_addrs[0],comment_text=Ctrl_U,pexpect_spawn=True)
  1215. def token_edit_comment1(self):
  1216. return self.edit_comment(out_num='1',comment_text='Token label #1',args=['--token=mm1'])
  1217. def remove_addr1(self):
  1218. return self.edit_comment(out_num=del_addrs[0],action='D')
  1219. def remove_addr2(self):
  1220. return self.edit_comment(out_num=del_addrs[1],action='D')
  1221. def token_remove_addr1(self):
  1222. return self.edit_comment(out_num=del_addrs[0],args=['--token=mm1'],action='D')
  1223. def token_remove_addr2(self):
  1224. return self.edit_comment(out_num=del_addrs[1],args=['--token=mm1'],action='D')
  1225. def twexport_noamt(self):
  1226. return self.twexport(add_args=['include_amts=0'])
  1227. def twexport(self,add_args=[]):
  1228. t = self.spawn('mmgen-tool', self.eth_args + ['twexport'] + add_args)
  1229. t.written_to_file('JSON data')
  1230. return t
  1231. async def twmove(self):
  1232. self.spawn('',msg_only=True)
  1233. from mmgen.tw.ctl import TwCtl
  1234. twctl = await TwCtl(cfg,self.proto)
  1235. imsg('Moving tracking wallet')
  1236. bakfile = twctl.tw_fn + '.bak.json'
  1237. if os.path.exists(bakfile):
  1238. os.unlink(bakfile)
  1239. os.rename( twctl.tw_fn, bakfile )
  1240. return 'ok'
  1241. def twimport(self,add_args=[],expect_str=None):
  1242. from mmgen.tw.json import TwJSON
  1243. fn = joinpath( self.tmpdir, TwJSON.Base(cfg,self.proto).dump_fn )
  1244. t = self.spawn('mmgen-tool',self.eth_args_noquiet + ['twimport',fn] + add_args)
  1245. t.expect('(y/N): ','y')
  1246. if expect_str:
  1247. t.expect(expect_str)
  1248. t.written_to_file('tracking wallet data')
  1249. return t
  1250. def twimport_nochksum(self):
  1251. return self.twimport(add_args=['ignore_checksum=true'],expect_str='ignoring incorrect checksum')
  1252. def tw_chktotal(self):
  1253. self.spawn('',msg_only=True)
  1254. from mmgen.tw.json import TwJSON
  1255. fn = joinpath( self.tmpdir, TwJSON.Base(cfg,self.proto).dump_fn )
  1256. res = json.loads(read_from_file(fn))
  1257. cmp_or_die( res['data']['value'], vbal6, 'value in tracking wallet JSON dump' )
  1258. return 'ok'
  1259. async def twcompare(self):
  1260. self.spawn('',msg_only=True)
  1261. from mmgen.tw.ctl import TwCtl
  1262. twctl = await TwCtl(cfg,self.proto)
  1263. fn = twctl.tw_fn
  1264. imsg('Comparing imported tracking wallet with original')
  1265. data = [json.dumps(json.loads(read_from_file(f)),sort_keys=True) for f in (fn,fn+'.bak.json')]
  1266. cmp_or_die(*data,'tracking wallets')
  1267. return 'ok'
  1268. def edit_json_twdump(self):
  1269. self.spawn('',msg_only=True)
  1270. from mmgen.tw.json import TwJSON
  1271. fn = TwJSON.Base(cfg,self.proto).dump_fn
  1272. text = json.loads(self.read_from_tmpfile(fn))
  1273. token_addr = self.read_from_tmpfile('token_addr2').strip()
  1274. text['data']['entries']['tokens'][token_addr][2][3] = f'edited comment [фубар] [{gr_uc}]'
  1275. self.write_to_tmpfile( fn, json.dumps(text,indent=4) )
  1276. return 'ok'
  1277. def stop(self):
  1278. self.spawn('',msg_only=True)
  1279. if not cfg.no_daemon_stop:
  1280. if not stop_test_daemons(self.proto.coin+'_rt'):
  1281. return False
  1282. set_vt100()
  1283. return 'ok'