modularize transaction classes

The monolithic tx.py module has been split into multiple modules, and a
clean separation of protocol-dependent and protocol-independent code has
been carried out.

- Protocol-independent base classes are located under `tx`.
- Protocol-dependent subclasses are under `base_proto/{name}/tx`.
- The code in `tx/__init__.py` loads the required module and returns an
  initialized instance of the requested class.
This commit is contained in:
The MMGen Project 2022-02-03 20:40:43 +00:00
commit 818488c559
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
57 changed files with 2924 additions and 2421 deletions

View file

@ -262,7 +262,7 @@ class AddrFile(MMGenObject):
Having caller supply protocol and checking address file protocol against it here
allows us to catch all mismatches in one place. This behavior differs from that of
transaction files, which determine the protocol independently, requiring the caller
to check for protocol mismatches (e.g. MMGenTX.check_correct_chain())
to check for protocol mismatches (e.g. mmgen.tx.completed.check_correct_chain())
"""
raise ValueError(
f'{p.desc} file is '

View file

View file

View file

@ -0,0 +1,325 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.bitcoin.tx.base: Bitcoin base transaction class
"""
from collections import namedtuple
import mmgen.tx.base as TxBase
from ....opts import opt
from ....obj import MMGenObject,MMGenList,HexStr
from ....util import msg,dmsg,make_chksum_6
def addr2pubhash(proto,addr):
ap = proto.parse_addr(addr)
assert ap,f'coin address {addr!r} could not be parsed'
return ap.bytes.hex()
def addr2scriptPubKey(proto,addr):
return {
'p2pkh': '76a914' + addr2pubhash(proto,addr) + '88ac',
'p2sh': 'a914' + addr2pubhash(proto,addr) + '87',
'bech32': proto.witness_vernum_hex + '14' + addr2pubhash(proto,addr)
}[addr.addr_fmt]
def scriptPubKey2addr(proto,s):
if len(s) == 50 and s[:6] == '76a914' and s[-4:] == '88ac':
return proto.pubhash2addr(bytes.fromhex(s[6:-4]),p2sh=False),'p2pkh'
elif len(s) == 46 and s[:4] == 'a914' and s[-2:] == '87':
return proto.pubhash2addr(bytes.fromhex(s[4:-2]),p2sh=True),'p2sh'
elif len(s) == 44 and s[:4] == proto.witness_vernum_hex + '14':
return proto.pubhash2bech32addr(bytes.fromhex(s[4:])),'bech32'
else:
raise NotImplementedError(f'Unknown scriptPubKey ({s})')
def DeserializeTX(proto,txhex):
"""
Parse a serialized Bitcoin transaction
For checking purposes, additionally reconstructs the serialized TX without signature
"""
def bytes2int(bytes_le):
if bytes_le[-1] & 0x80: # sign bit is set
die(3,"{}: Negative values not permitted in transaction!".format(bytes_le[::-1].hex()))
return int(bytes_le[::-1].hex(),16)
def bytes2coin_amt(bytes_le):
return proto.coin_amt(bytes2int(bytes_le) * proto.coin_amt.satoshi)
def bshift(n,skip=False,sub_null=False):
ret = tx[var.idx:var.idx+n]
var.idx += n
if sub_null:
var.raw_tx += b'\x00'
elif not skip:
var.raw_tx += ret
return ret
# https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers
# For example, the number 515 is encoded as 0xfd0302.
def readVInt(skip=False):
s = tx[var.idx]
var.idx += 1
if not skip:
var.raw_tx.append(s)
vbytes_len = 1 if s < 0xfd else 2 if s == 0xfd else 4 if s == 0xfe else 8
if vbytes_len == 1:
return s
else:
vbytes = tx[var.idx:var.idx+vbytes_len]
var.idx += vbytes_len
if not skip:
var.raw_tx += vbytes
return int(vbytes[::-1].hex(),16)
def make_txid(tx_bytes):
from hashlib import sha256
return sha256(sha256(tx_bytes).digest()).digest()[::-1].hex()
class vardata:
idx = 0
raw_tx = bytearray()
var = vardata()
tx = bytes.fromhex(txhex)
d = { 'version': bytes2int(bshift(4)) }
has_witness = tx[var.idx] == 0
if has_witness:
u = bshift(2,skip=True).hex()
if u != '0001':
raise IllegalWitnessFlagValue(f'{u!r}: Illegal value for flag in transaction!')
d['num_txins'] = readVInt()
d['txins'] = MMGenList([{
'txid': bshift(32)[::-1].hex(),
'vout': bytes2int(bshift(4)),
'scriptSig': bshift(readVInt(skip=True),sub_null=True).hex(),
'nSeq': bshift(4)[::-1].hex()
} for i in range(d['num_txins'])])
d['num_txouts'] = readVInt()
d['txouts'] = MMGenList([{
'amount': bytes2coin_amt(bshift(8)),
'scriptPubKey': bshift(readVInt()).hex()
} for i in range(d['num_txouts'])])
for o in d['txouts']:
o['address'] = scriptPubKey2addr(proto,o['scriptPubKey'])[0]
if has_witness:
# https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
# A non-witness program (defined hereinafter) txin MUST be associated with an empty
# witness field, represented by a 0x00.
d['txid'] = make_txid(tx[:4] + tx[6:var.idx] + tx[-4:])
d['witness_size'] = len(tx) - var.idx + 2 - 4 # add len(marker+flag), subtract len(locktime)
for txin in d['txins']:
if tx[var.idx] == 0:
bshift(1,skip=True)
continue
txin['witness'] = [
bshift(readVInt(skip=True),skip=True).hex() for item in range(readVInt(skip=True)) ]
else:
d['txid'] = make_txid(tx)
d['witness_size'] = 0
if len(tx) - var.idx != 4:
raise TxHexParseError('TX hex has invalid length: {} extra bytes'.format(len(tx)-var.idx-4))
d['locktime'] = bytes2int(bshift(4))
d['unsigned_hex'] = var.raw_tx.hex()
return namedtuple('deserialized_tx',list(d.keys()))(**d)
class Base(TxBase.Base):
rel_fee_desc = 'satoshis per byte'
rel_fee_disp = 'sat/byte'
_deserialized = None
class InputList(TxBase.Base.InputList):
# Lexicographical Indexing of Transaction Inputs and Outputs
# https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki
def sort_bip69(self):
def sort_func(a):
return (
bytes.fromhex(a.txid)
+ int.to_bytes(a.vout,4,'big') )
self.sort(key=sort_func)
class OutputList(TxBase.Base.OutputList):
def sort_bip69(self):
def sort_func(a):
return (
int.to_bytes(a.amt.to_unit('satoshi'),8,'big')
+ bytes.fromhex(addr2scriptPubKey(self.parent.proto,a.addr)) )
self.sort(key=sort_func)
def has_segwit_inputs(self):
return any(i.mmtype in ('S','B') for i in self.inputs)
def has_segwit_outputs(self):
return any(o.mmtype in ('S','B') for o in self.outputs)
# https://bitcoin.stackexchange.com/questions/1195/how-to-calculate-transaction-size-before-sending
# 180: uncompressed, 148: compressed
def estimate_size_old(self):
if not self.inputs or not self.outputs:
return None
return len(self.inputs)*180 + len(self.outputs)*34 + 10
# https://bitcoincore.org/en/segwit_wallet_dev/
# vsize: 3 times of the size with original serialization, plus the size with new
# serialization, divide the result by 4 and round up to the next integer.
# TODO: results differ slightly from actual transaction size
def estimate_size(self):
if not self.inputs or not self.outputs:
return None
sig_size = 72 # sig in DER format
pubkey_size_uncompressed = 65
pubkey_size_compressed = 33
def get_inputs_size():
# txid vout [scriptSig size (vInt)] scriptSig (<sig> <pubkey>) nSeq
isize_common = 32 + 4 + 1 + 4 # txid vout [scriptSig size] nSeq = 41
input_size = {
'L': isize_common + sig_size + pubkey_size_uncompressed, # = 180
'C': isize_common + sig_size + pubkey_size_compressed, # = 148
'S': isize_common + 23, # = 64
'B': isize_common + 0 # = 41
}
ret = sum(input_size[i.mmtype] for i in self.inputs if i.mmtype)
# We have no way of knowing whether a non-MMGen P2PKH addr is compressed or uncompressed
# until we see the key, so assume compressed for fee-estimation purposes. If fee estimate
# is off by more than 5%, sign() aborts and user is instructed to use --vsize-adj option.
return ret + sum(input_size['C'] for i in self.inputs if not i.mmtype)
def get_outputs_size():
# output bytes = amt: 8, byte_count: 1+, pk_script
# pk_script bytes: p2pkh: 25, p2sh: 23, bech32: 22
return sum({'p2pkh':34,'p2sh':32,'bech32':31}[o.addr.addr_fmt] for o in self.outputs)
# https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
# The witness is a serialization of all witness data of the transaction. Each txin is
# associated with a witness field. A witness field starts with a var_int to indicate the
# number of stack items for the txin. It is followed by stack items, with each item starts
# with a var_int to indicate the length. Witness data is NOT script.
# A non-witness program txin MUST be associated with an empty witness field, represented
# by a 0x00. If all txins are not witness program, a transaction's wtxid is equal to its txid.
def get_witness_size():
if not self.has_segwit_inputs():
return 0
wf_size = 1 + 1 + sig_size + 1 + pubkey_size_compressed # vInt vInt sig vInt pubkey = 108
return sum((1,wf_size)[i.mmtype in ('S','B')] for i in self.inputs)
isize = get_inputs_size()
osize = get_outputs_size()
wsize = get_witness_size()
# TODO: compute real varInt sizes instead of assuming 1 byte
# old serialization: [nVersion] [vInt][txins][vInt][txouts] [nLockTime]
old_size = 4 + 1 + isize + 1 + osize + 4
# marker = 0x00, flag = 0x01
# new serialization: [nVersion][marker][flag][vInt][txins][vInt][txouts][witness][nLockTime]
new_size = 4 + 1 + 1 + 1 + isize + 1 + osize + wsize + 4 \
if wsize else old_size
ret = (old_size * 3 + new_size) // 4
dmsg('\nData from estimate_size():')
dmsg(f' inputs size: {isize}, outputs size: {osize}, witness size: {wsize}')
dmsg(f' size: {new_size}, vsize: {ret}, old_size: {old_size}')
return int(ret * (opt.vsize_adj or 1))
# convert absolute CoinAmt fee to sat/byte using estimated size
def fee_abs2rel(self,abs_fee,to_unit='satoshi'):
return int(
abs_fee /
getattr( self.proto.coin_amt, to_unit ) /
self.estimate_size() )
@property
def deserialized(self):
if not self._deserialized:
self._deserialized = DeserializeTX(self.proto,self.serialized)
return self._deserialized
def update_serialized(self,data):
self.serialized = HexStr(data)
self._deserialized = None
self.check_serialized_integrity()
def check_serialized_integrity(self):
"""
Check that a malicious, compromised or malfunctioning coin daemon hasn't produced bad
serialized tx data.
Does not check witness data.
Perform this check every time a serialized tx is received from the coin daemon or read
from a transaction file.
"""
def do_error(errmsg):
from ....exception import TxHexMismatch
raise TxHexMismatch(errmsg+'\n'+hdr)
def check_equal(desc,hexio,mmio):
if mmio != hexio:
msg('\nMMGen {d}:\n{m}\nSerialized {d}:\n{h}'.format(
d = desc,
m = pp_fmt(mmio),
h = pp_fmt(hexio) ))
do_error(
f'{desc.capitalize()} in serialized transaction data from coin daemon ' +
'do not match those in MMGen transaction!' )
hdr = 'A malicious or malfunctioning coin daemon or other program may have altered your data!'
dtx = self.deserialized
if dtx.locktime != int(self.locktime or 0):
do_error(
f'Transaction hex nLockTime ({dtx.locktime}) ' +
f'does not match MMGen transaction nLockTime ({self.locktime})' )
check_equal(
'sequence numbers',
[int(i['nSeq'],16) for i in dtx.txins],
[i.sequence or self.proto.max_int for i in self.inputs] )
check_equal(
'inputs',
sorted((i['txid'],i['vout']) for i in dtx.txins),
sorted((i.txid,i.vout) for i in self.inputs) )
check_equal(
'outputs',
sorted((o['address'],self.proto.coin_amt(o['amount'])) for o in dtx.txouts),
sorted((o.addr,o.amt) for o in self.outputs) )
if str(self.txid) != make_chksum_6(bytes.fromhex(dtx.unsigned_hex)).upper():
do_error(
f'MMGen TxID ({self.txid}) does not match serialized transaction data!')

View file

@ -0,0 +1,51 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.bitcoin.tx.bump: Bitcoin transaction bump class
"""
import mmgen.tx.bump as TxBase
from .new import New
from .completed import Completed
class Bump(Completed,New,TxBase.Bump):
desc = 'fee-bumped transaction'
@property
def min_fee(self):
return self.sum_inputs() - self.sum_outputs() + self.relay_fee
def bump_fee(self,idx,fee):
self.update_output_amt(
idx,
self.sum_inputs() - self.sum_outputs(exclude=idx) - fee
)
def convert_and_check_fee(self,tx_fee,desc):
ret = super().convert_and_check_fee(tx_fee,desc)
if ret < self.min_fee:
msg('{} {c}: {} fee too small. Minimum fee: {} {c} ({} {})'.format(
ret.hl(),
desc,
self.min_fee,
self.fee_abs2rel(self.min_fee.hl()),
self.rel_fee_desc,
c = self.coin ))
return False
output_amt = self.outputs[self.bump_output_idx].amt
if ret >= output_amt:
msg('{} {c}: {} fee too large. Maximum fee: <{} {c}'.format(
ret.hl(),
desc,
output_amt.hl(),
c = self.coin ))
return False
return ret

View file

@ -0,0 +1,86 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.bitcoin.tx.completed: Bitcoin completed transaction class
"""
import mmgen.tx.completed as TxBase
from .base import Base,scriptPubKey2addr
from ....obj import HexStr
from ....util import msg
class Completed(Base,TxBase.Completed):
fn_fee_unit = 'satoshi'
# check signature and witness data
def check_sigs(self): # return True if sigs found, False otherwise; raise exception on error
txins = self.deserialized.txins
has_ss = any(ti['scriptSig'] for ti in txins)
has_witness = any('witness' in ti and ti['witness'] for ti in txins)
if not (has_ss or has_witness):
return False
fs = "Hex TX has {} scriptSig but input is of type '{}'!"
for n in range(len(txins)):
ti,mmti = txins[n],self.inputs[n]
if ti['scriptSig'] == '' or ( len(ti['scriptSig']) == 46 and # native P2WPKH or P2SH-P2WPKH
ti['scriptSig'][:6] == '16' + self.proto.witness_vernum_hex + '14' ):
assert 'witness' in ti, 'missing witness'
assert type(ti['witness']) == list and len(ti['witness']) == 2, 'malformed witness'
assert len(ti['witness'][1]) == 66, 'incorrect witness pubkey length'
assert mmti.mmtype == ('S','B')[ti['scriptSig']==''], fs.format('witness-type',mmti.mmtype)
else: # non-witness
assert mmti.mmtype not in ('S','B'), fs.format('signature in',mmti.mmtype)
assert not 'witness' in ti, 'non-witness input has witness'
# sig_size 72 (DER format), pubkey_size 'compressed':33, 'uncompressed':65
assert (200 < len(ti['scriptSig']) < 300), 'malformed scriptSig' # VERY rough check
return True
def check_pubkey_scripts(self):
for n,i in enumerate(self.inputs,1):
addr,fmt = scriptPubKey2addr(self.proto,i.scriptPubKey)
if i.addr != addr:
if fmt != i.addr.addr_fmt:
m = 'Address format of scriptPubKey ({}) does not match that of address ({}) in input #{}'
msg(m.format(fmt,i.addr.addr_fmt,n))
m = 'ERROR: Address and scriptPubKey of transaction input #{} do not match!'
die(3,(m+'\n {:23}{}'*3).format(n, 'address:',i.addr,
'scriptPubKey:',i.scriptPubKey,
'scriptPubKey->address:',addr ))
# def is_replaceable_from_rpc(self):
# dec_tx = await self.rpc.call('decoderawtransaction',self.serialized)
# return None < dec_tx['vin'][0]['sequence'] <= self.proto.max_int - 2
def is_replaceable(self):
return self.inputs[0].sequence == self.proto.max_int - 2
@property
def send_amt(self):
return self.sum_outputs(
exclude = None if len(self.outputs) == 1 else self.get_chg_output_idx()
)
def check_txfile_hex_data(self):
self.serialized = HexStr(self.serialized)
def parse_txfile_serialized_data(self):
pass
@property
def fee(self):
return self.sum_inputs() - self.sum_outputs()
@property
def change(self):
return self.sum_outputs() - self.send_amt
def get_serialized_locktime(self):
return int(bytes.fromhex(self.serialized[-8:])[::-1].hex(),16)

View file

@ -0,0 +1,133 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.bitcoin.tx.info: Bitcoin transaction info class
"""
from ....tx.info import TxInfo
from ....util import fmt,die
from ....color import red,green,pink
from ....addr import MMGenID
class TxInfo(TxInfo):
sort_orders = ('addr','raw')
txinfo_hdr_fs = 'TRANSACTION DATA\n\nID={i} ({a} {c}) UTC={t} RBF={r} Sig={s} Locktime={l}\n'
txinfo_hdr_fs_short = 'TX {i} ({a} {c}) UTC={t} RBF={r} Sig={s} Locktime={l}\n'
txinfo_ftr_fs = fmt("""
Input amount: {i} {d}
Spend amount: {s} {d}
Change: {C} {d}
Fee: {a} {c}{r}
""")
def format_rel_fee(self,terse):
tx = self.tx
return ' ({} {}, {} of spend amount)'.format(
pink(str(tx.fee_abs2rel(tx.fee))),
tx.rel_fee_disp,
pink('{:0.6f}%'.format( tx.fee / tx.send_amt * 100 ))
)
def format_abs_fee(self):
return self.tx.proto.coin_amt(self.tx.fee).hl()
def format_verbose_footer(self):
tx = self.tx
tsize = len(tx.serialized) // 2 if tx.serialized else 'unknown'
out = f'Transaction size: Vsize {tx.estimate_size()} (estimated), Total {tsize}'
if tx.name in ('Signed','OnlineSigned'):
wsize = tx.deserialized.witness_size
out += f', Base {tsize-wsize}, Witness {wsize}'
return out + '\n'
def format_body(self,blockcount,nonmm_str,max_mmwid,enl,terse,sort):
tx = self.tx
if sort not in self.sort_orders:
die(1,'{!r}: invalid transaction view sort order. Valid options: {}'.format(
sort,
','.join(self.sort_orders) ))
def format_io(desc):
io = getattr(tx,desc)
is_input = desc == 'inputs'
yield desc.capitalize() + ':\n' + enl
confs_per_day = 60*60*24 // tx.proto.avg_bdi
io_sorted = {
'addr': lambda: sorted(
io, # prepend '+' (sorts before '0') to ensure non-MMGen addrs are displayed first
key = lambda o: (o.mmid.sort_key if o.mmid else f'+{o.addr}') + f'{o.amt:040.20f}' ),
'raw': lambda: io
}[sort]
for n,e in enumerate(io_sorted()):
if is_input and blockcount:
confs = e.confs + blockcount - tx.blockcount
days = int(confs // confs_per_day)
if e.mmid:
mmid_fmt = e.mmid.fmt(
width=max_mmwid,
encl='()',
color=True,
append_chars=('',' (chg)')[bool(not is_input and e.is_chg and terse)],
append_color='green')
else:
mmid_fmt = MMGenID.fmtc(nonmm_str,width=max_mmwid,color=True)
if terse:
yield '{:3} {} {} {} {}\n'.format(
n+1,
e.addr.fmt(color=True,width=addr_w),
mmid_fmt,
e.amt.hl(),
tx.dcoin )
else:
def gen():
if is_input:
yield (n+1, 'tx,vout:', f'{e.txid.hl()},{red(str(e.vout))}')
yield ('', 'address:', f'{e.addr.hl()} {mmid_fmt}')
else:
yield (n+1, 'address:', f'{e.addr.hl()} {mmid_fmt}')
if e.label:
yield ('', 'comment:', e.label.hl())
yield ('', 'amount:', f'{e.amt.hl()} {tx.dcoin}')
if is_input and blockcount:
yield ('', 'confirmations:', f'{confs} (around {days} days)')
if not is_input and e.is_chg:
yield ('', 'change:', green('True'))
yield '\n'.join('{:>3} {:<8} {}'.format(*d) for d in gen()) + '\n\n'
addr_w = max(len(e.addr) for f in (tx.inputs,tx.outputs) for e in f)
return (
'Displaying inputs and outputs in {} sort order'.format({'raw':'raw','addr':'address'}[sort])
+ ('\n\n','\n')[terse]
+ ''.join(format_io('inputs'))
+ ''.join(format_io('outputs')) )
def strfmt_locktime(self,locktime=None,terse=False):
# Locktime itself is an unsigned 4-byte integer which can be parsed two ways:
#
# If less than 500 million, locktime is parsed as a block height. The transaction can be
# added to any block which has this height or higher.
# MMGen note: s/this height or higher/a higher block height/
#
# If greater than or equal to 500 million, locktime is parsed using the Unix epoch time
# format (the number of seconds elapsed since 1970-01-01T00:00 UTC). The transaction can be
# added to any block whose block time is greater than the locktime.
num = locktime or self.tx.locktime
if num == None:
return '(None)'
elif num >= 5 * 10**6:
import time
return ' '.join(time.strftime('%c',time.gmtime(num)).split()[1:])
elif num > 0:
return '{}{}'.format(('block height ','')[terse],num)
else:
die(2,f'{num!r}: invalid nLockTime value!')

View file

@ -0,0 +1,137 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.bitcoin.tx.new: Bitcoin new transaction class
"""
import mmgen.tx.new as TxBase
from .base import Base
from ....opts import opt
from ....obj import HexStr,MMGenTxID
from ....util import dmsg,vmsg,make_chksum_6
class New(Base,TxBase.New):
usr_fee_prompt = 'Enter transaction fee: '
fee_fail_fs = 'Network fee estimation for {c} confirmations failed ({t})'
no_chg_msg = 'Warning: Change address will be deleted as transaction produces no change'
msg_wallet_low_coin = 'Wallet has insufficient funds for this transaction ({} {} needed)'
@property
def relay_fee(self):
kb_fee = self.proto.coin_amt(self.rpc.cached['networkinfo']['relayfee'])
ret = kb_fee * self.estimate_size() / 1024
vmsg('Relay fee: {} {c}/kB, for transaction: {} {c}'.format(kb_fee,ret,c=self.coin))
return ret
async def get_rel_fee_from_network(self):
try:
ret = await self.rpc.call('estimatesmartfee',opt.tx_confs,opt.fee_estimate_mode.upper())
fee_per_kb = ret['feerate'] if 'feerate' in ret else -2
fe_type = 'estimatesmartfee'
except:
args = self.rpc.daemon.estimatefee_args(self.rpc)
fee_per_kb = await self.rpc.call('estimatefee',*args)
fe_type = 'estimatefee'
return fee_per_kb,fe_type
# given tx size, rel fee and units, return absolute fee
def fee_rel2abs(self,tx_size,units,amt,unit):
if tx_size:
return self.proto.coin_amt(amt * tx_size * getattr(self.proto.coin_amt,units[unit]))
else:
return None
# given network fee estimate in BTC/kB, return absolute fee using estimated tx size
def fee_est2abs(self,fee_per_kb,fe_type=None):
from decimal import Decimal
tx_size = self.estimate_size()
ret = self.proto.coin_amt(
fee_per_kb * Decimal(opt.tx_fee_adj) * tx_size / 1024,
from_decimal = True )
if opt.verbose:
msg(fmt(f"""
{fe_type.upper()} fee for {opt.tx_confs} confirmations: {fee_per_kb} {self.coin}/kB
TX size (estimated): {tx_size} bytes
Fee adjustment factor: {opt.tx_fee_adj:.2f}
Absolute fee (fee_per_kb * adj_factor * tx_size / 1024): {ret} {self.coin}
""").strip())
return ret
def convert_and_check_fee(self,tx_fee,desc):
abs_fee = self.feespec2abs(tx_fee,self.estimate_size())
if abs_fee == None:
raise ValueError(f'{tx_fee}: cannot convert {self.rel_fee_desc} to {self.coin}'
+ ' because transaction size is unknown')
if abs_fee == False:
err = f'{tx_fee!r}: invalid TX fee (not a {self.coin} amount or {self.rel_fee_desc} specification)'
elif abs_fee > self.proto.max_tx_fee:
err = f'{abs_fee} {self.coin}: {desc} fee too large (maximum fee: {self.proto.max_tx_fee} {self.coin})'
elif abs_fee < self.relay_fee:
err = f'{abs_fee} {self.coin}: {desc} fee too small (less than relay fee of {self.relay_fee} {self.coin})'
else:
return abs_fee
msg(err)
return False
async def get_cmdline_input_addrs(self):
# Bitcoin full node, call doesn't go to the network, so just call listunspent with addrs=[]
return []
def update_change_output(self,funds_left):
chg_idx = self.get_chg_output_idx()
if funds_left == 0:
msg(self.no_chg_msg)
self.outputs.pop(chg_idx)
else:
self.update_output_amt(chg_idx,self.proto.coin_amt(funds_left))
def check_fee(self):
fee = self.sum_inputs() - self.sum_outputs()
if fee > self.proto.max_tx_fee:
c = self.proto.coin
raise MaxFeeExceeded(f'Transaction fee of {fee} {c} too high! (> {self.proto.max_tx_fee} {c})')
def final_inputs_ok_msg(self,funds_left):
return 'Transaction produces {} {} in change'.format(
self.proto.coin_amt(funds_left).hl(),
self.coin
)
async def create_serialized(self,locktime=None,bump=None):
if not bump:
self.inputs.sort_bip69()
# do this only after inputs are sorted
if opt.rbf:
self.inputs[0].sequence = self.proto.max_int - 2 # handles the nLockTime case too
elif locktime:
self.inputs[0].sequence = self.proto.max_int - 1
self.outputs.sort_bip69()
ret = await self.rpc.call(
'createrawtransaction', [
{'txid':e.txid,'vout':e.vout,'sequence':e.sequence} if n == 0 and e.sequence else
{'txid':e.txid,'vout':e.vout}
for n,e in enumerate(self.inputs) ],
{e.addr:e.amt for e in self.outputs} )
if locktime and not bump:
msg(f'Setting nLockTime to {self.strfmt_locktime(locktime)}!')
assert isinstance(locktime,int), 'locktime value not an integer'
self.locktime = locktime
ret = ret[:-8] + bytes.fromhex('{:08x}'.format(locktime))[::-1].hex()
# TxID is set only once!
self.txid = MMGenTxID(make_chksum_6(bytes.fromhex(ret)).upper())
self.update_serialized(ret)

View file

@ -0,0 +1,82 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.bitcoin.tx.online: Bitcoin online signed transaction class
"""
import mmgen.tx.online as TxBase
from .signed import Signed
from ....globalvars import *
from ....util import msg,ymsg,rmsg
class OnlineSigned(Signed,TxBase.OnlineSigned):
async def send(self,prompt_user=True,exit_on_fail=False):
self.check_correct_chain()
if not g.bogus_send:
if self.has_segwit_outputs() and not self.rpc.info('segwit_is_active'):
die(2,'Transaction has Segwit outputs, but this blockchain does not support Segwit'
+ ' at the current height')
if self.fee > self.proto.max_tx_fee:
die(2,'Transaction fee ({}) greater than {} max_tx_fee ({} {})!'.format(
self.fee,
self.proto.name,
self.proto.max_tx_fee,
self.proto.coin ))
await self.status.display()
if prompt_user:
self.confirm_send()
if g.bogus_send:
ret = None
else:
try:
ret = await self.rpc.call('sendrawtransaction',self.serialized)
except Exception as e:
errmsg = str(e)
ret = False
if ret == False: # TODO: test send errors
if errmsg.count('Signature must use SIGHASH_FORKID'):
m = ('The Aug. 1 2017 UAHF has activated on this chain.\n'
+ 'Re-run the script with the --coin=bch option.' )
elif errmsg.count('Illegal use of SIGHASH_FORKID'):
m = ('The Aug. 1 2017 UAHF is not yet active on this chain.\n'
+ 'Re-run the script without the --coin=bch option.' )
elif errmsg.count('64: non-final'):
m = "Transaction with nLockTime {!r} can't be included in this block!".format(
self.strfmt_locktime(self.get_serialized_locktime()) )
else:
m = errmsg
ymsg(m)
rmsg(f'Send of MMGen transaction {self.txid} failed')
if exit_on_fail:
sys.exit(1)
return False
else:
if g.bogus_send:
m = 'BOGUS transaction NOT sent: {}'
else:
m = 'Transaction sent: {}'
assert ret == self.coin_txid, 'txid mismatch (after sending)'
msg(m.format(self.coin_txid.hl()))
self.add_timestamp()
self.add_blockcount()
self.desc = 'sent transaction'
return True
def print_contract_addr(self):
pass

View file

@ -0,0 +1,33 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.bitcoin.tx.signed: Bitcoin signed transaction class
"""
import mmgen.tx.signed as TxBase
from .completed import Completed
from ....util import fmt,vmsg
class Signed(Completed,TxBase.Signed):
def compare_size_and_estimated_size(self,tx_decoded):
est_vsize = self.estimate_size()
d = tx_decoded
vsize = d['vsize'] if 'vsize' in d else d['size']
vmsg(f'\nVsize: {vsize} (true) {est_vsize} (estimated)')
ratio = float(est_vsize) / vsize
if not (0.95 < ratio < 1.05): # allow for 5% error
from ....exception import BadTxSizeEstimate
raise BadTxSizeEstimate(fmt(f"""
Estimated transaction vsize is {ratio:1.2f} times the true vsize
Your transaction fee estimates will be inaccurate
Please re-create and re-sign the transaction using the option --vsize-adj={1/ratio:1.2f}
""").strip())

View file

@ -0,0 +1,102 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.bitcoin.tx.status: Bitcoin transaction status class
"""
import time
import mmgen.tx.status as TxBase
from ....opts import opt
from ....util import msg,suf,die,secs_to_dhms
class Status(TxBase.Status):
async def display(self,usr_req=False):
tx = self.tx
class r(object):
pass
async def is_in_wallet():
try:
ret = await tx.rpc.call('gettransaction',tx.coin_txid)
except:
return False
if ret.get('confirmations',0) > 0:
r.confs = ret['confirmations']
return True
else:
return False
async def is_in_utxos():
try:
return 'txid' in await tx.rpc.call('getrawtransaction',tx.coin_txid,True)
except:
return False
async def is_in_mempool():
try:
return 'height' in await tx.rpc.call('getmempoolentry',tx.coin_txid)
except:
return False
async def is_replaced():
if await is_in_mempool():
return False
try:
ret = await tx.rpc.call('gettransaction',tx.coin_txid)
except:
return False
else:
if 'bip125-replaceable' in ret and ret.get('confirmations',1) <= 0:
r.replacing_confs = -ret['confirmations']
r.replacing_txs = ret['walletconflicts']
return True
else:
return False
if await is_in_mempool():
if usr_req:
d = await tx.rpc.call('gettransaction',tx.coin_txid)
rep = ('' if d.get('bip125-replaceable') == 'yes' else 'NOT ') + 'replaceable'
t = d['timereceived']
if opt.quiet:
msg('Transaction is in mempool')
else:
msg(f'TX status: in mempool, {rep}')
msg('Sent {} ({} ago)'.format(
time.strftime('%c',time.gmtime(t)),
secs_to_dhms(int(time.time()-t))) )
else:
msg('Warning: transaction is in mempool!')
elif await is_in_wallet():
die(0,f'Transaction has {r.confs} confirmation{suf(r.confs)}')
elif await is_in_utxos():
rdie(2,'ERROR: transaction is in the blockchain (but not in the tracking wallet)!')
elif await is_replaced():
msg('Transaction has been replaced')
msg('Replacement transaction ' + (
f'has {r.replacing_confs} confirmation{suf(r.replacing_confs)}'
if r.replacing_confs else
'is in mempool' ) )
if not opt.quiet:
msg('Replacing transactions:')
d = []
for txid in r.replacing_txs:
try:
d.append(await tx.rpc.call('getmempoolentry',txid))
except:
d.append({})
for txid,mp_entry in zip(r.replacing_txs,d):
msg(f' {txid}' + (' in mempool' if 'height' in mp_entry else '') )
die(0,'')

View file

@ -0,0 +1,84 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.bitcoin.tx.unsigned: Bitcoin unsigned transaction class
"""
import mmgen.tx.unsigned as TxBase
from .completed import Completed
from ....globalvars import *
from ....obj import HexStr,CoinTxID,MMGenDict
from ....util import msg,msg_r,ymsg,qmsg,suf
class Unsigned(Completed,TxBase.Unsigned):
desc = 'unsigned transaction'
async def sign(self,tx_num_str,keys): # return signed object or False; don't exit or raise exception
try:
self.check_correct_chain()
except TransactionChainMismatch:
return False
if (self.has_segwit_inputs() or self.has_segwit_outputs()) and not self.proto.cap('segwit'):
ymsg(f"TX has Segwit inputs or outputs, but {self.coin} doesn't support Segwit!")
return False
self.check_pubkey_scripts()
qmsg(f'Passing {len(keys)} key{suf(keys)} to {self.rpc.daemon.exec_fn}')
if self.has_segwit_inputs():
from ....addr import KeyGenerator,AddrGenerator
kg = KeyGenerator(self.proto,'std')
ag = AddrGenerator(self.proto,'segwit')
keydict = MMGenDict([(d.addr,d.sec) for d in keys])
sig_data = []
for d in self.inputs:
e = {k:getattr(d,k) for k in ('txid','vout','scriptPubKey','amt')}
e['amount'] = e['amt']
del e['amt']
if d.mmtype == 'S':
e['redeemScript'] = ag.to_segwit_redeem_script(kg.gen_data(keydict[d.addr]))
sig_data.append(e)
msg_r(f'Signing transaction{tx_num_str}...')
wifs = [d.sec.wif for d in keys]
try:
args = (
('signrawtransaction', self.serialized,sig_data,wifs,self.proto.sighash_type),
('signrawtransactionwithkey',self.serialized,wifs,sig_data,self.proto.sighash_type)
)['sign_with_key' in self.rpc.caps]
ret = await self.rpc.call(*args)
except Exception as e:
ymsg(self.rpc.daemon.sigfail_errmsg(e))
return False
from ....tx import SignedTX
try:
self.update_serialized(ret['hex'])
new = await SignedTX(data=self.__dict__)
tx_decoded = await self.rpc.call( 'decoderawtransaction', ret['hex'] )
new.compare_size_and_estimated_size(tx_decoded)
new.coin_txid = CoinTxID(self.deserialized.txid)
if not new.coin_txid == tx_decoded['txid']:
raise BadMMGenTxID('txid mismatch (after signing)')
msg('OK')
return new
except Exception as e:
ymsg(f'\n{e.args[0]}')
if g.traceback:
import traceback
ymsg( '\n' + ''.join(traceback.format_exception(*sys.exc_info())) )
return False

View file

@ -1,606 +0,0 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
altcoins.base_proto.ethereum.tx: Ethereum transaction classes
"""
import json
from collections import namedtuple
from decimal import Decimal
from ...globalvars import g
from ...color import red,yellow,blue,pink
from ...opts import opt
from ...util import msg,msg_r,ymsg,dmsg,fmt,line_input,is_int,is_hex_str,make_chksum_6,die,suf,capfirst,pp_fmt
from ...exception import TransactionChainMismatch
from ...obj import Int,Str,HexStr,CoinTxID,MMGenTxID,ETHNonce
from ...addr import MMGenID,CoinAddr,TokenAddr,is_mmgen_id,is_coin_addr
from ...amt import ETHAmt
from ...tx import MMGenTX
from ...twctl import TrackingWallet
from .contract import Token
class EthereumMMGenTX:
class Base(MMGenTX.Base):
rel_fee_desc = 'gas price'
rel_fee_disp = 'gas price in Gwei'
txobj = None # ""
tx_gas = ETHAmt(21000,'wei') # an approximate number, used for fee estimation purposes
start_gas = ETHAmt(21000,'wei') # the actual startgas amt used in the transaction
# for simple sends with no data, tx_gas = start_gas = 21000
contract_desc = 'contract'
usr_contract_data = HexStr('')
disable_fee_check = False
# given absolute fee in ETH, return gas price in Gwei using tx_gas
def fee_abs2rel(self,abs_fee,to_unit='Gwei'):
ret = ETHAmt(int(abs_fee.toWei() // self.tx_gas.toWei()),'wei')
dmsg(f'fee_abs2rel() ==> {ret} ETH')
return ret if to_unit == 'eth' else ret.to_unit(to_unit,show_decimal=True)
def get_hex_locktime(self):
return None # TODO
# given rel fee (gasPrice) in wei, return absolute fee using tx_gas (not in MMGenTX)
def fee_gasPrice2abs(self,rel_fee):
assert isinstance(rel_fee,int), f'{rel_fee!r}: incorrect type for fee estimate (not an integer)'
return ETHAmt(rel_fee * self.tx_gas.toWei(),'wei')
def is_replaceable(self):
return True
async def get_receipt(self,txid,silent=False):
rx = await self.rpc.call('eth_getTransactionReceipt','0x'+txid) # -> null if pending
if not rx:
return None
tx = await self.rpc.call('eth_getTransactionByHash','0x'+txid)
return namedtuple('exec_status',['status','gas_sent','gas_used','gas_price','contract_addr','tx','rx'])(
status = Int(rx['status'],16), # zero is failure, non-zero success
gas_sent = Int(tx['gas'],16),
gas_used = Int(rx['gasUsed'],16),
gas_price = ETHAmt(int(tx['gasPrice'],16),from_unit='wei'),
contract_addr = self.proto.coin_addr(rx['contractAddress'][2:]) if rx['contractAddress'] else None,
tx = tx,
rx = rx,
)
class New(Base,MMGenTX.New):
hexdata_type = 'hex'
desc = 'transaction'
fee_fail_fs = 'Network fee estimation failed'
no_chg_msg = 'Warning: Transaction leaves account with zero balance'
usr_fee_prompt = 'Enter transaction fee or gas price: '
def __init__(self,*args,**kwargs):
MMGenTX.New.__init__(self,*args,**kwargs)
if opt.tx_gas:
self.tx_gas = self.start_gas = ETHAmt(int(opt.tx_gas),'wei')
if opt.contract_data:
m = "'--contract-data' option may not be used with token transaction"
assert not 'Token' in type(self).__name__, m
with open(opt.contract_data) as fp:
self.usr_contract_data = HexStr(fp.read().strip())
self.disable_fee_check = True
async def get_nonce(self):
return ETHNonce(int(await self.rpc.call('eth_getTransactionCount','0x'+self.inputs[0].addr,'pending'),16))
async def make_txobj(self): # called by create_raw()
self.txobj = {
'from': self.inputs[0].addr,
'to': self.outputs[0].addr if self.outputs else Str(''),
'amt': self.outputs[0].amt if self.outputs else ETHAmt('0'),
'gasPrice': self.fee_abs2rel(self.usr_fee,to_unit='eth'),
'startGas': self.start_gas,
'nonce': await self.get_nonce(),
'chainId': self.rpc.chainID,
'data': self.usr_contract_data,
}
# Instead of serializing tx data as with BTC, just create a JSON dump.
# This complicates things but means we avoid using the rlp library to deserialize the data,
# thus removing an attack vector
async def create_raw(self):
assert len(self.inputs) == 1,'Transaction has more than one input!'
o_num = len(self.outputs)
o_ok = 0 if self.usr_contract_data else 1
assert o_num == o_ok, f'Transaction has {o_num} output{suf(o_num)} (should have {o_ok})'
await self.make_txobj()
odict = { k: str(v) for k,v in self.txobj.items() if k != 'token_to' }
self.hex = json.dumps(odict)
self.update_txid()
def update_txid(self):
assert not is_hex_str(self.hex),'update_txid() must be called only when self.hex is not hex data'
self.txid = MMGenTxID(make_chksum_6(self.hex).upper())
def del_output(self,idx):
pass
def process_cmd_args(self,cmd_args,ad_f,ad_w):
lc = len(cmd_args)
if lc == 0 and self.usr_contract_data and not 'Token' in type(self).__name__:
return
if lc != 1:
die(1,f'{lc} output{suf(lc)} specified, but Ethereum transactions must have exactly one')
for a in cmd_args:
self.process_cmd_arg(a,ad_f,ad_w)
def select_unspent(self,unspent):
while True:
reply = line_input('Enter an account to spend from: ').strip()
if reply:
if not is_int(reply):
msg('Account number must be an integer')
elif int(reply) < 1:
msg('Account number must be >= 1')
elif int(reply) > len(unspent):
msg(f'Account number must be <= {len(unspent)}')
else:
return [int(reply)]
# coin-specific fee routines:
@property
def relay_fee(self):
return ETHAmt('0') # TODO
# get rel_fee (gas price) from network, return in native wei
async def get_rel_fee_from_network(self):
return Int(await self.rpc.call('eth_gasPrice'),16),'eth_gasPrice' # ==> rel_fee,fe_type
def check_fee(self):
if not self.disable_fee_check:
assert self.usr_fee <= self.proto.max_tx_fee
# given rel fee and units, return absolute fee using tx_gas
def fee_rel2abs(self,tx_size,units,amt,unit):
return ETHAmt(
ETHAmt(amt,units[unit]).toWei() * self.tx_gas.toWei(),
from_unit='wei'
)
# given fee estimate (gas price) in wei, return absolute fee, adjusting by opt.tx_fee_adj
def fee_est2abs(self,rel_fee,fe_type=None):
ret = self.fee_gasPrice2abs(rel_fee) * opt.tx_fee_adj
if opt.verbose:
msg(f'Estimated fee: {ret} ETH')
return ret
def convert_and_check_fee(self,tx_fee,desc='Missing description'):
abs_fee = self.feespec2abs(tx_fee,None)
if abs_fee == False:
return False
elif not self.disable_fee_check and (abs_fee > self.proto.max_tx_fee):
msg('{} {c}: {} fee too large (maximum fee: {} {c})'.format(
abs_fee.hl(),
desc,
self.proto.max_tx_fee.hl(),
c = self.proto.coin ))
return False
else:
return abs_fee
def update_change_output(self,funds_left):
if self.outputs and self.outputs[0].is_chg:
self.update_output_amt(0,ETHAmt(funds_left))
async def get_cmdline_input_addrs(self):
ret = []
if opt.inputs:
r = (await TrackingWallet(self.proto)).data_root # must create new instance here
m = 'Address {!r} not in tracking wallet'
for i in opt.inputs.split(','):
if is_mmgen_id(self.proto,i):
for addr in r:
if r[addr]['mmid'] == i:
ret.append(addr)
break
else:
raise UserAddressNotInWallet(m.format(i))
elif is_coin_addr(self.proto,i):
if not i in r:
raise UserAddressNotInWallet(m.format(i))
ret.append(i)
else:
die(1,f'{i!r}: not an MMGen ID or coin address')
return ret
def final_inputs_ok_msg(self,funds_left):
chg = '0' if (self.outputs and self.outputs[0].is_chg) else funds_left
return 'Transaction leaves {} {} in the sender’s account'.format(
ETHAmt(chg).hl(),
self.proto.coin
)
class Completed(Base,MMGenTX.Completed):
fn_fee_unit = 'Mwei'
txview_hdr_fs = 'TRANSACTION DATA\n\nID={i} ({a} {c}) UTC={t} Sig={s} Locktime={l}\n'
txview_hdr_fs_short = 'TX {i} ({a} {c}) UTC={t} Sig={s} Locktime={l}\n'
txview_ftr_fs = fmt("""
Total in account: {i} {d}
Total to spend: {o} {d}
Remaining balance: {C} {d}
TX fee: {a} {c}{r}
""")
fmt_keys = ('from','to','amt','nonce')
@property
def send_amt(self):
return self.outputs[0].amt if self.outputs else self.proto.coin_amt('0')
@property
def fee(self):
return self.fee_gasPrice2abs(self.txobj['gasPrice'].toWei())
@property
def change(self):
return self.sum_inputs() - self.send_amt - self.fee
def check_txfile_hex_data(self):
pass
def format_view_body(self,blockcount,nonmm_str,max_mmwid,enl,terse,sort):
m = {}
for k in ('inputs','outputs'):
if len(getattr(self,k)):
m[k] = getattr(self,k)[0].mmid if len(getattr(self,k)) else ''
m[k] = ' ' + m[k].hl() if m[k] else ' ' + MMGenID.hlc(nonmm_str)
fs = """From: {}{f_mmid}
To: {}{t_mmid}
Amount: {} {c}
Gas price: {g} Gwei
Start gas: {G} Kwei
Nonce: {}
Data: {d}
\n""".replace('\t','')
t = self.txobj
td = t['data']
from ...color import yellow
return fs.format(
*((t[k] if t[k] != '' else Str('None')).hl() for k in self.fmt_keys),
d = '{}... ({} bytes)'.format(td[:40],len(td)//2) if len(td) else Str('None'),
c = self.proto.dcoin if len(self.outputs) else '',
g = yellow(str(t['gasPrice'].to_unit('Gwei',show_decimal=True))),
G = yellow(str(t['startGas'].to_unit('Kwei'))),
t_mmid = m['outputs'] if len(self.outputs) else '',
f_mmid = m['inputs'] )
def format_view_abs_fee(self):
return self.fee.hl() + (' (max)' if self.txobj['data'] else '')
def format_view_rel_fee(self,terse):
return ' ({} of spend amount)'.format(
pink('{:0.6f}%'.format( self.fee / self.send_amt * 100 ))
)
def format_view_verbose_footer(self):
if self.txobj['data']:
from .contract import parse_abi
return '\nParsed contract data: ' + pp_fmt(parse_abi(self.txobj['data']))
else:
return ''
def check_sigs(self,deserial_tx=None): # TODO
if is_hex_str(self.hex):
return True
return False
def check_pubkey_scripts(self):
pass
class Unsigned(Completed,MMGenTX.Unsigned):
hexdata_type = 'json'
desc = 'unsigned transaction'
def parse_txfile_hex_data(self):
d = json.loads(self.hex)
o = {
'from': CoinAddr(self.proto,d['from']),
# NB: for token, 'to' is sendto address
'to': CoinAddr(self.proto,d['to']) if d['to'] else Str(''),
'amt': ETHAmt(d['amt']),
'gasPrice': ETHAmt(d['gasPrice']),
'startGas': ETHAmt(d['startGas']),
'nonce': ETHNonce(d['nonce']),
'chainId': None if d['chainId'] == 'None' else Int(d['chainId']),
'data': HexStr(d['data']) }
self.tx_gas = o['startGas'] # approximate, but better than nothing
self.txobj = o
return d # 'token_addr','decimals' required by Token subclass
async def do_sign(self,wif,tx_num_str):
o = self.txobj
o_conv = {
'to': bytes.fromhex(o['to']),
'startgas': o['startGas'].toWei(),
'gasprice': o['gasPrice'].toWei(),
'value': o['amt'].toWei() if o['amt'] else 0,
'nonce': o['nonce'],
'data': bytes.fromhex(o['data']) }
from .pyethereum.transactions import Transaction
etx = Transaction(**o_conv).sign(wif,o['chainId'])
assert etx.sender.hex() == o['from'],(
'Sender address recovered from signature does not match true sender')
from . import rlp
self.hex = rlp.encode(etx).hex()
self.coin_txid = CoinTxID(etx.hash.hex())
if o['data']:
if o['to']:
assert self.txobj['token_addr'] == TokenAddr(etx.creates.hex()),'Token address mismatch'
else: # token- or contract-creating transaction
self.txobj['token_addr'] = TokenAddr(self.proto,etx.creates.hex())
assert self.check_sigs(),'Signature check failed'
async def sign(self,tx_num_str,keys): # return TX object or False; don't exit or raise exception
try:
self.check_correct_chain()
except TransactionChainMismatch:
return False
msg_r(f'Signing transaction{tx_num_str}...')
try:
await self.do_sign(keys[0].sec.wif,tx_num_str)
msg('OK')
return MMGenTX.Signed(data=self.__dict__)
except Exception as e:
msg("{e!s}: transaction signing failed!")
if g.traceback:
import traceback
ymsg('\n'+''.join(traceback.format_exception(*sys.exc_info())))
return False
class Signed(Completed,MMGenTX.Signed):
desc = 'signed transaction'
def parse_txfile_hex_data(self):
from .pyethereum.transactions import Transaction
from . import rlp
etx = rlp.decode(bytes.fromhex(self.hex),Transaction)
d = etx.to_dict() # ==> hex values have '0x' prefix, 0 is '0x'
for k in ('sender','to','data'):
if k in d:
d[k] = d[k].replace('0x','',1)
o = {
'from': CoinAddr(self.proto,d['sender']),
# NB: for token, 'to' is token address
'to': CoinAddr(self.proto,d['to']) if d['to'] else Str(''),
'amt': ETHAmt(d['value'],'wei'),
'gasPrice': ETHAmt(d['gasprice'],'wei'),
'startGas': ETHAmt(d['startgas'],'wei'),
'nonce': ETHNonce(d['nonce']),
'data': HexStr(d['data']) }
if o['data'] and not o['to']: # token- or contract-creating transaction
# NB: could be a non-token contract address:
o['token_addr'] = TokenAddr(self.proto,etx.creates.hex())
self.disable_fee_check = True
txid = CoinTxID(etx.hash.hex())
assert txid == self.coin_txid,"txid in tx.hex doesn't match value in MMGen transaction file"
self.tx_gas = o['startGas'] # approximate, but better than nothing
self.txobj = o
return d # 'token_addr','decimals' required by Token subclass
async def get_status(self,status=False):
class r(object):
pass
async def is_in_mempool():
if not 'full_node' in self.rpc.caps:
return False
if self.rpc.daemon.id in ('parity','openethereum'):
pool = [x['hash'] for x in await self.rpc.call('parity_pendingTransactions')]
elif self.rpc.daemon.id in ('geth','erigon'):
res = await self.rpc.call('txpool_content')
pool = list(res['pending']) + list(res['queued'])
return '0x'+self.coin_txid in pool
async def is_in_wallet():
d = await self.rpc.call('eth_getTransactionReceipt','0x'+self.coin_txid)
if d and 'blockNumber' in d and d['blockNumber'] is not None:
r.confs = 1 + int(await self.rpc.call('eth_blockNumber'),16) - int(d['blockNumber'],16)
r.exec_status = int(d['status'],16)
return True
return False
if await is_in_mempool():
msg('Transaction is in mempool' if status else 'Warning: transaction is in mempool!')
return
if status:
if await is_in_wallet():
if self.txobj['data']:
cd = capfirst(self.contract_desc)
if r.exec_status == 0:
msg(f'{cd} failed to execute!')
else:
msg(f'{cd} successfully executed with status {r.exec_status}')
die(0,f'Transaction has {r.confs} confirmation{suf(r.confs)}')
die(1,'Transaction is neither in mempool nor blockchain!')
async def send(self,prompt_user=True,exit_on_fail=False):
self.check_correct_chain()
if not self.disable_fee_check and (self.fee > self.proto.max_tx_fee):
die(2,'Transaction fee ({}) greater than {} max_tx_fee ({} {})!'.format(
self.fee,
self.proto.name,
self.proto.max_tx_fee,
self.proto.coin ))
await self.get_status()
if prompt_user:
self.confirm_send()
if g.bogus_send:
ret = None
else:
try:
ret = await self.rpc.call('eth_sendRawTransaction','0x'+self.hex)
except:
raise
ret = False
if ret == False:
msg(red(f'Send of MMGen transaction {self.txid} failed'))
if exit_on_fail:
sys.exit(1)
return False
else:
if g.bogus_send:
m = 'BOGUS transaction NOT sent: {}'
else:
m = 'Transaction sent: {}'
assert ret == '0x'+self.coin_txid,'txid mismatch (after sending)'
if self.proto.network == 'regtest' and g.daemon_id == 'erigon': # ERIGON
import asyncio
await asyncio.sleep(5)
self.desc = 'sent transaction'
msg(m.format(self.coin_txid.hl()))
self.add_timestamp()
self.add_blockcount()
return True
def print_contract_addr(self):
if 'token_addr' in self.txobj:
msg('Contract address: {}'.format(self.txobj['token_addr'].hl()))
class Bump(MMGenTX.Bump,Completed,New):
@property
def min_fee(self):
return ETHAmt(self.fee * Decimal('1.101'))
def bump_fee(self,idx,fee):
self.txobj['gasPrice'] = self.fee_abs2rel(fee,to_unit='eth')
async def get_nonce(self):
return self.txobj['nonce']
class EthereumTokenMMGenTX:
class Base(EthereumMMGenTX.Base):
tx_gas = ETHAmt(52000,'wei')
start_gas = ETHAmt(60000,'wei')
contract_desc = 'token contract'
class New(Base,EthereumMMGenTX.New):
desc = 'transaction'
fee_is_approximate = True
async def make_txobj(self): # called by create_raw()
await super().make_txobj()
t = Token(self.proto,self.tw.token,self.tw.decimals)
o = self.txobj
o['token_addr'] = t.addr
o['decimals'] = t.decimals
o['token_to'] = o['to']
o['data'] = t.create_data(o['token_to'],o['amt'])
def update_change_output(self,funds_left):
if self.outputs[0].is_chg:
self.update_output_amt(0,self.inputs[0].amt)
# token transaction, so check both eth and token balances
# TODO: add test with insufficient funds
async def precheck_sufficient_funds(self,inputs_sum,sel_unspent,outputs_sum):
eth_bal = await self.tw.get_eth_balance(sel_unspent[0].addr)
if eth_bal == 0: # we don't know the fee yet
msg('This account has no ether to pay for the transaction fee!')
return False
return await super().precheck_sufficient_funds(inputs_sum,sel_unspent,outputs_sum)
async def get_funds_left(self,fee,outputs_sum):
return ( await self.tw.get_eth_balance(self.inputs[0].addr) ) - fee
def final_inputs_ok_msg(self,funds_left):
token_bal = (
ETHAmt('0') if self.outputs[0].is_chg
else self.inputs[0].amt - self.outputs[0].amt
)
return "Transaction leaves ≈{} {} and {} {} in the sender's account".format(
funds_left.hl(),
self.proto.coin,
token_bal.hl(),
self.proto.dcoin
)
class Completed(Base,EthereumMMGenTX.Completed):
fmt_keys = ('from','token_to','amt','nonce')
@property
def change(self):
return self.sum_inputs() - self.send_amt
def format_view_rel_fee(self,terse):
return ''
def format_view_body(self,*args,**kwargs):
return 'Token: {d} {c}\n{r}'.format(
d = self.txobj['token_addr'].hl(),
c = blue('(' + self.proto.dcoin + ')'),
r = super().format_view_body(*args,**kwargs ))
class Unsigned(Completed,EthereumMMGenTX.Unsigned):
desc = 'unsigned transaction'
def parse_txfile_hex_data(self):
d = EthereumMMGenTX.Unsigned.parse_txfile_hex_data(self)
o = self.txobj
o['token_addr'] = TokenAddr(self.proto,d['token_addr'])
o['decimals'] = Int(d['decimals'])
t = Token(self.proto,o['token_addr'],o['decimals'])
o['data'] = t.create_data(o['to'],o['amt'])
o['token_to'] = t.transferdata2sendaddr(o['data'])
async def do_sign(self,wif,tx_num_str):
o = self.txobj
t = Token(self.proto,o['token_addr'],o['decimals'])
tx_in = t.make_tx_in(o['from'],o['to'],o['amt'],self.start_gas,o['gasPrice'],nonce=o['nonce'])
(self.hex,self.coin_txid) = await t.txsign(tx_in,wif,o['from'],chain_id=o['chainId'])
assert self.check_sigs(),'Signature check failed'
class Signed(Completed,EthereumMMGenTX.Signed):
desc = 'signed transaction'
def parse_txfile_hex_data(self):
d = EthereumMMGenTX.Signed.parse_txfile_hex_data(self)
o = self.txobj
assert self.tw.token == o['to']
o['token_addr'] = TokenAddr(self.proto,o['to'])
o['decimals'] = self.tw.decimals
t = Token(self.proto,o['token_addr'],o['decimals'])
o['amt'] = t.transferdata2amt(o['data'])
o['token_to'] = t.transferdata2sendaddr(o['data'])
class Bump(EthereumMMGenTX.Bump,Completed,New):
pass

View file

View file

@ -0,0 +1,69 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.ethereum.tx.base: Ethereum base transaction class
"""
from collections import namedtuple
import mmgen.tx.base as TxBase
from ....amt import ETHAmt
from ....obj import HexStr,Int
from ....util import dmsg
class Base(TxBase.Base):
rel_fee_desc = 'gas price'
rel_fee_disp = 'gas price in Gwei'
txobj = None # ""
tx_gas = ETHAmt(21000,'wei') # an approximate number, used for fee estimation purposes
start_gas = ETHAmt(21000,'wei') # the actual startgas amt used in the transaction
# for simple sends with no data, tx_gas = start_gas = 21000
contract_desc = 'contract'
usr_contract_data = HexStr('')
disable_fee_check = False
# given absolute fee in ETH, return gas price in Gwei using tx_gas
def fee_abs2rel(self,abs_fee,to_unit='Gwei'):
ret = ETHAmt(int(abs_fee.toWei() // self.tx_gas.toWei()),'wei')
dmsg(f'fee_abs2rel() ==> {ret} ETH')
return ret if to_unit == 'eth' else ret.to_unit(to_unit,show_decimal=True)
# given rel fee (gasPrice) in wei, return absolute fee using tx_gas (Ethereum-only method)
def fee_gasPrice2abs(self,rel_fee):
assert isinstance(rel_fee,int), f'{rel_fee!r}: incorrect type for fee estimate (not an integer)'
return ETHAmt(rel_fee * self.tx_gas.toWei(),'wei')
def is_replaceable(self):
return True
async def get_receipt(self,txid,silent=False):
rx = await self.rpc.call('eth_getTransactionReceipt','0x'+txid) # -> null if pending
if not rx:
return None
tx = await self.rpc.call('eth_getTransactionByHash','0x'+txid)
return namedtuple('exec_status',['status','gas_sent','gas_used','gas_price','contract_addr','tx','rx'])(
status = Int(rx['status'],16), # zero is failure, non-zero success
gas_sent = Int(tx['gas'],16),
gas_used = Int(rx['gasUsed'],16),
gas_price = ETHAmt(int(tx['gasPrice'],16),from_unit='wei'),
contract_addr = self.proto.coin_addr(rx['contractAddress'][2:]) if rx['contractAddress'] else None,
tx = tx,
rx = rx,
)
def check_serialized_integrity(self): # TODO
return True
class TokenBase(Base):
tx_gas = ETHAmt(52000,'wei')
start_gas = ETHAmt(60000,'wei')
contract_desc = 'token contract'

View file

@ -0,0 +1,35 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.ethereum.tx.bump: Ethereum transaction bump class
"""
import mmgen.tx.bump as TxBase
from .completed import Completed,TokenCompleted
from .new import New,TokenNew
from ....amt import ETHAmt
from decimal import Decimal
class Bump(Completed,New,TxBase.Bump):
desc = 'fee-bumped transaction'
@property
def min_fee(self):
return ETHAmt(self.fee * Decimal('1.101'))
def bump_fee(self,idx,fee):
self.txobj['gasPrice'] = self.fee_abs2rel(fee,to_unit='eth')
async def get_nonce(self):
return self.txobj['nonce']
class TokenBump(TokenCompleted,TokenNew,Bump):
desc = 'fee-bumped transaction'

View file

@ -0,0 +1,55 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.ethereum.tx.completed: Ethereum completed transaction class
"""
import mmgen.tx.completed as TxBase
from .base import Base,TokenBase
class Completed(Base,TxBase.Completed):
fn_fee_unit = 'Mwei'
@property
def send_amt(self):
return self.outputs[0].amt if self.outputs else self.proto.coin_amt('0')
@property
def fee(self):
return self.fee_gasPrice2abs(self.txobj['gasPrice'].toWei())
@property
def change(self):
return self.sum_inputs() - self.send_amt - self.fee
def check_txfile_hex_data(self):
pass
def check_sigs(self): # TODO
from ....util import is_hex_str
if is_hex_str(self.serialized):
return True
return False
def check_pubkey_scripts(self):
pass
def strfmt_locktime(self,locktime=None,terse=False):
pass
def get_serialized_locktime(self):
return None # TODO
class TokenCompleted(TokenBase,Completed):
@property
def change(self):
return self.sum_inputs() - self.send_amt

View file

@ -0,0 +1,83 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.ethereum.tx.info: Ethereum transaction info class
"""
from ....tx.info import TxInfo
from ....util import fmt,pp_fmt
from ....color import pink,yellow,blue
from ....addr import MMGenID
from ....obj import Str
class TxInfo(TxInfo):
txinfo_hdr_fs = 'TRANSACTION DATA\n\nID={i} ({a} {c}) UTC={t} Sig={s} Locktime={l}\n'
txinfo_hdr_fs_short = 'TX {i} ({a} {c}) UTC={t} Sig={s} Locktime={l}\n'
txinfo_ftr_fs = fmt("""
Total in account: {i} {d}
Total to spend: {o} {d}
Remaining balance: {C} {d}
TX fee: {a} {c}{r}
""")
fmt_keys = ('from','to','amt','nonce')
def format_body(self,blockcount,nonmm_str,max_mmwid,enl,terse,sort):
tx = self.tx
m = {}
for k in ('inputs','outputs'):
if len(getattr(tx,k)):
m[k] = getattr(tx,k)[0].mmid if len(getattr(tx,k)) else ''
m[k] = ' ' + m[k].hl() if m[k] else ' ' + MMGenID.hlc(nonmm_str)
fs = """From: {}{f_mmid}
To: {}{t_mmid}
Amount: {} {c}
Gas price: {g} Gwei
Start gas: {G} Kwei
Nonce: {}
Data: {d}
\n""".replace('\t','')
t = tx.txobj
td = t['data']
return fs.format(
*((t[k] if t[k] != '' else Str('None')).hl() for k in self.fmt_keys),
d = '{}... ({} bytes)'.format(td[:40],len(td)//2) if len(td) else Str('None'),
c = tx.proto.dcoin if len(tx.outputs) else '',
g = yellow(str(t['gasPrice'].to_unit('Gwei',show_decimal=True))),
G = yellow(str(t['startGas'].to_unit('Kwei'))),
t_mmid = m['outputs'] if len(tx.outputs) else '',
f_mmid = m['inputs'] )
def format_abs_fee(self):
return self.tx.fee.hl() + (' (max)' if self.tx.txobj['data'] else '')
def format_rel_fee(self,terse):
return ' ({} of spend amount)'.format(
pink('{:0.6f}%'.format( self.tx.fee / self.tx.send_amt * 100 ))
)
def format_verbose_footer(self):
if self.tx.txobj['data']:
from ..contract import parse_abi
return '\nParsed contract data: ' + pp_fmt(parse_abi(self.tx.txobj['data']))
else:
return ''
class TokenTxInfo(TxInfo):
fmt_keys = ('from','token_to','amt','nonce')
def format_rel_fee(self,terse):
return ''
def format_body(self,*args,**kwargs):
return 'Token: {d} {c}\n{r}'.format(
d = self.tx.txobj['token_addr'].hl(),
c = blue('(' + self.tx.proto.dcoin + ')'),
r = super().format_body(*args,**kwargs ))

View file

@ -0,0 +1,197 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.ethereum.tx.new: Ethereum new transaction class
"""
import json
import mmgen.tx.new as TxBase
from .base import Base,TokenBase
from ....opts import opt
from ....obj import Int,ETHNonce,MMGenTxID,Str
from ....amt import ETHAmt
from ....util import msg,line_input,is_int,is_hex_str,make_chksum_6
from ....twctl import TrackingWallet
from ....addr import is_mmgen_id,is_coin_addr
from ..contract import Token
class New(Base,TxBase.New):
desc = 'transaction'
fee_fail_fs = 'Network fee estimation failed'
no_chg_msg = 'Warning: Transaction leaves account with zero balance'
usr_fee_prompt = 'Enter transaction fee or gas price: '
hexdata_type = 'hex'
async def get_nonce(self):
return ETHNonce(int(await self.rpc.call('eth_getTransactionCount','0x'+self.inputs[0].addr,'pending'),16))
async def make_txobj(self): # called by create_serialized()
self.txobj = {
'from': self.inputs[0].addr,
'to': self.outputs[0].addr if self.outputs else Str(''),
'amt': self.outputs[0].amt if self.outputs else ETHAmt('0'),
'gasPrice': self.fee_abs2rel(self.usr_fee,to_unit='eth'),
'startGas': self.start_gas,
'nonce': await self.get_nonce(),
'chainId': self.rpc.chainID,
'data': self.usr_contract_data,
}
# Instead of serializing tx data as with BTC, just create a JSON dump.
# This complicates things but means we avoid using the rlp library to deserialize the data,
# thus removing an attack vector
async def create_serialized(self,locktime=None,bump=None):
assert len(self.inputs) == 1,'Transaction has more than one input!'
o_num = len(self.outputs)
o_ok = 0 if self.usr_contract_data else 1
assert o_num == o_ok, f'Transaction has {o_num} output{suf(o_num)} (should have {o_ok})'
await self.make_txobj()
odict = { k: str(v) for k,v in self.txobj.items() if k != 'token_to' }
self.serialized = json.dumps(odict)
self.update_txid()
def update_txid(self):
assert not is_hex_str(self.serialized), (
'update_txid() must be called only when self.serialized is not hex data' )
self.txid = MMGenTxID(make_chksum_6(self.serialized).upper())
def process_cmd_args(self,cmd_args,ad_f,ad_w):
lc = len(cmd_args)
if lc == 0 and self.usr_contract_data and not 'Token' in type(self).__name__:
return
if lc != 1:
die(1,f'{lc} output{suf(lc)} specified, but Ethereum transactions must have exactly one')
for a in cmd_args:
self.process_cmd_arg(a,ad_f,ad_w)
def select_unspent(self,unspent):
while True:
reply = line_input('Enter an account to spend from: ').strip()
if reply:
if not is_int(reply):
msg('Account number must be an integer')
elif int(reply) < 1:
msg('Account number must be >= 1')
elif int(reply) > len(unspent):
msg(f'Account number must be <= {len(unspent)}')
else:
return [int(reply)]
# get rel_fee (gas price) from network, return in native wei
async def get_rel_fee_from_network(self):
return Int(await self.rpc.call('eth_gasPrice'),16),'eth_gasPrice' # ==> rel_fee,fe_type
def check_fee(self):
if not self.disable_fee_check:
assert self.usr_fee <= self.proto.max_tx_fee
# given rel fee and units, return absolute fee using self.tx_gas
def fee_rel2abs(self,tx_size,units,amt,unit):
return ETHAmt(
ETHAmt(amt,units[unit]).toWei() * self.tx_gas.toWei(),
from_unit='wei'
)
# given fee estimate (gas price) in wei, return absolute fee, adjusting by opt.tx_fee_adj
def fee_est2abs(self,rel_fee,fe_type=None):
ret = self.fee_gasPrice2abs(rel_fee) * opt.tx_fee_adj
if opt.verbose:
msg(f'Estimated fee: {ret} ETH')
return ret
def convert_and_check_fee(self,tx_fee,desc):
abs_fee = self.feespec2abs(tx_fee,None)
if abs_fee == False:
return False
elif not self.disable_fee_check and (abs_fee > self.proto.max_tx_fee):
msg('{} {c}: {} fee too large (maximum fee: {} {c})'.format(
abs_fee.hl(),
desc,
self.proto.max_tx_fee.hl(),
c = self.proto.coin ))
return False
else:
return abs_fee
def update_change_output(self,funds_left):
if self.outputs and self.outputs[0].is_chg:
self.update_output_amt(0,ETHAmt(funds_left))
async def get_cmdline_input_addrs(self):
ret = []
if opt.inputs:
data_root = (await TrackingWallet(self.proto)).data_root # must create new instance here
errmsg = 'Address {!r} not in tracking wallet'
for addr in opt.inputs.split(','):
if is_mmgen_id(self.proto,addr):
for waddr in data_root:
if data_root[waddr]['mmid'] == addr:
ret.append(waddr)
break
else:
raise UserAddressNotInWallet(errmsg.format(addr))
elif is_coin_addr(self.proto,addr):
if not addr in data_root:
raise UserAddressNotInWallet(errmsg.format(addr))
ret.append(addr)
else:
die(1,f'{addr!r}: not an MMGen ID or coin address')
return ret
def final_inputs_ok_msg(self,funds_left):
chg = '0' if (self.outputs and self.outputs[0].is_chg) else funds_left
return 'Transaction leaves {} {} in the sender’s account'.format(
ETHAmt(chg).hl(),
self.proto.coin
)
class TokenNew(TokenBase,New):
desc = 'transaction'
fee_is_approximate = True
async def make_txobj(self): # called by create_serialized()
await super().make_txobj()
t = Token(self.proto,self.tw.token,self.tw.decimals)
o = self.txobj
o['token_addr'] = t.addr
o['decimals'] = t.decimals
o['token_to'] = o['to']
o['data'] = t.create_data(o['token_to'],o['amt'])
def update_change_output(self,funds_left):
if self.outputs[0].is_chg:
self.update_output_amt(0,self.inputs[0].amt)
# token transaction, so check both eth and token balances
# TODO: add test with insufficient funds
async def precheck_sufficient_funds(self,inputs_sum,sel_unspent,outputs_sum):
eth_bal = await self.tw.get_eth_balance(sel_unspent[0].addr)
if eth_bal == 0: # we don't know the fee yet
msg('This account has no ether to pay for the transaction fee!')
return False
return await super().precheck_sufficient_funds(inputs_sum,sel_unspent,outputs_sum)
async def get_funds_left(self,fee,outputs_sum):
return ( await self.tw.get_eth_balance(self.inputs[0].addr) ) - fee
def final_inputs_ok_msg(self,funds_left):
token_bal = (
ETHAmt('0') if self.outputs[0].is_chg
else self.inputs[0].amt - self.outputs[0].amt
)
return "Transaction leaves ≈{} {} and {} {} in the sender's account".format(
funds_left.hl(),
self.proto.coin,
token_bal.hl(),
self.proto.dcoin
)

View file

@ -0,0 +1,83 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# https://gitlab.com/mmgen/mmgen
"""
base_proto.ethereum.tx.online: Ethereum online signed transaction class
"""
from ....globalvars import *
import mmgen.tx.online as TxBase
from .signed import Signed,TokenSigned
from .. import erigon_sleep
from ....util import msg,rmsg
class OnlineSigned(Signed,TxBase.OnlineSigned):
async def send(self,prompt_user=True,exit_on_fail=False):
self.check_correct_chain()
if not self.disable_fee_check and (self.fee > self.proto.max_tx_fee):
die(2,'Transaction fee ({}) greater than {} max_tx_fee ({} {})!'.format(
self.fee,
self.proto.name,
self.proto.max_tx_fee,
self.proto.coin ))
await self.status.display()
if prompt_user:
self.confirm_send()
if g.bogus_send:
ret = None
else:
try:
ret = await self.rpc.call('eth_sendRawTransaction','0x'+self.serialized)
except:
raise
ret = False
if ret == False:
rmsg(f'Send of MMGen transaction {self.txid} failed')
if exit_on_fail:
sys.exit(1)
return False
else:
if g.bogus_send:
m = 'BOGUS transaction NOT sent: {}'
else:
m = 'Transaction sent: {}'
assert ret == '0x'+self.coin_txid,'txid mismatch (after sending)'
await erigon_sleep(self)
self.desc = 'sent transaction'
msg(m.format(self.coin_txid.hl()))
self.add_timestamp()
self.add_blockcount()
return True
def print_contract_addr(self):
if 'token_addr' in self.txobj:
msg('Contract address: {}'.format( self.txobj['token_addr'].hl() ))
class TokenOnlineSigned(TokenSigned,OnlineSigned):
def parse_txfile_serialized_data(self):
from ....addr import TokenAddr
from ..contract import Token
d = OnlineSigned.parse_txfile_serialized_data(self)
o = self.txobj
assert self.tw.token == o['to']
o['token_addr'] = TokenAddr(self.proto,o['to'])
o['decimals'] = self.tw.decimals
t = Token(self.proto,o['token_addr'],o['decimals'])
o['amt'] = t.transferdata2amt(o['data'])
o['token_to'] = t.transferdata2sendaddr(o['data'])

Some files were not shown because too many files have changed in this diff Show more