ts_ethdev.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2019 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. ts_ethdev.py: Ethdev tests for the test.py test suite
  20. """
  21. import sys,os,subprocess,re,shutil
  22. from decimal import Decimal
  23. from mmgen.globalvars import g
  24. from mmgen.opts import opt
  25. from mmgen.util import die
  26. from mmgen.exception import *
  27. from test.common import *
  28. from test.test_py_d.common import *
  29. del_addrs = ('4','1')
  30. dfl_sid = '98831F3A'
  31. # The Parity dev address with lots of coins. Create with "ethkey -b info ''":
  32. dfl_addr = '00a329c0648769a73afac7f9381e08fb43dbea72'
  33. dfl_addr_chk = '00a329c0648769A73afAc7F9381E08FB43dBEA72'
  34. dfl_privkey = '4d5db4107d237df6a3d58ee5f70ae63d73d7658d4026f2eefd2f204c81682cb7'
  35. burn_addr = 'deadbeef'*5
  36. amt1 = '999999.12345689012345678'
  37. amt2 = '888.111122223333444455'
  38. parity_pid_fn = 'parity.pid'
  39. parity_key_fn = 'parity.devkey'
  40. # Token sends require varying amounts of gas, depending on compiler version
  41. try:
  42. solc_ver = re.search(r'Version:\s*(.*)',
  43. subprocess.Popen(['solc','--version'],stdout=subprocess.PIPE
  44. ).stdout.read().decode()).group(1)
  45. except:
  46. solc_ver = '' # no solc on system - prompt for precompiled v0.5.3 contract files
  47. if re.match(r'\b0.5.1\b',solc_ver): # Raspbian Stretch
  48. vbal1 = '1.2288337'
  49. vbal2 = '99.997085083'
  50. vbal3 = '1.23142165'
  51. vbal4 = '127.0287837'
  52. elif solc_ver == '' or re.match(r'\b0.5.3\b',solc_ver): # Ubuntu Bionic
  53. vbal1 = '1.2288487'
  54. vbal2 = '99.997092733'
  55. vbal3 = '1.23142915'
  56. vbal4 = '127.0287987'
  57. bals = {
  58. '1': [ ('98831F3A:E:1','123.456')],
  59. '2': [ ('98831F3A:E:1','123.456'),('98831F3A:E:11','1.234')],
  60. '3': [ ('98831F3A:E:1','123.456'),('98831F3A:E:11','1.234'),('98831F3A:E:21','2.345')],
  61. '4': [ ('98831F3A:E:1','100'),
  62. ('98831F3A:E:2','23.45495'),
  63. ('98831F3A:E:11','1.234'),
  64. ('98831F3A:E:21','2.345')],
  65. '5': [ ('98831F3A:E:1','100'),
  66. ('98831F3A:E:2','23.45495'),
  67. ('98831F3A:E:11','1.234'),
  68. ('98831F3A:E:21','2.345'),
  69. (burn_addr + '\s+Non-MMGen',amt1)],
  70. '8': [ ('98831F3A:E:1','0'),
  71. ('98831F3A:E:2','23.45495'),
  72. ('98831F3A:E:11',vbal1,'a'),
  73. ('98831F3A:E:12','99.99895'),
  74. ('98831F3A:E:21','2.345'),
  75. (burn_addr + '\s+Non-MMGen',amt1)],
  76. '9': [ ('98831F3A:E:1','0'),
  77. ('98831F3A:E:2','23.45495'),
  78. ('98831F3A:E:11',vbal1,'a'),
  79. ('98831F3A:E:12',vbal2),
  80. ('98831F3A:E:21','2.345'),
  81. (burn_addr + '\s+Non-MMGen',amt1)]
  82. }
  83. token_bals = {
  84. '1': [ ('98831F3A:E:11','1000','1.234')],
  85. '2': [ ('98831F3A:E:11','998.76544',vbal3,'a'),
  86. ('98831F3A:E:12','1.23456','0')],
  87. '3': [ ('98831F3A:E:11','110.654317776666555545',vbal1,'a'),
  88. ('98831F3A:E:12','1.23456','0')],
  89. '4': [ ('98831F3A:E:11','110.654317776666555545',vbal1,'a'),
  90. ('98831F3A:E:12','1.23456','0'),
  91. (burn_addr + '\s+Non-MMGen',amt2,amt1)],
  92. '5': [ ('98831F3A:E:11','110.654317776666555545',vbal1,'a'),
  93. ('98831F3A:E:12','1.23456','99.99895'),
  94. (burn_addr + '\s+Non-MMGen',amt2,amt1)],
  95. '6': [ ('98831F3A:E:11','110.654317776666555545',vbal1,'a'),
  96. ('98831F3A:E:12','0',vbal2),
  97. ('98831F3A:E:13','1.23456','0'),
  98. (burn_addr + '\s+Non-MMGen',amt2,amt1)]
  99. }
  100. token_bals_getbalance = {
  101. '1': (vbal4,'999999.12345689012345678'),
  102. '2': ('111.888877776666555545','888.111122223333444455')
  103. }
  104. from test.test_py_d.ts_base import *
  105. from test.test_py_d.ts_shared import *
  106. class TestSuiteEthdev(TestSuiteBase,TestSuiteShared):
  107. 'Ethereum transacting, token deployment and tracking wallet operations'
  108. networks = ('eth','etc')
  109. passthru_opts = ('coin',)
  110. tmpdir_nums = [22]
  111. cmd_group = (
  112. ('setup', 'Ethereum Parity dev mode tests for coin {} (start parity)'.format(g.coin)),
  113. ('addrgen', 'generating addresses'),
  114. ('addrimport', 'importing addresses'),
  115. ('addrimport_dev_addr', "importing Parity dev address 'Ox00a329c..'"),
  116. ('txcreate1', 'creating a transaction (spend from dev address to address :1)'),
  117. ('txsign1', 'signing the transaction'),
  118. ('txsign1_ni', 'signing the transaction (non-interactive)'),
  119. ('txsend1', 'sending the transaction'),
  120. ('bal1', 'the {} balance'.format(g.coin)),
  121. ('txcreate2', 'creating a transaction (spend from dev address to address :11)'),
  122. ('txsign2', 'signing the transaction'),
  123. ('txsend2', 'sending the transaction'),
  124. ('bal2', 'the {} balance'.format(g.coin)),
  125. ('txcreate3', 'creating a transaction (spend from dev address to address :21)'),
  126. ('txsign3', 'signing the transaction'),
  127. ('txsend3', 'sending the transaction'),
  128. ('bal3', 'the {} balance'.format(g.coin)),
  129. ('tx_status1', 'getting the transaction status'),
  130. ('txcreate4', 'creating a transaction (spend from MMGen address, low TX fee)'),
  131. ('txbump', 'bumping the transaction fee'),
  132. ('txsign4', 'signing the transaction'),
  133. ('txsend4', 'sending the transaction'),
  134. ('bal4', 'the {} balance'.format(g.coin)),
  135. ('txcreate5', 'creating a transaction (fund burn address)'),
  136. ('txsign5', 'signing the transaction'),
  137. ('txsend5', 'sending the transaction'),
  138. ('addrimport_burn_addr',"importing burn address"),
  139. ('bal5', 'the {} balance'.format(g.coin)),
  140. ('add_label', 'adding a UTF-8 label'),
  141. ('chk_label', 'the label'),
  142. ('remove_label', 'removing the label'),
  143. ('token_compile1', 'compiling ERC20 token #1'),
  144. ('token_deploy1a', 'deploying ERC20 token #1 (SafeMath)'),
  145. ('token_deploy1b', 'deploying ERC20 token #1 (Owned)'),
  146. ('token_deploy1c', 'deploying ERC20 token #1 (Token)'),
  147. ('tx_status2', 'getting the transaction status'),
  148. ('bal6', 'the {} balance'.format(g.coin)),
  149. ('token_compile2', 'compiling ERC20 token #2'),
  150. ('token_deploy2a', 'deploying ERC20 token #2 (SafeMath)'),
  151. ('token_deploy2b', 'deploying ERC20 token #2 (Owned)'),
  152. ('token_deploy2c', 'deploying ERC20 token #2 (Token)'),
  153. ('contract_deploy', 'deploying contract (create,sign,send)'),
  154. ('token_fund_users', 'transferring token funds from dev to user'),
  155. ('token_user_bals', 'show balances after transfer'),
  156. ('token_addrgen', 'generating token addresses'),
  157. ('token_addrimport_badaddr1','importing token addresses (no token address)'),
  158. ('token_addrimport_badaddr2','importing token addresses (bad token address)'),
  159. ('token_addrimport', 'importing token addresses'),
  160. ('bal7', 'the {} balance'.format(g.coin)),
  161. ('token_bal1', 'the {} balance and token balance'.format(g.coin)),
  162. ('token_txcreate1', 'creating a token transaction'),
  163. ('token_txsign1', 'signing the transaction'),
  164. ('token_txsend1', 'sending the transaction'),
  165. ('token_bal2', 'the {} balance and token balance'.format(g.coin)),
  166. ('token_txcreate2', 'creating a token transaction (to burn address)'),
  167. ('token_txbump', 'bumping the transaction fee'),
  168. ('token_txsign2', 'signing the transaction'),
  169. ('token_txsend2', 'sending the transaction'),
  170. ('token_bal3', 'the {} balance and token balance'.format(g.coin)),
  171. ('del_dev_addr', "deleting the dev address"),
  172. ('bal1_getbalance', 'the {} balance (getbalance)'.format(g.coin)),
  173. ('addrimport_token_burn_addr',"importing the token burn address"),
  174. ('token_bal4', 'the {} balance and token balance'.format(g.coin)),
  175. ('token_bal_getbalance','the token balance (getbalance)'),
  176. ('txcreate_noamt', 'creating a transaction (full amount send)'),
  177. ('txsign_noamt', 'signing the transaction'),
  178. ('txsend_noamt', 'sending the transaction'),
  179. ('bal8', 'the {} balance'.format(g.coin)),
  180. ('token_bal5', 'the token balance'),
  181. ('token_txcreate_noamt', 'creating a token transaction (full amount send)'),
  182. ('token_txsign_noamt', 'signing the transaction'),
  183. ('token_txsend_noamt', 'sending the transaction'),
  184. ('bal9', 'the {} balance'.format(g.coin)),
  185. ('token_bal6', 'the token balance'),
  186. ('listaddresses1', 'listaddresses'),
  187. ('listaddresses2', 'listaddresses minconf=999999999 (ignored)'),
  188. ('listaddresses3', 'listaddresses sort=age (ignored)'),
  189. ('listaddresses4', 'listaddresses showempty=1 sort=age (ignored)'),
  190. ('token_listaddresses1','listaddresses --token=mm1'),
  191. ('token_listaddresses2','listaddresses --token=mm1 showempty=1'),
  192. ('twview1','twview'),
  193. ('twview2','twview wide=1'),
  194. ('twview3','twview wide=1 sort=age (ignored)'),
  195. ('twview4','twview wide=1 minconf=999999999 (ignored)'),
  196. ('twview5','twview wide=1 minconf=0 (ignored)'),
  197. ('twview6','twview age_fmt=days (ignored)'),
  198. ('token_twview1','twview --token=mm1'),
  199. ('token_twview2','twview --token=mm1 wide=1'),
  200. ('token_twview3','twview --token=mm1 wide=1 sort=age (ignored)'),
  201. ('edit_label1','adding label to addr #{} in {} tracking wallet'.format(del_addrs[0],g.coin)),
  202. ('edit_label2','adding label to addr #{} in {} tracking wallet'.format(del_addrs[1],g.coin)),
  203. ('edit_label3','removing label from addr #{} in {} tracking wallet'.format(del_addrs[0],g.coin)),
  204. ('remove_addr1','removing addr #{} from {} tracking wallet'.format(del_addrs[0],g.coin)),
  205. ('remove_addr2','removing addr #{} from {} tracking wallet'.format(del_addrs[1],g.coin)),
  206. ('remove_token_addr1','removing addr #{} from {} token tracking wallet'.format(del_addrs[0],g.coin)),
  207. ('remove_token_addr2','removing addr #{} from {} token tracking wallet'.format(del_addrs[1],g.coin)),
  208. ('stop', 'stopping parity'),
  209. )
  210. @property
  211. def eth_args(self):
  212. return ['--outdir={}'.format(self.tmpdir),'--coin='+g.coin,'--rpc-port=8549','--quiet']
  213. def setup(self):
  214. self.spawn('',msg_only=True)
  215. os.environ['MMGEN_BOGUS_WALLET_DATA'] = ''
  216. opts = ['--ports-shift=4','--config=dev']
  217. lf_arg = '--log-file=' + joinpath(self.tr.data_dir,'parity.log')
  218. if g.platform == 'win':
  219. dc_dir = joinpath(os.environ['LOCALAPPDATA'],'Parity','Ethereum','chains','DevelopmentChain')
  220. shutil.rmtree(dc_dir,ignore_errors=True)
  221. m1 = 'Please start parity on another terminal as follows:\n'
  222. m2 = ['parity',lf_arg] + opts
  223. m3 = '\nPress ENTER to continue: '
  224. my_raw_input(m1 + ' '.join(m2) + m3)
  225. elif subprocess.call(['which','parity'],stdout=subprocess.PIPE) == 0:
  226. ss = 'parity.*--log-file=test/data_dir.*/parity.log' # allow for UTF8_DEBUG
  227. try:
  228. pid = subprocess.check_output(['pgrep','-af',ss]).split()[0]
  229. os.kill(int(pid),9)
  230. except: pass
  231. # '--base-path' doesn't work together with daemon mode, so we have to clobber the main dev chain
  232. dc_dir = joinpath(os.environ['HOME'],'.local/share/io.parity.ethereum/chains/DevelopmentChain')
  233. shutil.rmtree(dc_dir,ignore_errors=True)
  234. bdir = joinpath(self.tr.data_dir,'parity')
  235. try: os.mkdir(bdir)
  236. except: pass
  237. redir = None if opt.exact_output else subprocess.PIPE
  238. pidfile = joinpath(self.tmpdir,parity_pid_fn)
  239. subprocess.check_call(['parity',lf_arg] + opts + ['daemon',pidfile],stderr=redir,stdout=redir)
  240. time.sleep(3) # race condition
  241. pid = self.read_from_tmpfile(parity_pid_fn)
  242. elif subprocess.call('netstat -tnl | grep -q 127.0.0.1:8549',shell=True) == 0:
  243. m1 = 'No parity executable found on system, but port 8549 is active!'
  244. m2 = 'Before continuing, you should probably run the command'
  245. m3 = 'test/test.py -X setup ethdev'
  246. m4 = 'on the remote host.'
  247. sys.stderr.write('{}\n{}\n{} {}\n'.format(m1,m2,cyan(m3),m4))
  248. confirm_continue()
  249. else:
  250. die(1,'No parity executable found!')
  251. return 'ok'
  252. def addrgen(self,addrs='1-3,11-13,21-23'):
  253. from mmgen.addr import MMGenAddrType
  254. t = self.spawn('mmgen-addrgen', self.eth_args + [dfl_words_file,addrs])
  255. t.written_to_file('Addresses')
  256. t.read()
  257. return t
  258. def addrimport(self,ext='21-23]{}.addrs',expect='9/9',add_args=[],bad_input=False):
  259. ext = ext.format('-α' if g.debug_utf8 else '')
  260. fn = self.get_file_with_ext(ext,no_dot=True,delete=False)
  261. t = self.spawn('mmgen-addrimport', self.eth_args[1:] + add_args + [fn])
  262. if bad_input:
  263. t.read()
  264. t.req_exit_val = 2
  265. return t
  266. if g.debug: t.expect("Type uppercase 'YES' to confirm: ",'YES\n')
  267. t.expect('Importing')
  268. t.expect(expect)
  269. t.read()
  270. return t
  271. def addrimport_one_addr(self,addr=None,extra_args=[]):
  272. t = self.spawn('mmgen-addrimport', self.eth_args[1:] + extra_args + ['--address='+addr])
  273. t.expect('OK')
  274. return t
  275. def addrimport_dev_addr(self):
  276. return self.addrimport_one_addr(addr=dfl_addr)
  277. def addrimport_burn_addr(self):
  278. return self.addrimport_one_addr(addr=burn_addr)
  279. def txcreate(self,args=[],menu=[],acct='1',non_mmgen_inputs=0,
  280. interactive_fee = '50G',
  281. eth_fee_res = None,
  282. fee_res_fs = '0.00105 {} (50 gas price in Gwei)',
  283. fee_desc = 'gas price' ):
  284. fee_res = fee_res_fs.format(g.coin)
  285. t = self.spawn('mmgen-txcreate', self.eth_args + ['-B'] + args)
  286. t.expect(r'add \[l\]abel, .*?:.','p', regex=True)
  287. t.written_to_file('Account balances listing')
  288. return self.txcreate_ui_common( t, menu=menu,
  289. input_sels_prompt = 'to spend from',
  290. inputs = acct,
  291. file_desc = 'Ethereum transaction',
  292. bad_input_sels = True,
  293. non_mmgen_inputs = non_mmgen_inputs,
  294. interactive_fee = interactive_fee,
  295. fee_res = fee_res,
  296. fee_desc = fee_desc,
  297. eth_fee_res = eth_fee_res,
  298. add_comment = ref_tx_label_jp )
  299. def txsign(self,ni=False,ext='{}.rawtx',add_args=[]):
  300. ext = ext.format('-α' if g.debug_utf8 else '')
  301. keyfile = joinpath(self.tmpdir,parity_key_fn)
  302. write_to_file(keyfile,dfl_privkey+'\n')
  303. txfile = self.get_file_with_ext(ext,no_dot=True)
  304. t = self.spawn( 'mmgen-txsign',
  305. self.eth_args
  306. + add_args
  307. + ([],['--yes'])[ni]
  308. + ['-k', keyfile, txfile, dfl_words_file] )
  309. return self.txsign_ui_common(t,ni=ni,has_label=True)
  310. def txsend(self,ni=False,bogus_send=False,ext='{}.sigtx',add_args=[]):
  311. ext = ext.format('-α' if g.debug_utf8 else '')
  312. txfile = self.get_file_with_ext(ext,no_dot=True)
  313. if not bogus_send: os.environ['MMGEN_BOGUS_SEND'] = ''
  314. t = self.spawn('mmgen-txsend', self.eth_args + add_args + [txfile])
  315. if not bogus_send: os.environ['MMGEN_BOGUS_SEND'] = '1'
  316. txid = self.txsend_ui_common(t,quiet=True,bogus_send=bogus_send,has_label=True)
  317. return t
  318. def txcreate1(self):
  319. # valid_keypresses = EthereumTwUnspentOutputs.key_mappings.keys()
  320. menu = ['a','d','r','M','D','e','m','m'] # include one invalid keypress, 'D'
  321. args = ['98831F3A:E:1,123.456']
  322. return self.txcreate(args=args,menu=menu,acct='1',non_mmgen_inputs=1)
  323. def txsign1(self): return self.txsign(add_args=['--use-internal-keccak-module'])
  324. def txsign1_ni(self): return self.txsign(ni=True)
  325. def txsend1(self): return self.txsend()
  326. def bal1(self): return self.bal(n='1')
  327. def txcreate2(self):
  328. args = ['98831F3A:E:11,1.234']
  329. return self.txcreate(args=args,acct='10',non_mmgen_inputs=1)
  330. def txsign2(self): return self.txsign(ni=True,ext='1.234,50000]{}.rawtx')
  331. def txsend2(self): return self.txsend(ext='1.234,50000]{}.sigtx')
  332. def bal2(self): return self.bal(n='2')
  333. def txcreate3(self):
  334. args = ['98831F3A:E:21,2.345']
  335. return self.txcreate(args=args,acct='10',non_mmgen_inputs=1)
  336. def txsign3(self): return self.txsign(ni=True,ext='2.345,50000]{}.rawtx')
  337. def txsend3(self): return self.txsend(ext='2.345,50000]{}.sigtx')
  338. def bal3(self): return self.bal(n='3')
  339. def tx_status(self,ext,expect_str):
  340. ext = ext.format('-α' if g.debug_utf8 else '')
  341. txfile = self.get_file_with_ext(ext,no_dot=True)
  342. t = self.spawn('mmgen-txsend', self.eth_args + ['--status',txfile])
  343. t.expect(expect_str)
  344. t.read()
  345. return t
  346. def tx_status1(self):
  347. return self.tx_status(ext='2.345,50000]{}.sigtx',expect_str='has 1 confirmation')
  348. def txcreate4(self):
  349. args = ['98831F3A:E:2,23.45495']
  350. interactive_fee='40G'
  351. fee_res_fs='0.00084 {} (40 gas price in Gwei)'
  352. return self.txcreate( args = args,
  353. acct = '1',
  354. non_mmgen_inputs = 0,
  355. interactive_fee = interactive_fee,
  356. fee_res_fs = fee_res_fs,
  357. eth_fee_res = True)
  358. def txbump(self,ext=',40000]{}.rawtx',fee='50G',add_args=[]):
  359. ext = ext.format('-α' if g.debug_utf8 else '')
  360. txfile = self.get_file_with_ext(ext,no_dot=True)
  361. t = self.spawn('mmgen-txbump', self.eth_args + add_args + ['--yes',txfile])
  362. t.expect('or gas price: ',fee+'\n')
  363. t.read()
  364. return t
  365. def txsign4(self): return self.txsign(ni=True,ext='.45495,50000]{}.rawtx')
  366. def txsend4(self): return self.txsend(ext='.45495,50000]{}.sigtx')
  367. def bal4(self): return self.bal(n='4')
  368. def txcreate5(self):
  369. args = [burn_addr + ','+amt1]
  370. return self.txcreate(args=args,acct='10',non_mmgen_inputs=1)
  371. def txsign5(self): return self.txsign(ni=True,ext=amt1+',50000]{}.rawtx')
  372. def txsend5(self): return self.txsend(ext=amt1+',50000]{}.sigtx')
  373. def bal5(self): return self.bal(n='5')
  374. bal_corr = Decimal('0.0000032') # gas use for token sends varies between ETH and ETC!
  375. def bal(self,n=None):
  376. t = self.spawn('mmgen-tool', self.eth_args + ['twview','wide=1'])
  377. for b in bals[n]:
  378. addr,amt,adj = b if len(b) == 3 else b + (False,)
  379. if adj and g.coin == 'ETC': amt = str(Decimal(amt) + self.bal_corr)
  380. pat = r'{}\s+{}\s'.format(addr,amt.replace('.',r'\.'))
  381. t.expect(pat,regex=True)
  382. t.read()
  383. return t
  384. def token_bal(self,n=None):
  385. t = self.spawn('mmgen-tool', self.eth_args + ['--token=mm1','twview','wide=1'])
  386. for b in token_bals[n]:
  387. addr,_amt1,_amt2,adj = b if len(b) == 4 else b + (False,)
  388. if adj and g.coin == 'ETC': _amt2 = str(Decimal(_amt2) + self.bal_corr)
  389. pat = r'{}\s+{}\s+{}\s'.format(addr,_amt1.replace('.',r'\.'),_amt2.replace('.',r'\.'))
  390. t.expect(pat,regex=True)
  391. t.read()
  392. return t
  393. def bal_getbalance(self,idx,etc_adj=False,extra_args=[]):
  394. bal1 = token_bals_getbalance[idx][0]
  395. bal2 = token_bals_getbalance[idx][1]
  396. bal1 = Decimal(bal1)
  397. if etc_adj and g.coin == 'ETC': bal1 += self.bal_corr
  398. t = self.spawn('mmgen-tool', self.eth_args + extra_args + ['getbalance'])
  399. t.expect(r'\n[0-9A-F]{8}: .* '+str(bal1),regex=True)
  400. t.expect(r'\nNon-MMGen: .* '+bal2,regex=True)
  401. total = t.expect_getend(r'\nTOTAL:\s+',regex=True).split()[0]
  402. t.read()
  403. assert Decimal(bal1) + Decimal(bal2) == Decimal(total)
  404. return t
  405. def add_label(self,addr='98831F3A:E:3',lbl=utf8_label):
  406. t = self.spawn('mmgen-tool', self.eth_args + ['add_label',addr,lbl])
  407. t.expect('Added label.*in tracking wallet',regex=True)
  408. return t
  409. def chk_label(self,addr='98831F3A:E:3',label_pat=utf8_label_pat):
  410. t = self.spawn('mmgen-tool', self.eth_args + ['listaddresses','all_labels=1'])
  411. t.expect(r'{}\s+\S{{30}}\S+\s+{}\s+'.format(addr,(label_pat or label)),regex=True)
  412. return t
  413. def remove_label(self,addr='98831F3A:E:3'):
  414. t = self.spawn('mmgen-tool', self.eth_args + ['remove_label',addr])
  415. t.expect('Removed label.*in tracking wallet',regex=True)
  416. return t
  417. def token_compile(self,token_data={}):
  418. odir = joinpath(self.tmpdir,token_data['symbol'].lower())
  419. if self.skip_for_win():
  420. m ='Copy solc v0.5.3 contract data for token {} to directory {} and hit ENTER: '
  421. input(m.format(token_data['symbol'],odir))
  422. return 'skip'
  423. self.spawn('',msg_only=True)
  424. cmd_args = ['--{}={}'.format(k,v) for k,v in list(token_data.items())]
  425. imsg("Compiling solidity token contract '{}' with 'solc'".format(token_data['symbol']))
  426. try: os.mkdir(odir)
  427. except: pass
  428. cmd = ['scripts/create-token.py','--coin='+g.coin,'--outdir='+odir] + cmd_args + [dfl_addr_chk]
  429. imsg("Executing: {}".format(' '.join(cmd)))
  430. subprocess.check_output(cmd,stderr=subprocess.STDOUT)
  431. imsg("ERC20 token '{}' compiled".format(token_data['symbol']))
  432. return 'ok'
  433. def token_compile1(self):
  434. token_data = { 'name':'MMGen Token 1', 'symbol':'MM1', 'supply':10**26, 'decimals':18 }
  435. return self.token_compile(token_data)
  436. def token_compile2(self):
  437. token_data = { 'name':'MMGen Token 2', 'symbol':'MM2', 'supply':10**18, 'decimals':10 }
  438. return self.token_compile(token_data)
  439. def _rpc_init(self):
  440. g.proto.rpc_port = 8549
  441. rpc_init()
  442. def token_deploy(self,num,key,gas,mmgen_cmd='txdo',tx_fee='8G'):
  443. self._rpc_init()
  444. keyfile = joinpath(self.tmpdir,parity_key_fn)
  445. fn = joinpath(self.tmpdir,'mm'+str(num),key+'.bin')
  446. os.environ['MMGEN_BOGUS_SEND'] = ''
  447. args = ['-B',
  448. '--tx-fee='+tx_fee,
  449. '--tx-gas={}'.format(gas),
  450. '--contract-data='+fn,
  451. '--inputs='+dfl_addr,
  452. '--yes' ]
  453. if mmgen_cmd == 'txdo': args += ['-k',keyfile]
  454. t = self.spawn( 'mmgen-'+mmgen_cmd, self.eth_args + args)
  455. if mmgen_cmd == 'txcreate':
  456. t.written_to_file('Ethereum transaction')
  457. ext = '[0,8000]{}.rawtx'.format('-α' if g.debug_utf8 else '')
  458. txfile = self.get_file_with_ext(ext,no_dot=True)
  459. t = self.spawn('mmgen-txsign', self.eth_args + ['--yes','-k',keyfile,txfile],no_msg=True)
  460. self.txsign_ui_common(t,ni=True)
  461. txfile = txfile.replace('.rawtx','.sigtx')
  462. t = self.spawn('mmgen-txsend', self.eth_args + [txfile],no_msg=True)
  463. os.environ['MMGEN_BOGUS_SEND'] = '1'
  464. txid = self.txsend_ui_common(t,caller=mmgen_cmd,quiet=True,bogus_send=False)
  465. addr = t.expect_getend('Contract address: ')
  466. from mmgen.altcoins.eth.tx import EthereumMMGenTX as etx
  467. assert etx.get_exec_status(txid,True) != 0,(
  468. "Contract '{}:{}' failed to execute. Aborting".format(num,key))
  469. if key == 'Token':
  470. self.write_to_tmpfile('token_addr{}'.format(num),addr+'\n')
  471. imsg('\nToken MM{} deployed!'.format(num))
  472. return t
  473. def token_deploy1a(self): return self.token_deploy(num=1,key='SafeMath',gas=200000)
  474. def token_deploy1b(self): return self.token_deploy(num=1,key='Owned',gas=250000)
  475. def token_deploy1c(self): return self.token_deploy(num=1,key='Token',gas=1100000,tx_fee='7G')
  476. def tx_status2(self):
  477. return self.tx_status(ext=g.coin+'[0,7000]{}.sigtx',expect_str='successfully executed')
  478. def bal6(self): return self.bal5()
  479. def token_deploy2a(self): return self.token_deploy(num=2,key='SafeMath',gas=200000)
  480. def token_deploy2b(self): return self.token_deploy(num=2,key='Owned',gas=250000)
  481. def token_deploy2c(self): return self.token_deploy(num=2,key='Token',gas=1100000)
  482. def contract_deploy(self): # test create,sign,send
  483. return self.token_deploy(num=2,key='SafeMath',gas=1100000,mmgen_cmd='txcreate')
  484. def token_transfer_ops(self,op,amt=1000):
  485. self.spawn('',msg_only=True)
  486. sid = dfl_sid
  487. from mmgen.tool import MMGenToolCmd
  488. usr_mmaddrs = ['{}:E:{}'.format(sid,i) for i in (11,21)]
  489. usr_addrs = [MMGenToolCmd().gen_addr(addr,dfl_words_file) for addr in usr_mmaddrs]
  490. self._rpc_init()
  491. from mmgen.altcoins.eth.contract import Token
  492. from mmgen.altcoins.eth.tx import EthereumMMGenTX as etx
  493. def do_transfer():
  494. for i in range(2):
  495. tk = Token(self.read_from_tmpfile('token_addr{}'.format(i+1)).strip())
  496. imsg_r('\n'+tk.info())
  497. imsg('dev token balance (pre-send): {}'.format(tk.balance(dfl_addr)))
  498. imsg('Sending {} {} to address {} ({})'.format(amt,g.coin,usr_addrs[i],usr_mmaddrs[i]))
  499. from mmgen.obj import ETHAmt
  500. txid = tk.transfer( dfl_addr, usr_addrs[i], amt, dfl_privkey,
  501. start_gas = ETHAmt(60000,'wei'),
  502. gasPrice = ETHAmt(8,'Gwei') )
  503. assert etx.get_exec_status(txid,True) != 0,'Transfer of token funds failed. Aborting'
  504. def show_bals():
  505. for i in range(2):
  506. tk = Token(self.read_from_tmpfile('token_addr{}'.format(i+1)).strip())
  507. imsg('Token: {}'.format(tk.symbol()))
  508. imsg('dev token balance: {}'.format(tk.balance(dfl_addr)))
  509. imsg('usr token balance: {} ({} {})'.format(
  510. tk.balance(usr_addrs[i]),usr_mmaddrs[i],usr_addrs[i]))
  511. silence()
  512. if op == 'show_bals': show_bals()
  513. elif op == 'do_transfer': do_transfer()
  514. end_silence()
  515. return 'ok'
  516. def token_fund_users(self):
  517. return self.token_transfer_ops(op='do_transfer')
  518. def token_user_bals(self):
  519. return self.token_transfer_ops(op='show_bals')
  520. def token_addrgen(self):
  521. self.addrgen(addrs='11-13')
  522. ok_msg()
  523. return self.addrgen(addrs='21-23')
  524. def token_addrimport_badaddr1(self):
  525. t = self.addrimport(ext='[11-13]{}.addrs',add_args=['--token=abc'],bad_input=True)
  526. t.req_exit_val = 2
  527. return t
  528. def token_addrimport_badaddr2(self):
  529. t = self.addrimport(ext='[11-13]{}.addrs',add_args=['--token='+'00deadbeef'*4],bad_input=True)
  530. t.req_exit_val = 2
  531. return t
  532. def token_addrimport(self):
  533. for n,r in ('1','11-13'),('2','21-23'):
  534. tk_addr = self.read_from_tmpfile('token_addr'+n).strip()
  535. t = self.addrimport(ext='['+r+']{}.addrs',expect='3/3',add_args=['--token='+tk_addr])
  536. t.p.wait()
  537. ok_msg()
  538. t.skip_ok = True
  539. return t
  540. def bal7(self): return self.bal5()
  541. def token_bal1(self): return self.token_bal(n='1')
  542. def token_txcreate(self,args=[],token='',inputs='1',fee='50G'):
  543. t = self.spawn('mmgen-txcreate', self.eth_args + ['--token='+token,'-B','--tx-fee='+fee] + args)
  544. return self.txcreate_ui_common( t,
  545. menu = [],
  546. inputs = inputs,
  547. input_sels_prompt = 'to spend from',
  548. file_desc = 'Ethereum token transaction',
  549. add_comment = ref_tx_label_lat_cyr_gr)
  550. def token_txsign(self,ext='',token=''):
  551. return self.txsign(ni=True,ext=ext,add_args=['--token='+token])
  552. def token_txsend(self,ext='',token=''):
  553. return self.txsend(ext=ext,add_args=['--token=mm1'])
  554. def token_txcreate1(self):
  555. return self.token_txcreate(args=['98831F3A:E:12,1.23456'],token='mm1')
  556. def token_txsign1(self):
  557. return self.token_txsign(ext='1.23456,50000]{}.rawtx',token='mm1')
  558. def token_txsend1(self):
  559. return self.token_txsend(ext='1.23456,50000]{}.sigtx',token='mm1')
  560. def token_bal2(self):
  561. return self.token_bal(n='2')
  562. def twview(self,args=[],expect_str='',tool_args=[],exit_val=0):
  563. t = self.spawn('mmgen-tool', self.eth_args + args + ['twview'] + tool_args)
  564. if expect_str:
  565. t.expect(expect_str,regex=True)
  566. t.read()
  567. t.req_exit_val = exit_val
  568. return t
  569. def token_txcreate2(self):
  570. return self.token_txcreate(args=[burn_addr+','+amt2],token='mm1')
  571. def token_txbump(self):
  572. return self.txbump(ext=amt2+',50000]{}.rawtx',fee='56G',add_args=['--token=mm1'])
  573. def token_txsign2(self):
  574. return self.token_txsign(ext=amt2+',50000]{}.rawtx',token='mm1')
  575. def token_txsend2(self):
  576. return self.token_txsend(ext=amt2+',50000]{}.sigtx',token='mm1')
  577. def token_bal3(self):
  578. return self.token_bal(n='3')
  579. def del_dev_addr(self):
  580. t = self.spawn('mmgen-tool', self.eth_args + ['remove_address',dfl_addr])
  581. t.read() # TODO
  582. return t
  583. def bal1_getbalance(self):
  584. return self.bal_getbalance('1',etc_adj=True)
  585. def addrimport_token_burn_addr(self):
  586. return self.addrimport_one_addr(addr=burn_addr,extra_args=['--token=mm1'])
  587. def token_bal4(self):
  588. return self.token_bal(n='4')
  589. def token_bal_getbalance(self):
  590. return self.bal_getbalance('2',extra_args=['--token=mm1'])
  591. def txcreate_noamt(self):
  592. return self.txcreate(args=['98831F3A:E:12'],eth_fee_res=True)
  593. def txsign_noamt(self):
  594. return self.txsign(ext='99.99895,50000]{}.rawtx')
  595. def txsend_noamt(self):
  596. return self.txsend(ext='99.99895,50000]{}.sigtx')
  597. def bal8(self): return self.bal(n='8')
  598. def token_bal5(self): return self.token_bal(n='5')
  599. def token_txcreate_noamt(self):
  600. return self.token_txcreate(args=['98831F3A:E:13'],token='mm1',inputs='2',fee='51G')
  601. def token_txsign_noamt(self):
  602. return self.token_txsign(ext='1.23456,51000]{}.rawtx',token='mm1')
  603. def token_txsend_noamt(self):
  604. return self.token_txsend(ext='1.23456,51000]{}.sigtx',token='mm1')
  605. def bal9(self): return self.bal(n='9')
  606. def token_bal6(self): return self.token_bal(n='6')
  607. def listaddresses(self,args=[],tool_args=['all_labels=1'],exit_val=0):
  608. t = self.spawn('mmgen-tool', self.eth_args + args + ['listaddresses'] + tool_args)
  609. t.read()
  610. t.req_exit_val = exit_val
  611. return t
  612. def listaddresses1(self):
  613. return self.listaddresses()
  614. def listaddresses2(self):
  615. return self.listaddresses(tool_args=['minconf=999999999'])
  616. def listaddresses3(self):
  617. return self.listaddresses(tool_args=['sort=age'])
  618. def listaddresses4(self):
  619. return self.listaddresses(tool_args=['sort=age','showempty=1'])
  620. def token_listaddresses1(self):
  621. return self.listaddresses(args=['--token=mm1'])
  622. def token_listaddresses2(self):
  623. return self.listaddresses(args=['--token=mm1'],tool_args=['showempty=1'])
  624. def twview1(self):
  625. return self.twview()
  626. def twview2(self):
  627. return self.twview(tool_args=['wide=1'])
  628. def twview3(self):
  629. return self.twview(tool_args=['wide=1','sort=age'])
  630. def twview4(self):
  631. return self.twview(tool_args=['wide=1','minconf=999999999'])
  632. def twview5(self):
  633. return self.twview(tool_args=['wide=1','minconf=0'])
  634. def twview6(self):
  635. return self.twview(tool_args=['age_fmt=days'])
  636. def token_twview1(self):
  637. return self.twview(args=['--token=mm1'])
  638. def token_twview2(self):
  639. return self.twview(args=['--token=mm1'],tool_args=['wide=1'])
  640. def token_twview3(self):
  641. return self.twview(args=['--token=mm1'],tool_args=['wide=1','sort=age'])
  642. def edit_label(self,out_num,args=[],action='l',label_text=None):
  643. t = self.spawn('mmgen-txcreate', self.eth_args + args + ['-B','-i'])
  644. p1,p2 = ('emove address:\b','return to main menu): ')
  645. p3,r3 = (p2,label_text+'\n') if label_text is not None else ('(y/N): ','y')
  646. p4,r4 = (('(y/N): ',),('y',)) if label_text == '' else ((),())
  647. for p,r in zip((p1,p1,p2,p3)+p4+(p1,p1),('M',action,out_num+'\n',r3)+r4+('M','q')):
  648. t.expect(p,r)
  649. return t
  650. def edit_label1(self):
  651. return self.edit_label(out_num=del_addrs[0],label_text='First added label-α')
  652. def edit_label2(self):
  653. return self.edit_label(out_num=del_addrs[1],label_text='Second added label')
  654. def edit_label3(self):
  655. return self.edit_label(out_num=del_addrs[0],label_text='')
  656. def remove_addr1(self):
  657. return self.edit_label(out_num=del_addrs[0],action='R')
  658. def remove_addr2(self):
  659. return self.edit_label(out_num=del_addrs[1],action='R')
  660. def remove_token_addr1(self):
  661. return self.edit_label(out_num=del_addrs[0],args=['--token=mm1'],action='R')
  662. def remove_token_addr2(self):
  663. return self.edit_label(out_num=del_addrs[1],args=['--token=mm1'],action='R')
  664. def stop(self):
  665. self.spawn('',msg_only=True)
  666. if subprocess.call(['which','parity'],stdout=subprocess.PIPE) == 0:
  667. pid = self.read_from_tmpfile(parity_pid_fn)
  668. if opt.no_daemon_stop:
  669. msg_r('(leaving daemon running by user request)')
  670. else:
  671. subprocess.check_call(['kill',pid])
  672. else:
  673. imsg('No parity executable found on system. Ignoring')
  674. return 'ok'