ethswap.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2025 The MMGen Project <mmgen@tuta.io>
  5. # Licensed under the GNU General Public License, Version 3:
  6. # https://www.gnu.org/licenses
  7. # Public project repositories:
  8. # https://github.com/mmgen/mmgen-wallet
  9. # https://gitlab.com/mmgen/mmgen-wallet
  10. """
  11. test.cmdtest_d.ethswap: Ethereum swap tests for the cmdtest.py test suite
  12. """
  13. from subprocess import run, PIPE, DEVNULL
  14. from mmgen.util import msg_r, rmsg, die
  15. from mmgen.protocol import init_proto
  16. from mmgen.fileutil import get_data_from_file
  17. from ..include.common import imsg, chk_equal
  18. from .include.common import dfl_sid, eth_inbound_addr, thorchain_router_addr_file
  19. from .include.proxy import TestProxy
  20. from .httpd.thornode.swap import ThornodeSwapServer
  21. from .regtest import CmdTestRegtest
  22. from .swap import CmdTestSwapMethods, create_cross_methods
  23. from .ethdev import CmdTestEthdev
  24. class CmdTestEthSwapMethods:
  25. async def token_deploy_a(self):
  26. return await self._token_deploy_math(num=1)
  27. async def token_deploy_b(self):
  28. return await self._token_deploy_owned(num=1)
  29. async def token_deploy_c(self):
  30. return await self._token_deploy_token(num=1)
  31. def token_compile_router(self):
  32. if not self.using_solc:
  33. bin_fn = 'test/ref/ethereum/bin/THORChain_Router.bin'
  34. imsg(f'Using precompiled contract data ‘{bin_fn}’')
  35. import shutil
  36. shutil.copy(bin_fn, self.tmpdir)
  37. return 'skip'
  38. imsg("Compiling THORChain router contract")
  39. self.spawn(msg_only=True)
  40. cmd = [
  41. 'solc',
  42. '--evm-version=constantinople',
  43. '--overwrite',
  44. f'--output-dir={self.tmpdir}',
  45. '--bin',
  46. 'test/ref/ethereum/THORChain_Router.sol']
  47. imsg('Executing: {}'.format(' '.join(cmd)))
  48. cp = run(cmd, stdout=DEVNULL, stderr=PIPE)
  49. if cp.returncode != 0:
  50. rmsg('solc failed with the following output:')
  51. die(2, cp.stderr.decode())
  52. imsg('THORChain router contract compiled')
  53. return 'ok'
  54. async def token_deploy_router(self):
  55. return await self._token_deploy(
  56. key = 'thorchain_router',
  57. gas = 1_000_000,
  58. fn = f'{self.tmpdir}/THORChain_Router.bin')
  59. async def token_fund_user(self):
  60. return await self._token_transfer_ops(
  61. op = 'fund_user',
  62. mm_idxs = [1, 2, 12],
  63. token_addr = 'token_addr1',
  64. amt = self.token_fund_amt)
  65. def token_addrgen(self):
  66. return self._token_addrgen(mm_idxs=[1], naddrs=12)
  67. def token_addrimport(self):
  68. return self._token_addrimport('token_addr1', '1-12', expect='12/12')
  69. def token_addrimport_inbound(self):
  70. token_addr = self.read_from_tmpfile('token_addr1').strip()
  71. return self.spawn(
  72. 'mmgen-addrimport',
  73. ['--quiet', '--regtest=1', f'--token-addr={token_addr}', f'--address={eth_inbound_addr}'])
  74. def token_bal1(self):
  75. return self._token_bal_check(pat=rf'{dfl_sid}:E:1\s+{self.token_fund_amt}\s')
  76. def token_bal2(self):
  77. return self._token_bal_check(pat=rf'{eth_inbound_addr}\s+\S+\s+87.654321\s')
  78. async def _check_token_swaptx_memo(self, chk):
  79. from mmgen.proto.eth.contract import Contract
  80. self.spawn(msg_only=True)
  81. addr = get_data_from_file(self.cfg, thorchain_router_addr_file, quiet=True).strip()
  82. c = Contract(self.cfg, self.proto, addr, rpc=await self.rpc)
  83. res = (await c.do_call('saved_memo()'))[2:]
  84. memo_len = int(res[64:128], 16)
  85. chk_equal(bytes.fromhex(res[128:128+(2*memo_len)]).decode(), chk)
  86. imsg(f'saved_memo: {chk}')
  87. return 'ok'
  88. def _swaptxsend_eth_proxy(self, *, add_opts=[], test=False):
  89. t = self._swaptxsend(
  90. add_opts = ['--tx-proxy=eth'] + (['--test'] if test else []) + add_opts,
  91. spawn_only = True)
  92. t.expect('view: ', 'y')
  93. t.expect('continue: ', '\n') # exit swap quote
  94. t.expect('(y/N): ', '\n') # add comment
  95. if not test:
  96. t.expect('to confirm: ', 'YES\n')
  97. return t
  98. class CmdTestEthSwap(CmdTestSwapMethods, CmdTestRegtest):
  99. 'Ethereum swap operations'
  100. bdb_wallet = True
  101. tmpdir_nums = [47]
  102. networks = ('btc',)
  103. passthru_opts = ('coin', 'rpc_backend', 'eth_daemon_id')
  104. cross_group = 'ethswap_eth'
  105. cross_coin = 'eth'
  106. cmd_group_in = (
  107. ('setup', 'regtest (Bob and Alice) mode setup'),
  108. ('eth_setup', 'Ethereum devnet setup'),
  109. ('subgroup.init', []),
  110. ('subgroup.fund', ['init']),
  111. ('subgroup.eth_init', []),
  112. ('subgroup.eth_fund', ['eth_init']),
  113. ('subgroup.swap', ['fund', 'eth_fund']),
  114. ('subgroup.eth_swap', ['fund', 'eth_fund']),
  115. ('subgroup.token_init', ['eth_fund']),
  116. ('subgroup.token_swap', ['fund', 'token_init']),
  117. ('subgroup.eth_token_swap', ['fund', 'token_init']),
  118. ('swap_server_stop', 'stopping the Thornode server'),
  119. ('eth_stop', 'stopping the Ethereum daemon'),
  120. ('stop', 'stopping the regtest daemon'),
  121. )
  122. cmd_subgroups = {
  123. 'init': (
  124. 'creating Bob’s MMGen wallet and tracking wallet',
  125. ('walletconv_bob', 'wallet creation (Bob)'),
  126. ('addrgen_bob', 'address generation (Bob)'),
  127. ('addrimport_bob', 'importing Bob’s addresses'),
  128. ),
  129. 'fund': (
  130. 'funding Bob’s wallet',
  131. ('bob_import_miner_addr', 'importing miner’s coinbase addr into Bob’s wallet'),
  132. ('fund_bob', 'funding Bob’s wallet'),
  133. ('generate', 'mining a block'),
  134. ('bob_bal1', 'Bob’s balance'),
  135. ),
  136. 'eth_init': (
  137. 'initializing the ETH tracking wallet',
  138. ('eth_addrgen', ''),
  139. ('eth_addrimport', ''),
  140. ('eth_addrimport_devaddr', ''),
  141. ('eth_addrimport_reth_devaddr', ''),
  142. ('eth_fund_devaddr', ''),
  143. ('eth_del_reth_devaddr', ''),
  144. ),
  145. 'eth_fund': (
  146. 'funding the ETH tracking wallet',
  147. ('eth_fund_mmgen_addr1', ''),
  148. ('eth_fund_mmgen_addr1b', ''),
  149. ('eth_fund_mmgen_addr2', ''),
  150. ('eth_bal1', ''),
  151. ),
  152. 'token_init': (
  153. 'deploying tokens and initializing the ETH token tracking wallet',
  154. ('eth_token_compile1', ''),
  155. ('eth_token_deploy_a', ''),
  156. ('eth_token_deploy_b', ''),
  157. ('eth_token_deploy_c', ''),
  158. ('eth_token_compile_router', ''),
  159. ('eth_token_deploy_router', ''),
  160. ('eth_token_fund_user', ''),
  161. ('eth_token_addrgen', ''),
  162. ('eth_token_addrimport', ''),
  163. ('eth_token_addrimport_inbound', ''),
  164. ('eth_token_bal1', ''),
  165. ),
  166. 'token_swap': (
  167. 'token swap operations (BTC -> MM1)',
  168. ('swaptxcreate3', 'creating a BTC->MM1 swap transaction'),
  169. ('swaptxsign3', 'signing the swap transaction'),
  170. ('swaptxsend3', 'sending the swap transaction'),
  171. ),
  172. 'swap': (
  173. 'swap operations (BTC -> ETH)',
  174. ('swaptxcreate1', 'creating a BTC->ETH swap transaction'),
  175. ('swaptxcreate2', 'creating a BTC->ETH swap transaction (used account)'),
  176. ('swaptxsign1', 'signing the swap transaction'),
  177. ('swaptxsend1', 'sending the swap transaction'),
  178. ('swaptxbump1', 'bumping the swap transaction'),
  179. ('swaptxsign2', 'signing the bump transaction'),
  180. ('swaptxsend2', 'sending the bump transaction'),
  181. ('generate', 'generating a block'),
  182. ('bob_bal2', 'Bob’s balance'),
  183. ('swaptxdo1', 'creating, signing and sending a swap transaction'),
  184. ('generate', 'generating a block'),
  185. ('bob_bal3', 'Bob’s balance'),
  186. ),
  187. 'eth_swap': (
  188. 'swap operations (ETH -> BTC)',
  189. ('eth_swaptxcreate1', ''),
  190. ('eth_swaptxcreate2', ''),
  191. ('eth_swaptxsign1', ''),
  192. ('eth_swaptxsend1', ''),
  193. ('eth_swaptxstatus1', ''),
  194. ('eth_bal2', ''),
  195. ),
  196. 'eth_token_swap': (
  197. 'swap operations (ETH -> ERC20, ERC20 -> BTC, ERC20 -> ETH)',
  198. # ETH -> MM1
  199. ('eth_swaptxcreate3a', ''),
  200. ('eth_swaptxcreate3b', ''),
  201. ('eth_swaptxsign3', ''),
  202. ('eth_swaptxsend3', ''),
  203. ('eth_swaptxmemo3', ''),
  204. # MM1 -> BTC
  205. ('eth_swaptxcreate4', ''),
  206. ('eth_swaptxsign4', ''),
  207. ('eth_swaptxsend4', ''),
  208. ('eth_swaptxmemo4', ''),
  209. ('eth_swaptxstatus4', ''),
  210. ('eth_swaptxreceipt4', ''),
  211. ('eth_token_bal2', ''),
  212. # MM1 -> ETH
  213. ('eth_swaptxcreate5a', ''),
  214. ('eth_swaptxcreate5b', ''),
  215. ('eth_swaptxsign5', ''),
  216. ('eth_etherscan_server_start', ''),
  217. ('eth_swaptxsend5_test', ''),
  218. ('eth_swaptxsend5a', ''),
  219. ('eth_swaptxsend5b', ''),
  220. ('eth_swaptxsend5', ''),
  221. ('eth_etherscan_server_stop', ''),
  222. ),
  223. }
  224. exec(create_cross_methods(cross_coin, cross_group, cmd_group_in, cmd_subgroups))
  225. def __init__(self, cfg, trunner, cfgs, spawn):
  226. super().__init__(cfg, trunner, cfgs, spawn)
  227. if not trunner:
  228. return
  229. globals()[self.cross_group] = self.create_cross_runner(
  230. trunner,
  231. add_cfg = {'eth_daemon_id': trunner.cfg.eth_daemon_id})
  232. self.swap_server = ThornodeSwapServer()
  233. self.swap_server.start()
  234. TestProxy(self, cfg)
  235. def swaptxcreate1(self):
  236. t = self._swaptxcreate(['BTC', '8.765', 'ETH'])
  237. t.expect('OK? (Y/n): ', 'y')
  238. t.expect(':E:2')
  239. t.expect('OK? (Y/n): ', 'y')
  240. return self._swaptxcreate_ui_common(t)
  241. def swaptxcreate2(self):
  242. t = self._swaptxcreate(['BTC', '8.765', 'ETH', f'{dfl_sid}:E:1'])
  243. t.expect('OK? (Y/n): ', 'y')
  244. return self._swaptxcreate_ui_common(t)
  245. def swaptxsign1(self):
  246. return self._swaptxsign()
  247. def swaptxsend1(self):
  248. return self._swaptxsend()
  249. def swaptxsend2(self):
  250. return self._swaptxsend(add_opts=[f'--proxy=localhost:{TestProxy.port}'])
  251. swaptxsign3 = swaptxsign2 = swaptxsign1
  252. swaptxsend3 = swaptxsend1
  253. def swaptxbump1(self): # create one-output TX back to self to rescue funds
  254. return self._swaptxbump('40s', output_args=[f'{dfl_sid}:B:1'])
  255. def swaptxdo1(self):
  256. return self._swaptxcreate_ui_common(
  257. self._swaptxcreate(
  258. ['BTC', '0.223344', f'{dfl_sid}:B:3', 'ETH', f'{dfl_sid}:E:2'],
  259. action = 'txdo'),
  260. sign_and_send = True,
  261. file_desc = 'Sent transaction')
  262. def bob_bal2(self):
  263. return self._user_bal_cli('bob', chk='499.9999252')
  264. def bob_bal3(self):
  265. return self._user_bal_cli('bob', chk='499.77656902')
  266. def swaptxcreate3(self):
  267. t = self._swaptxcreate(['BTC', '0.87654321', 'ETH.MM1', f'{dfl_sid}:E:5'])
  268. t.expect('OK? (Y/n): ', 'y')
  269. return self._swaptxcreate_ui_common(t)
  270. def swap_server_stop(self):
  271. return self._thornode_server_stop()
  272. class CmdTestEthSwapEth(CmdTestEthSwapMethods, CmdTestSwapMethods, CmdTestEthdev):
  273. 'Ethereum swap operations - Ethereum wallet'
  274. networks = ('eth',)
  275. tmpdir_nums = [48]
  276. fund_amt = '123.456'
  277. token_fund_amt = 1000
  278. is_helper = True
  279. bals = lambda self, k: {
  280. 'swap1': [('98831F3A:E:1', '123.456')],
  281. 'swap2': [('98831F3A:E:1', {'geth': '114.690978056', 'reth': '114.69097664'}[self.daemon.id])],
  282. }[k]
  283. cmd_group_in = CmdTestEthdev.cmd_group_in + (
  284. # eth_fund:
  285. ('fund_mmgen_addr1', 'funding user address :1)'),
  286. ('fund_mmgen_addr1b', 'funding user address :3)'),
  287. ('fund_mmgen_addr2', 'funding user address :11)'),
  288. ('bal1', 'the ETH balance'),
  289. # eth_swap:
  290. ('swaptxcreate1', 'creating an ETH->BTC swap transaction'),
  291. ('swaptxcreate2', 'creating an ETH->BTC swap transaction (spec address, trade limit)'),
  292. ('swaptxsign1', 'signing the transaction'),
  293. ('swaptxsend1', 'sending the transaction'),
  294. ('swaptxstatus1', 'getting the transaction status (with --verbose)'),
  295. ('bal2', 'the ETH balance'),
  296. # token_init:
  297. ('token_compile1', 'compiling ERC20 token #1'),
  298. ('token_deploy_a', 'deploying ERC20 token MM1 (SafeMath)'),
  299. ('token_deploy_b', 'deploying ERC20 token MM1 (Owned)'),
  300. ('token_deploy_c', 'deploying ERC20 token MM1 (Token)'),
  301. ('token_compile_router', 'compiling THORChain router contract'),
  302. ('token_deploy_router', 'deploying THORChain router contract'),
  303. ('token_fund_user', 'transferring token funds from dev to user'),
  304. ('token_addrgen', 'generating token addresses'),
  305. ('token_addrimport', 'importing token addresses using token address (MM1)'),
  306. ('token_addrimport_inbound', 'importing THORNode inbound token address'),
  307. ('token_bal1', 'the token balance'),
  308. # eth_token_swap:
  309. # ETH -> MM1
  310. ('swaptxcreate3a', 'creating an ETH->MM1 swap transaction'),
  311. ('swaptxcreate3b', 'creating an ETH->MM1 swap transaction (specific address)'),
  312. ('swaptxsign3', 'signing the transaction'),
  313. ('swaptxsend3', 'sending the transaction'),
  314. ('swaptxmemo3', 'the memo of the sent transaction'),
  315. # MM1 -> BTC
  316. ('swaptxcreate4', 'creating an MM1->BTC swap transaction'),
  317. ('swaptxsign4', 'signing the transaction'),
  318. ('swaptxsend4', 'sending the transaction'),
  319. ('swaptxmemo4', 'checking the memo'),
  320. ('swaptxstatus4', 'getting the transaction status'),
  321. ('swaptxreceipt4', 'getting the transaction receipt'),
  322. ('token_bal2', 'the token balance'),
  323. # MM1 -> ETH
  324. ('swaptxcreate5a', 'creating an MM1->ETH swap transaction'),
  325. ('swaptxcreate5b', 'creating an MM1->ETH swap transaction (specific address)'),
  326. ('swaptxsign5', 'signing the transaction'),
  327. ('etherscan_server_start', 'starting the Etherscan server'),
  328. ('swaptxsend5_test', 'testing the transaction via Etherscan'),
  329. ('swaptxsend5a', 'sending the transaction via Etherscan (p1)'),
  330. ('swaptxsend5b', 'sending the transaction via Etherscan (p2)'),
  331. ('swaptxsend5', 'sending the transaction via Etherscan (complete)'),
  332. ('etherscan_server_stop', 'stopping the Etherscan server'),
  333. )
  334. def fund_mmgen_addr1b(self):
  335. return self._fund_mmgen_addr(arg=f'{dfl_sid}:E:3,0.001')
  336. def swaptxcreate1(self):
  337. t = self._swaptxcreate(['ETH', '8.765', 'BTC'])
  338. t.expect('OK? (Y/n): ', 'y')
  339. return self._swaptxcreate_ui_common(t)
  340. def swaptxcreate2(self):
  341. return self._swaptxcreate_ui_common(
  342. self._swaptxcreate(
  343. ['ETH', '8.765', 'BTC', f'{dfl_sid}:B:4'],
  344. add_opts = ['--trade-limit=3%' ,'--stream-interval=7']),
  345. expect = ':2019e4/7/0')
  346. def swaptxcreate3a(self):
  347. t = self._swaptxcreate(['ETH', '0.7654321', 'ETH.MM1'], add_opts=['--gas=fallback'])
  348. t.expect(f'{dfl_sid}:E:4') # check that correct unused address was found
  349. t.expect('(Y/n): ', 'y')
  350. return self._swaptxcreate_ui_common(t)
  351. def swaptxcreate3b(self):
  352. t = self._swaptxcreate(['ETH', '8.765', 'ETH.MM1', f'{dfl_sid}:E:5'], add_opts=['--gas=auto'])
  353. return self._swaptxcreate_ui_common(t)
  354. async def swaptxmemo3(self):
  355. self.spawn(msg_only=True)
  356. import json
  357. fn = self.get_file_with_ext('sigtx')
  358. tx = json.loads(get_data_from_file(self.cfg, fn, quiet=True).strip())
  359. txid = tx['MMGenTransaction']['coin_txid']
  360. chk = '=:ETH.MM1:0x48596c861c970eb4ca72c5082ff7fecd8ee5be9d:0/3/0' # E:5
  361. imsg(f'TxID: {txid}\nmemo: {chk}')
  362. res = await (await self.rpc).call('eth_getTransactionByHash', '0x' + txid)
  363. chk_equal(bytes.fromhex(res['input'].removeprefix('0x')).decode(), chk)
  364. return 'ok'
  365. def swaptxcreate4(self):
  366. t = self._swaptxcreate(['ETH.MM1', '87.654321', 'BTC', f'{dfl_sid}:C:2'], add_opts=['--gas=auto'])
  367. return self._swaptxcreate_ui_common(t)
  368. def swaptxcreate5a(self):
  369. t = self._swaptxcreate(
  370. ['ETH.MM1', '98.7654321', 'ETH'],
  371. add_opts = ['--gas=58000', '--router-gas=500000'])
  372. t.expect(f'{dfl_sid}:E:13') # check that correct unused address was found
  373. t.expect('(Y/n): ', 'y')
  374. return self._swaptxcreate_ui_common(t)
  375. def swaptxcreate5b(self):
  376. t = self._swaptxcreate(['ETH.MM1', '98.7654321', 'ETH', f'{dfl_sid}:E:12'])
  377. return self._swaptxcreate_ui_common(t)
  378. def swaptxsign1(self):
  379. return self._swaptxsign()
  380. def swaptxsend1(self):
  381. return self._swaptxsend()
  382. def swaptxstatus1(self):
  383. return self._swaptxsend(add_opts=['--verbose', '--status'], status=True)
  384. async def swaptxmemo4(self):
  385. import time
  386. time.sleep(1)
  387. return await self._check_token_swaptx_memo('=:b:mkQsXA7mqDtnUpkaXMbDtAL1KMeof4GPw3:0/3/0')
  388. def swaptxreceipt4(self):
  389. return self._swaptxsend(add_opts=['--receipt'], spawn_only=True)
  390. def swaptxsend5_test(self):
  391. return self._swaptxsend_eth_proxy(test=True)
  392. def swaptxsend5a(self):
  393. return self._swaptxsend_eth_proxy(
  394. add_opts = ['--txhex-idx=1', f'--proxy=localhost:{TestProxy.port}'])
  395. def swaptxsend5b(self):
  396. return self._swaptxsend_eth_proxy(add_opts=['--txhex-idx=2'])
  397. def swaptxsend5(self):
  398. return self._swaptxsend_eth_proxy()
  399. swaptxsign5 = swaptxsign4 = swaptxsign3 = swaptxsign1
  400. swaptxsend4 = swaptxsend3 = swaptxsend1
  401. swaptxstatus4 = swaptxstatus1
  402. def bal1(self):
  403. return self.bal('swap1')
  404. def bal2(self):
  405. return self.bal('swap2')