new.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. proto.eth.tx.new: Ethereum new transaction class
  12. """
  13. import json
  14. from ....tx import new as TxBase
  15. from ....obj import Int, ETHNonce, MMGenTxID, HexStr
  16. from ....util import msg, is_int, is_hex_str, make_chksum_6, suf, die
  17. from ....tw.ctl import TwCtl
  18. from ....addr import is_mmgen_id, is_coin_addr
  19. from ..contract import Token
  20. from .base import Base, TokenBase
  21. class New(Base, TxBase.New):
  22. desc = 'transaction'
  23. fee_fail_fs = 'Network fee estimation failed'
  24. no_chg_msg = 'Warning: Transaction leaves account with zero balance'
  25. usr_fee_prompt = 'Enter transaction fee or gas price: '
  26. msg_insufficient_funds = 'Account balance insufficient to fund this transaction ({} {} needed)'
  27. def __init__(self, *args, **kwargs):
  28. super().__init__(*args, **kwargs)
  29. if self.cfg.gas:
  30. self.gas = self.start_gas = self.proto.coin_amt(int(self.cfg.gas), from_unit='wei')
  31. else:
  32. self.gas = self.proto.coin_amt(self.dfl_gas, from_unit='wei')
  33. self.start_gas = self.proto.coin_amt(self.dfl_start_gas, from_unit='wei')
  34. if self.cfg.contract_data:
  35. m = "'--contract-data' option may not be used with token transaction"
  36. assert 'Token' not in self.name, m
  37. with open(self.cfg.contract_data) as fp:
  38. self.usr_contract_data = HexStr(fp.read().strip())
  39. self.disable_fee_check = True
  40. async def get_nonce(self):
  41. return ETHNonce(int(
  42. await self.rpc.call('eth_getTransactionCount', '0x'+self.inputs[0].addr, 'pending'), 16))
  43. async def make_txobj(self): # called by create_serialized()
  44. self.txobj = {
  45. 'from': self.inputs[0].addr,
  46. 'to': self.outputs[0].addr if self.outputs else None,
  47. 'amt': self.outputs[0].amt if self.outputs else self.proto.coin_amt('0'),
  48. 'gasPrice': self.fee_abs2gasprice(self.usr_fee),
  49. 'startGas': self.start_gas,
  50. 'nonce': await self.get_nonce(),
  51. 'chainId': self.rpc.chainID,
  52. 'data': self.usr_contract_data}
  53. # Instead of serializing tx data as with BTC, just create a JSON dump.
  54. # This complicates things but means we avoid using the rlp library to deserialize the data,
  55. # thus removing an attack vector
  56. async def create_serialized(self, *, locktime=None):
  57. assert len(self.inputs) == 1, 'Transaction has more than one input!'
  58. o_num = len(self.outputs)
  59. o_ok = 0 if self.usr_contract_data else 1
  60. assert o_num == o_ok, f'Transaction has {o_num} output{suf(o_num)} (should have {o_ok})'
  61. await self.make_txobj()
  62. odict = {k:v if v is None else str(v) for k, v in self.txobj.items() if k != 'token_to'}
  63. self.serialized = json.dumps(odict)
  64. self.update_txid()
  65. def update_txid(self):
  66. assert not is_hex_str(self.serialized), (
  67. 'update_txid() must be called only when self.serialized is not hex data')
  68. self.txid = MMGenTxID(make_chksum_6(self.serialized).upper())
  69. async def process_cmdline_args(self, cmd_args, ad_f, ad_w):
  70. lc = len(cmd_args)
  71. if lc == 0 and self.usr_contract_data and 'Token' not in self.name:
  72. return
  73. if lc != 1:
  74. die(1, f'{lc} output{suf(lc)} specified, but Ethereum transactions must have exactly one')
  75. arg = self.parse_cmdline_arg(self.proto, cmd_args[0], ad_f, ad_w)
  76. self.add_output(
  77. coinaddr = arg.addr,
  78. amt = self.proto.coin_amt(arg.amt or '0'),
  79. is_chg = not arg.amt)
  80. def get_unspent_nums_from_user(self, unspent):
  81. from ....ui import line_input
  82. while True:
  83. reply = line_input(self.cfg, 'Enter an account to spend from: ').strip()
  84. if reply:
  85. if not is_int(reply):
  86. msg('Account number must be an integer')
  87. elif int(reply) < 1:
  88. msg('Account number must be >= 1')
  89. elif int(reply) > len(unspent):
  90. msg(f'Account number must be <= {len(unspent)}')
  91. else:
  92. return [int(reply)]
  93. @property
  94. def network_estimated_fee_label(self):
  95. return 'Network-estimated'
  96. # get rel_fee (gas price) from network, return in native wei
  97. async def get_rel_fee_from_network(self):
  98. return Int(await self.rpc.call('eth_gasPrice'), base=16), 'eth_gasPrice'
  99. def check_chg_addr_is_wallet_addr(self):
  100. pass
  101. def check_fee(self):
  102. if not self.disable_fee_check:
  103. assert self.usr_fee <= self.proto.max_tx_fee
  104. # given rel fee and units, return absolute fee using self.gas
  105. def fee_rel2abs(self, tx_size, amt_in_units, unit):
  106. return self.proto.coin_amt(int(amt_in_units * self.gas.toWei()), from_unit=unit)
  107. # given fee estimate (gas price) in wei, return absolute fee, adjusting by self.cfg.fee_adjust
  108. def fee_est2abs(self, rel_fee, *, fe_type=None):
  109. ret = self.fee_gasPrice2abs(rel_fee) * self.cfg.fee_adjust
  110. if self.cfg.verbose:
  111. msg(f'Estimated fee: {ret} ETH')
  112. return ret
  113. def convert_and_check_fee(self, fee, desc):
  114. abs_fee = self.feespec2abs(fee, None)
  115. if abs_fee is False:
  116. return False
  117. elif not self.disable_fee_check and (abs_fee > self.proto.max_tx_fee):
  118. msg('{} {c}: {} fee too large (maximum fee: {} {c})'.format(
  119. abs_fee.hl(),
  120. desc,
  121. self.proto.max_tx_fee.hl(),
  122. c = self.proto.coin))
  123. return False
  124. else:
  125. return abs_fee
  126. def update_change_output(self, funds_left):
  127. if self.outputs and self.outputs[0].is_chg:
  128. self.update_output_amt(0, funds_left)
  129. async def get_input_addrs_from_inputs_opt(self):
  130. ret = []
  131. if self.cfg.inputs:
  132. data_root = (await TwCtl(self.cfg, self.proto)).data_root # must create new instance here
  133. errmsg = 'Address {!r} not in tracking wallet'
  134. for addr in self.cfg.inputs.split(','):
  135. if is_mmgen_id(self.proto, addr):
  136. for waddr in data_root:
  137. if data_root[waddr]['mmid'] == addr:
  138. ret.append(waddr)
  139. break
  140. else:
  141. die('UserAddressNotInWallet', errmsg.format(addr))
  142. elif is_coin_addr(self.proto, addr):
  143. if not addr in data_root:
  144. die('UserAddressNotInWallet', errmsg.format(addr))
  145. ret.append(addr)
  146. else:
  147. die(1, f'{addr!r}: not an MMGen ID or coin address')
  148. return ret
  149. def final_inputs_ok_msg(self, funds_left):
  150. chg = self.proto.coin_amt('0') if (self.outputs and self.outputs[0].is_chg) else funds_left
  151. return 'Transaction leaves {} {} in the sender’s account'.format(chg.hl(), self.proto.coin)
  152. class TokenNew(TokenBase, New):
  153. desc = 'transaction'
  154. fee_is_approximate = True
  155. async def make_txobj(self): # called by create_serialized()
  156. await super().make_txobj()
  157. t = Token(self.cfg, self.proto, self.twctl.token, self.twctl.decimals)
  158. o = self.txobj
  159. o['token_addr'] = t.addr
  160. o['decimals'] = t.decimals
  161. o['token_to'] = o['to']
  162. o['data'] = t.create_data(o['token_to'], o['amt'])
  163. def update_change_output(self, funds_left):
  164. if self.outputs[0].is_chg:
  165. self.update_output_amt(0, self.inputs[0].amt)
  166. # token transaction, so check both eth and token balances
  167. # TODO: add test with insufficient funds
  168. async def precheck_sufficient_funds(self, inputs_sum, sel_unspent, outputs_sum):
  169. eth_bal = await self.twctl.get_eth_balance(sel_unspent[0].addr)
  170. if eth_bal == 0: # we don't know the fee yet
  171. msg('This account has no ether to pay for the transaction fee!')
  172. return False
  173. return await super().precheck_sufficient_funds(inputs_sum, sel_unspent, outputs_sum)
  174. async def get_funds_available(self, fee, outputs_sum):
  175. bal = await self.twctl.get_eth_balance(self.inputs[0].addr)
  176. return self._funds_available(bal >= fee, bal - fee if bal >= fee else fee - bal)
  177. def final_inputs_ok_msg(self, funds_left):
  178. token_bal = (
  179. self.proto.coin_amt('0') if self.outputs[0].is_chg
  180. else self.inputs[0].amt - self.outputs[0].amt
  181. )
  182. return "Transaction leaves ≈{} {} and {} {} in the sender's account".format(
  183. funds_left.hl(),
  184. self.proto.coin,
  185. token_bal.hl(),
  186. self.proto.dcoin
  187. )