new.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2024 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(await self.rpc.call('eth_getTransactionCount','0x'+self.inputs[0].addr,'pending'),16))
  42. async def make_txobj(self): # called by create_serialized()
  43. self.txobj = {
  44. 'from': self.inputs[0].addr,
  45. 'to': self.outputs[0].addr if self.outputs else None,
  46. 'amt': self.outputs[0].amt if self.outputs else self.proto.coin_amt('0'),
  47. 'gasPrice': self.fee_abs2gas(self.usr_fee),
  48. 'startGas': self.start_gas,
  49. 'nonce': await self.get_nonce(),
  50. 'chainId': self.rpc.chainID,
  51. 'data': self.usr_contract_data,
  52. }
  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,bump=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_cmd_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_cmd_arg(cmd_args[0], ad_f, ad_w)
  76. self.add_output(
  77. coinaddr = arg.coin_addr,
  78. amt = self.proto.coin_amt(arg.amt or '0'),
  79. is_chg = not arg.amt)
  80. def select_unspent(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'),16), 'eth_gasPrice'
  99. def check_fee(self):
  100. if not self.disable_fee_check:
  101. assert self.usr_fee <= self.proto.max_tx_fee
  102. # given rel fee and units, return absolute fee using self.gas
  103. def fee_rel2abs(self, tx_size, units, amt_in_units, unit):
  104. return self.proto.coin_amt(amt_in_units, from_unit=units[unit]) * self.gas.toWei()
  105. # given fee estimate (gas price) in wei, return absolute fee, adjusting by self.cfg.fee_adjust
  106. def fee_est2abs(self,rel_fee,fe_type=None):
  107. ret = self.fee_gasPrice2abs(rel_fee) * self.cfg.fee_adjust
  108. if self.cfg.verbose:
  109. msg(f'Estimated fee: {ret} ETH')
  110. return ret
  111. def convert_and_check_fee(self,fee,desc):
  112. abs_fee = self.feespec2abs(fee,None)
  113. if abs_fee is False:
  114. return False
  115. elif not self.disable_fee_check and (abs_fee > self.proto.max_tx_fee):
  116. msg('{} {c}: {} fee too large (maximum fee: {} {c})'.format(
  117. abs_fee.hl(),
  118. desc,
  119. self.proto.max_tx_fee.hl(),
  120. c = self.proto.coin ))
  121. return False
  122. else:
  123. return abs_fee
  124. def update_change_output(self,funds_left):
  125. if self.outputs and self.outputs[0].is_chg:
  126. self.update_output_amt(0, funds_left)
  127. async def get_input_addrs_from_cmdline(self):
  128. ret = []
  129. if self.cfg.inputs:
  130. data_root = (await TwCtl(self.cfg,self.proto)).data_root # must create new instance here
  131. errmsg = 'Address {!r} not in tracking wallet'
  132. for addr in self.cfg.inputs.split(','):
  133. if is_mmgen_id(self.proto,addr):
  134. for waddr in data_root:
  135. if data_root[waddr]['mmid'] == addr:
  136. ret.append(waddr)
  137. break
  138. else:
  139. die( 'UserAddressNotInWallet', errmsg.format(addr) )
  140. elif is_coin_addr(self.proto,addr):
  141. if not addr in data_root:
  142. die( 'UserAddressNotInWallet', errmsg.format(addr) )
  143. ret.append(addr)
  144. else:
  145. die(1,f'{addr!r}: not an MMGen ID or coin address')
  146. return ret
  147. def final_inputs_ok_msg(self, funds_left):
  148. chg = self.proto.coin_amt('0') if (self.outputs and self.outputs[0].is_chg) else funds_left
  149. return 'Transaction leaves {} {} in the sender’s account'.format(chg.hl(), self.proto.coin)
  150. class TokenNew(TokenBase,New):
  151. desc = 'transaction'
  152. fee_is_approximate = True
  153. async def make_txobj(self): # called by create_serialized()
  154. await super().make_txobj()
  155. t = Token(self.cfg,self.proto,self.twctl.token,self.twctl.decimals)
  156. o = self.txobj
  157. o['token_addr'] = t.addr
  158. o['decimals'] = t.decimals
  159. o['token_to'] = o['to']
  160. o['data'] = t.create_data(o['token_to'],o['amt'])
  161. def update_change_output(self,funds_left):
  162. if self.outputs[0].is_chg:
  163. self.update_output_amt(0,self.inputs[0].amt)
  164. # token transaction, so check both eth and token balances
  165. # TODO: add test with insufficient funds
  166. async def precheck_sufficient_funds(self,inputs_sum,sel_unspent,outputs_sum):
  167. eth_bal = await self.twctl.get_eth_balance(sel_unspent[0].addr)
  168. if eth_bal == 0: # we don't know the fee yet
  169. msg('This account has no ether to pay for the transaction fee!')
  170. return False
  171. return await super().precheck_sufficient_funds(inputs_sum,sel_unspent,outputs_sum)
  172. async def get_funds_available(self, fee, outputs_sum):
  173. bal = await self.twctl.get_eth_balance(self.inputs[0].addr)
  174. return self._funds_available(bal >= fee, bal - fee if bal >= fee else fee - bal)
  175. def final_inputs_ok_msg(self,funds_left):
  176. token_bal = (
  177. self.proto.coin_amt('0') if self.outputs[0].is_chg
  178. else self.inputs[0].amt - self.outputs[0].amt
  179. )
  180. return "Transaction leaves ≈{} {} and {} {} in the sender's account".format(
  181. funds_left.hl(),
  182. self.proto.coin,
  183. token_bal.hl(),
  184. self.proto.dcoin
  185. )