eliminate use of global vars g.proto, g.coin, g.rpc and others

This patch eliminates nearly all the global variables that changed during the
execution of scripts.  With a few minor exceptions, global vars are now used
only during initialization or reserved for cfg file / cmdline options and other
unchanging values.

The result is a code base that's much more maintainable and extensible and less
error-prone.  The autosigning code, which supports signing of transactions for
multiple protocols and networks, has been greatly simplified.

Doing away with globals required many changes throughout the code base, and
other related (and not so related) changes and cleanups were made along the
way, resulting in an enormous patch.

Additional code changes include:

    - tx.py: complete reorganization of TX classes and use of nesting

    - protocol.py: separation of Regtest and Testnet into distinct subclasses
      with separate address and transaction files and file extensions

    - new module help.py for the help notes, loaded on demand

    - addr.py: rewrite of the address file label parsing code

    - tx.py,tw.py: use of generators to create formatted text

User-visible changes include:

    - importing of addresses for tokens not yet in the user's tracking wallet
      is now performed with the `--token-addr` option instead of `--token`

Testing:

    Testing this patch requires a full run of the test suite as described on the
    Test-Suite wiki page.
This commit is contained in:
The MMGen Project 2020-05-28 09:53:34 +00:00
commit c3f185e8b0
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
63 changed files with 4295 additions and 3616 deletions

View file

@ -24,6 +24,7 @@ from hashlib import sha256,sha512
from .common import *
from .obj import *
from .baseconv import *
from .protocol import init_proto
pnm = g.proj_name
@ -32,11 +33,11 @@ def dmsg_sc(desc,data):
Msg(f'sc_debug_{desc}: {data}')
class AddrGenerator(MMGenObject):
def __new__(cls,addr_type):
def __new__(cls,proto,addr_type):
if type(addr_type) == str: # allow override w/o check
gen_method = addr_type
elif type(addr_type) == MMGenAddrType:
assert addr_type in proto.mmtypes, f'{addr_type}: invalid address type for coin {g.coin}'
assert addr_type in proto.mmtypes, f'{addr_type}: invalid address type for coin {proto.coin}'
gen_method = addr_type.gen_method
else:
raise TypeError(f'{type(addr_type)}: incorrect argument type for {cls.__name__}()')
@ -50,13 +51,14 @@ class AddrGenerator(MMGenObject):
assert gen_method in gen_methods
me = super(cls,cls).__new__(gen_methods[gen_method])
me.desc = gen_methods
me.proto = proto
return me
class AddrGeneratorP2PKH(AddrGenerator):
def to_addr(self,pubhex):
from .protocol import hash160
assert type(pubhex) == PubKey
return CoinAddr(g.proto.pubhash2addr(hash160(pubhex),p2sh=False))
return CoinAddr(self.proto,self.proto.pubhash2addr(hash160(pubhex),p2sh=False))
def to_segwit_redeem_script(self,pubhex):
raise NotImplementedError('Segwit redeem script not supported by this address type')
@ -64,24 +66,24 @@ class AddrGeneratorP2PKH(AddrGenerator):
class AddrGeneratorSegwit(AddrGenerator):
def to_addr(self,pubhex):
assert pubhex.compressed,'Uncompressed public keys incompatible with Segwit'
return CoinAddr(g.proto.pubhex2segwitaddr(pubhex))
return CoinAddr(self.proto,self.proto.pubhex2segwitaddr(pubhex))
def to_segwit_redeem_script(self,pubhex):
assert pubhex.compressed,'Uncompressed public keys incompatible with Segwit'
return HexStr(g.proto.pubhex2redeem_script(pubhex))
return HexStr(self.proto.pubhex2redeem_script(pubhex))
class AddrGeneratorBech32(AddrGenerator):
def to_addr(self,pubhex):
assert pubhex.compressed,'Uncompressed public keys incompatible with Segwit'
from .protocol import hash160
return CoinAddr(g.proto.pubhash2bech32addr(hash160(pubhex)))
return CoinAddr(self.proto,self.proto.pubhash2bech32addr(hash160(pubhex)))
def to_segwit_redeem_script(self,pubhex):
raise NotImplementedError('Segwit redeem script not supported by this address type')
class AddrGeneratorEthereum(AddrGenerator):
def __init__(self,addr_type):
def __init__(self,proto,addr_type):
try:
assert not g.use_internal_keccak_module
@ -95,7 +97,7 @@ class AddrGeneratorEthereum(AddrGenerator):
def to_addr(self,pubhex):
assert type(pubhex) == PubKey
return CoinAddr(self.keccak_256(bytes.fromhex(pubhex[2:])).hexdigest()[24:])
return CoinAddr(self.proto,self.keccak_256(bytes.fromhex(pubhex[2:])).hexdigest()[24:])
def to_wallet_passwd(self,sk_hex):
return WalletPassword(self.hash256(sk_hex)[:32])
@ -119,9 +121,9 @@ class AddrGeneratorZcashZ(AddrGenerator):
from nacl.bindings import crypto_scalarmult_base
p2 = crypto_scalarmult_base(self.zhash256(key,1))
from .protocol import _b58chk_encode
ver_bytes = g.proto.addr_fmt_to_ver_bytes('zcash_z')
ver_bytes = self.proto.addr_fmt_to_ver_bytes('zcash_z')
ret = _b58chk_encode(ver_bytes + self.zhash256(key,0) + p2)
return CoinAddr(ret)
return CoinAddr(self.proto,ret)
def to_viewkey(self,pubhex): # pubhex is really privhex
key = bytes.fromhex(pubhex)
@ -131,16 +133,16 @@ class AddrGeneratorZcashZ(AddrGenerator):
vk[63] &= 0x7f
vk[63] |= 0x40
from .protocol import _b58chk_encode
ver_bytes = g.proto.addr_fmt_to_ver_bytes('viewkey')
ver_bytes = self.proto.addr_fmt_to_ver_bytes('viewkey')
ret = _b58chk_encode(ver_bytes + vk)
return ZcashViewKey(ret)
return ZcashViewKey(self.proto,ret)
def to_segwit_redeem_script(self,pubhex):
raise NotImplementedError('Zcash z-addresses incompatible with Segwit')
class AddrGeneratorMonero(AddrGenerator):
def __init__(self,addr_type):
def __init__(self,proto,addr_type):
try:
assert not g.use_internal_keccak_module
@ -189,9 +191,10 @@ class AddrGeneratorMonero(AddrGenerator):
vk_hex = self.to_viewkey(sk_hex)
pk_str = self.encodepoint(scalarmultbase(hex2int_le(sk_hex)))
pvk_str = self.encodepoint(scalarmultbase(hex2int_le(vk_hex)))
addr_p1 = g.proto.addr_fmt_to_ver_bytes('monero') + pk_str + pvk_str
addr_p1 = self.proto.addr_fmt_to_ver_bytes('monero') + pk_str + pvk_str
return CoinAddr(
proto = self.proto,
addr = self.b58enc(addr_p1 + self.keccak_256(addr_p1).digest()[:4]) )
def to_wallet_passwd(self,sk_hex):
@ -200,34 +203,36 @@ class AddrGeneratorMonero(AddrGenerator):
def to_viewkey(self,sk_hex):
assert len(sk_hex) == 64, f'{len(sk_hex)}: incorrect privkey length'
return MoneroViewKey(
g.proto.preprocess_key(self.keccak_256(bytes.fromhex(sk_hex)).digest(),None).hex() )
self.proto.preprocess_key(self.keccak_256(bytes.fromhex(sk_hex)).digest(),None).hex() )
def to_segwit_redeem_script(self,sk_hex):
raise NotImplementedError('Monero addresses incompatible with Segwit')
class KeyGenerator(MMGenObject):
def __new__(cls,addr_type,generator=None,silent=False):
def __new__(cls,proto,addr_type,generator=None,silent=False):
if type(addr_type) == str: # allow override w/o check
pubkey_type = addr_type
elif type(addr_type) == MMGenAddrType:
assert addr_type in g.proto.mmtypes,'{}: invalid address type for coin {}'.format(addr_type,g.coin)
assert addr_type in proto.mmtypes, f'{address}: invalid address type for coin {proto.coin}'
pubkey_type = addr_type.pubkey_type
else:
raise TypeError('{}: incorrect argument type for {}()'.format(type(addr_type),cls.__name__))
raise TypeError(f'{type(addr_type)}: incorrect argument type for {cls.__name__}()')
if pubkey_type == 'std':
if cls.test_for_secp256k1(silent=silent) and generator != 1:
if not opt.key_generator or opt.key_generator == 2 or generator == 2:
return super(cls,cls).__new__(KeyGeneratorSecp256k1)
me = super(cls,cls).__new__(KeyGeneratorSecp256k1)
else:
qmsg('Using (slow) native Python ECDSA library for address generation')
return super(cls,cls).__new__(KeyGeneratorPython)
me = super(cls,cls).__new__(KeyGeneratorPython)
elif pubkey_type in ('zcash_z','monero'):
me = super(cls,cls).__new__(KeyGeneratorDummy)
me.desc = 'mmgen-'+pubkey_type
return me
else:
raise ValueError('{}: invalid pubkey_type argument'.format(pubkey_type))
raise ValueError(f'{pubkey_type}: invalid pubkey_type argument')
me.proto = proto
return me
@classmethod
def test_for_secp256k1(self,silent=False):
@ -288,19 +293,25 @@ class KeyGeneratorDummy(KeyGenerator):
assert type(privhex) == PrivKey
return PubKey(privhex,compressed=privhex.compressed)
class AddrListEntry(MMGenListItem):
addr = ListItemAttr('CoinAddr')
class AddrListEntryBase(MMGenListItem):
invalid_attrs = {'proto'}
def __init__(self,proto,**kwargs):
self.__dict__['proto'] = proto
MMGenListItem.__init__(self,**kwargs)
class AddrListEntry(AddrListEntryBase):
addr = ListItemAttr('CoinAddr',include_proto=True)
idx = ListItemAttr('AddrIdx') # not present in flat addrlists
label = ListItemAttr('TwComment',reassign_ok=True)
sec = ListItemAttr(PrivKey,typeconv=False)
viewkey = ListItemAttr('ViewKey')
sec = ListItemAttr('PrivKey',include_proto=True)
viewkey = ListItemAttr('ViewKey',include_proto=True)
wallet_passwd = ListItemAttr('WalletPassword')
class PasswordListEntry(MMGenListItem):
class PasswordListEntry(AddrListEntryBase):
passwd = ListItemAttr(str,typeconv=False) # TODO: create Password type
idx = ImmutableAttr('AddrIdx')
label = ListItemAttr('TwComment',reassign_ok=True)
sec = ListItemAttr(PrivKey,typeconv=False)
sec = ListItemAttr('PrivKey',include_proto=True)
class AddrListChksum(str,Hilite):
color = 'pink'
@ -335,7 +346,7 @@ class AddrListIDStr(str,Hilite):
if fmt_str:
ret = fmt_str.format(s)
else:
bc = (g.proto.base_coin,g.coin)[g.proto.base_coin=='ETH']
bc = (addrlist.proto.base_coin,addrlist.proto.coin)[addrlist.proto.base_coin=='ETH']
mt = addrlist.al_id.mmtype
ret = '{}{}{}[{}]'.format(addrlist.al_id.sid,('-'+bc,'')[bc=='BTC'],('-'+mt,'')[mt in ('L','E')],s)
@ -376,7 +387,7 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
chksum_rec_f = lambda foo,e: (str(e.idx), e.addr)
line_ctr = 0
def __init__(self,
def __init__(self,proto,
addrfile = '',
al_id = '',
adata = [],
@ -389,8 +400,14 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
do_chksum = True
self.update_msgs()
mmtype = mmtype or g.proto.dfl_mmtype
assert mmtype in MMGenAddrType.mmtypes,'{}: mmtype not in {}'.format(mmtype,repr(MMGenAddrType.mmtypes))
mmtype = mmtype or proto.dfl_mmtype
assert mmtype in MMGenAddrType.mmtypes, f'{mmtype}: mmtype not in {MMGenAddrType.mmtypes!r}'
from .protocol import CoinProtocol
self.bitcoin_addrtypes = tuple(
MMGenAddrType(CoinProtocol.Bitcoin,key).name for key in CoinProtocol.Bitcoin.mmtypes)
self.proto = proto
if seed and addr_idxs: # data from seed + idxs
self.al_id,src = AddrListID(seed.sid,mmtype),'gen'
@ -403,10 +420,10 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
do_chksum = False
elif addrlist: # data from flat address list
self.al_id = None
adata = AddrListList([AddrListEntry(addr=a) for a in set(addrlist)])
adata = AddrListData([AddrListEntry(proto=proto,addr=a) for a in set(addrlist)])
elif keylist: # data from flat key list
self.al_id = None
adata = AddrListList([AddrListEntry(sec=PrivKey(wif=k)) for k in set(keylist)])
adata = AddrListData([AddrListEntry(proto=proto,sec=PrivKey(proto=proto,wif=k)) for k in set(keylist)])
elif seed or addr_idxs:
die(3,'Must specify both seed and addr indexes')
elif al_id or adata:
@ -448,10 +465,10 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
gen_viewkey = type(self) == KeyAddrList and 'viewkey' in self.al_id.mmtype.extra_attrs
if self.gen_addrs:
kg = KeyGenerator(self.al_id.mmtype)
ag = AddrGenerator(self.al_id.mmtype)
kg = KeyGenerator(self.proto,self.al_id.mmtype)
ag = AddrGenerator(self.proto,self.al_id.mmtype)
t_addrs,num,pos,out = len(addrnums),0,0,AddrListList()
t_addrs,num,pos,out = len(addrnums),0,0,AddrListData()
le = self.entry_type
while pos != t_addrs:
@ -465,10 +482,11 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
if not g.debug:
qmsg_r('\rGenerating {} #{} ({} of {})'.format(self.gen_desc,num,pos,t_addrs))
e = le(idx=num)
e = le(proto=self.proto,idx=num)
# Secret key is double sha256 of seed hash round /num/
e.sec = PrivKey(
self.proto,
sha256(sha256(seed).digest()).digest(),
compressed = compressed,
pubkey_type = pubkey_type )
@ -497,17 +515,17 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
return True # format is checked when added to list entry object
def scramble_seed(self,seed):
is_btcfork = g.proto.base_coin == 'BTC'
if is_btcfork and self.al_id.mmtype == 'L' and not g.proto.testnet:
is_btcfork = self.proto.base_coin == 'BTC'
if is_btcfork and self.al_id.mmtype == 'L' and not self.proto.testnet:
dmsg_sc('str','(none)')
return seed
if g.proto.base_coin == 'ETH':
scramble_key = g.coin.lower()
if self.proto.base_coin == 'ETH':
scramble_key = self.proto.coin.lower()
else:
scramble_key = (g.coin.lower()+':','')[is_btcfork] + self.al_id.mmtype.name
scramble_key = (self.proto.coin.lower()+':','')[is_btcfork] + self.al_id.mmtype.name
from .crypto import scramble_seed
if g.proto.testnet:
scramble_key += ':testnet'
if self.proto.testnet:
scramble_key += ':' + self.proto.network
dmsg_sc('str',scramble_key)
return scramble_seed(seed,scramble_key.encode())
@ -517,7 +535,7 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
self.ext += '.'+g.mmenc_ext
def write_to_file(self,ask_tty=True,ask_write_default_yes=False,binary=False,desc=None):
tn = ('','.testnet')[g.proto.testnet]
tn = ('.' + self.proto.network) if self.proto.testnet else ''
fn = '{}{x}{}.{}'.format(self.id_str,tn,self.ext,x='-α' if g.debug_utf8 else '')
ask_tty = self.has_keys and not opt.quiet
write_data_to_file(fn,self.fmt_data,desc or self.file_desc,ask_tty=ask_tty,binary=binary)
@ -554,12 +572,14 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
if idx == e.idx:
e.label = comment
def make_reverse_dict(self,coinaddrs):
d,b = MMGenDict(),coinaddrs
def make_reverse_dict_addrlist(self,coinaddrs):
d = MMGenDict()
b = coinaddrs
for e in self.data:
try:
d[b[b.index(e.addr)]] = MMGenID('{}:{}'.format(self.al_id,e.idx)),e.label
except: pass
d[b[b.index(e.addr)]] = ( MMGenID(self.proto, f'{self.al_id}:{e.idx}'), e.label )
except ValueError:
pass
return d
def remove_dup_keys(self,cmplist):
@ -585,9 +605,9 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
def generate_addrs_from_keys(self):
# assume that the first listed mmtype is valid for flat key list
t = MMGenAddrType(g.proto.mmtypes[0])
kg = KeyGenerator(t.pubkey_type)
ag = AddrGenerator(t.gen_method)
t = self.proto.addr_type(self.proto.mmtypes[0])
kg = KeyGenerator(self.proto,t.pubkey_type)
ag = AddrGenerator(self.proto,t.gen_method)
d = self.data
for n,e in enumerate(d,1):
qmsg_r('\rGenerating addresses from keylist: {}/{}'.format(n,len(d)))
@ -597,10 +617,10 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
qmsg('\rGenerated addresses from keylist: {}/{} '.format(n,len(d)))
def make_label(self):
bc,mt = g.proto.base_coin,self.al_id.mmtype
l_coin = [] if bc == 'BTC' else [g.coin] if bc == 'ETH' else [bc]
l_type = [] if mt == 'E' or (mt == 'L' and not g.proto.testnet) else [mt.name.upper()]
l_tn = [] if not g.proto.testnet else ['TESTNET']
bc,mt = self.proto.base_coin,self.al_id.mmtype
l_coin = [] if bc == 'BTC' else [self.proto.coin] if bc == 'ETH' else [bc]
l_type = [] if mt == 'E' or (mt == 'L' and not self.proto.testnet) else [mt.name.upper()]
l_tn = [] if not self.proto.testnet else [self.proto.network.upper()]
lbl_p2 = ':'.join(l_coin+l_type+l_tn)
return self.al_id.sid + ('',' ')[bool(lbl_p2)] + lbl_p2
@ -646,34 +666,36 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
def parse_file_body(self,lines):
ret = AddrListList()
ret = AddrListData()
le = self.entry_type
iifs = "{!r}: invalid identifier [expected '{}:']"
while lines:
idx,addr,lbl = self.get_line(lines)
assert is_mmgen_idx(idx),'invalid address index {!r}'.format(idx)
assert is_mmgen_idx(idx), f'invalid address index {idx!r}'
self.check_format(addr)
a = le(**{ 'idx':int(idx), self.main_attr:addr, 'label':lbl })
a = le(**{ 'proto': self.proto, 'idx':int(idx), self.main_attr:addr, 'label':lbl })
if self.has_keys: # order: wif,(orig_hex),viewkey,wallet_passwd
d = self.get_line(lines)
assert d[0] == self.al_id.mmtype.wif_label+':',iifs.format(d[0],self.al_id.mmtype.wif_label)
a.sec = PrivKey(wif=d[1])
for k,dtype in (('viewkey',ViewKey),('wallet_passwd',WalletPassword)):
a.sec = PrivKey(proto=self.proto,wif=d[1])
for k,dtype,add_proto in (
('viewkey',ViewKey,True),
('wallet_passwd',WalletPassword,False) ):
if k in self.al_id.mmtype.extra_attrs:
d = self.get_line(lines)
assert d[0] == k+':',iifs.format(d[0],k)
setattr(a,k,dtype(d[1]))
setattr(a,k,dtype( *((self.proto,d[1]) if add_proto else (d[1],)) ) )
ret.append(a)
if self.has_keys:
if (hasattr(opt,'yes') and opt.yes) or keypress_confirm('Check key-to-address validity?'):
kg = KeyGenerator(self.al_id.mmtype)
ag = AddrGenerator(self.al_id.mmtype)
kg = KeyGenerator(self.proto,self.al_id.mmtype)
ag = AddrGenerator(self.proto,self.al_id.mmtype)
llen = len(ret)
for n,e in enumerate(ret):
qmsg_r('\rVerifying keys {}/{}'.format(n+1,llen))
@ -685,35 +707,46 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
def parse_file(self,fn,buf=[],exit_on_error=True):
def parse_addrfile_label(lbl): # we must maintain backwards compat, so parse is tricky
al_coin,al_mmtype = None,None
tn = lbl[-8:] == ':TESTNET'
if tn:
assert g.proto.testnet, f'{self.data_desc} file is testnet but protocol is mainnet!'
def parse_addrfile_label(lbl):
"""
label examples:
- Bitcoin legacy mainnet: no label
- Bitcoin legacy testnet: 'LEGACY:TESTNET'
- Bitcoin Segwit: 'SEGWIT'
- Bitcoin Segwit testnet: 'SEGWIT:TESTNET'
- Bitcoin Bech32 regtest: 'BECH32:REGTEST'
- Litecoin legacy mainnet: 'LTC'
- Litecoin Bech32 mainnet: 'LTC:BECH32'
- Litecoin legacy testnet: 'LTC:LEGACY:TESTNET'
- Ethereum mainnet: 'ETH'
- Ethereum Classic mainnet: 'ETC'
- Ethereum regtest: 'ETH:REGTEST'
"""
lbl = lbl.lower()
# remove the network component:
if lbl.endswith(':testnet'):
network = 'testnet'
lbl = lbl[:-8]
elif lbl.endswith(':regtest'):
network = 'regtest'
lbl = lbl[:-8]
else:
assert not g.proto.testnet, f'{self.data_desc} file is mainnet but protocol is testnet!'
lbl = lbl.split(':',1)
if len(lbl) == 2:
al_coin,al_mmtype = lbl[0],lbl[1].lower()
else:
if lbl[0].lower() in MMGenAddrType.get_names():
al_mmtype = lbl[0].lower()
else:
al_coin = lbl[0]
network = 'mainnet'
# this block fails if al_mmtype is invalid for g.coin
if not al_mmtype:
mmtype = MMGenAddrType('E' if al_coin in ('ETH','ETC') else 'L',on_fail='raise')
else:
mmtype = MMGenAddrType(al_mmtype,on_fail='raise')
if lbl in self.bitcoin_addrtypes:
coin,mmtype_key = ( 'BTC', lbl )
elif ':' in lbl: # first component is coin, second is mmtype_key
coin,mmtype_key = lbl.split(':')
else: # only component is coin
coin,mmtype_key = ( lbl, None )
from .protocol import init_proto
return (init_proto(al_coin or 'BTC').base_coin, mmtype, tn)
proto = init_proto(coin=coin,network=network)
def check_coin_mismatch(base_coin): # die if addrfile coin doesn't match g.coin
m = '{} address file format, but base coin is {}!'
assert base_coin == g.proto.base_coin, m.format(base_coin,g.proto.base_coin)
if mmtype_key == None:
mmtype_key = proto.mmtypes[0]
return ( proto, proto.addr_type(mmtype_key) )
lines = get_lines_from_file(fn,self.data_desc+' data',trim_comments=True)
@ -732,20 +765,31 @@ Removed {{}} duplicate WIF key{{}} from keylist (also in {pnm} key-address file
self.set_pw_fmt(ss[0])
self.set_pw_len(ss[1])
self.pw_id_str = MMGenPWIDString(ls.pop())
base_coin,mmtype = None,MMGenPasswordType('P')
testnet = False
proto = init_proto('btc')# FIXME: dummy protocol
mmtype = MMGenPasswordType(proto,'P')
elif len(ls) == 1:
base_coin,mmtype,testnet = parse_addrfile_label(ls[0])
check_coin_mismatch(base_coin)
proto,mmtype = parse_addrfile_label(ls[0])
elif len(ls) == 0:
base_coin,mmtype = 'BTC',MMGenAddrType('L')
testnet = False
check_coin_mismatch(base_coin)
proto = init_proto('btc')
mmtype = proto.addr_type('L')
else:
raise ValueError("'{}': Invalid first line for {} file '{}'".format(lines[0],self.gen_desc,fn))
raise ValueError(f'{lines[0]}: Invalid first line for {self.gen_desc} file {fn!r}')
self.base_coin = base_coin
self.is_testnet = testnet
if type(self) != PasswordList:
if proto.base_coin != self.proto.base_coin or proto.network != self.proto.network:
"""
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())
"""
raise ValueError(
f'{self.data_desc} file is '
+ f'{proto.base_coin} {proto.network} but protocol is '
+ f'{self.proto.base_coin} {self.proto.network}' )
self.base_coin = proto.base_coin
self.network = proto.network
self.al_id = AddrListID(SeedID(sid=sid),mmtype)
data = self.parse_file_body(lines[1:-1])
@ -850,7 +894,7 @@ Record this checksum: it will be used to verify the password file in the future
feature_warn_fs = 'WARNING: {!r} is a potentially dangerous feature. Use at your own risk!'
hex2bip39 = False
def __init__(self,
def __init__(self,proto,
infile = None,
seed = None,
pw_idxs = None,
@ -860,6 +904,7 @@ Record this checksum: it will be used to verify the password file in the future
chk_params_only = False
):
self.proto = proto # proto is ignored
self.update_msgs()
if infile:
@ -877,7 +922,7 @@ Record this checksum: it will be used to verify the password file in the future
if self.hex2bip39:
ymsg(self.feature_warn_fs.format(pw_fmt))
self.set_pw_len_vs_seed_len(pw_len,seed)
self.al_id = AddrListID(seed.sid,MMGenPasswordType('P'))
self.al_id = AddrListID(seed.sid,MMGenPasswordType(self.proto,'P'))
self.data = self.generate(seed,pw_idxs)
if self.pw_fmt in ('bip39','xmrseed'):
@ -983,7 +1028,6 @@ Record this checksum: it will be used to verify the password file in the future
pw_len_hex = baseconv.seedlen_map_rev['xmrseed'][self.pw_len] * 2
# take most significant part
bytes_trunc = bytes.fromhex(hex_sec[:pw_len_hex])
from .protocol import init_proto
bytes_preproc = init_proto('xmr').preprocess_key(bytes_trunc,None)
return ' '.join(baseconv.frombytes(bytes_preproc,wl_id='xmrseed'))
else:
@ -1043,11 +1087,13 @@ re-import your addresses.
""".strip().format(pnm=pnm)
}
def __new__(cls,*args,**kwargs):
return MMGenObject.__new__(altcoin_subclass(cls,'tw','AddrData'))
def __new__(cls,proto,*args,**kwargs):
return MMGenObject.__new__(altcoin_subclass(cls,proto,'tw'))
def __init__(self,*args,**kwargs):
def __init__(self,proto,*args,**kwargs):
self.al_ids = {}
self.proto = proto
self.rpc = None
def seed_ids(self):
return list(self.al_ids.keys())
@ -1058,7 +1104,7 @@ re-import your addresses.
return self.al_ids[al_id]
def mmaddr2coinaddr(self,mmaddr):
al_id,idx = MMGenID(mmaddr).rsplit(':',1)
al_id,idx = MMGenID(self.proto,mmaddr).rsplit(':',1)
coinaddr = ''
if al_id in self.al_ids:
coinaddr = self.addrlist(al_id).coinaddr(int(idx))
@ -1068,38 +1114,6 @@ re-import your addresses.
d = self.make_reverse_dict([coinaddr])
return (list(d.values())[0][0]) if d else None
@classmethod
async def get_tw_data(cls,wallet=None):
vmsg('Getting address data from tracking wallet')
if 'label_api' in g.rpc.caps:
accts = await g.rpc.call('listlabels')
ll = await g.rpc.batch_call('getaddressesbylabel',[(k,) for k in accts])
alists = [list(a.keys()) for a in ll]
else:
accts = await g.rpc.call('listaccounts',0,True)
alists = await g.rpc.batch_call('getaddressesbyaccount',[(k,) for k in accts])
return list(zip(accts,alists))
async def add_tw_data(self,wallet):
twd = await type(self).get_tw_data(wallet)
out,i = {},0
for acct,addr_array in twd:
l = TwLabel(acct,on_fail='silent')
if l and l.mmid.type == 'mmgen':
obj = l.mmid.obj
if len(addr_array) != 1:
die(2,self.msgs['too_many_acct_addresses'].format(acct))
al_id = AddrListID(SeedID(sid=obj.sid),MMGenAddrType(obj.mmtype))
if al_id not in out:
out[al_id] = []
out[al_id].append(AddrListEntry(idx=obj.idx,addr=addr_array[0],label=l.comment))
i += 1
vmsg('{n} {pnm} addresses found, {m} accounts total'.format(n=i,pnm=pnm,m=len(twd)))
for al_id in out:
self.add(AddrList(al_id=al_id,adata=AddrListList(sorted(out[al_id],key=lambda a: a.idx))))
def add(self,addrlist):
if type(addrlist) == AddrList:
self.al_ids[addrlist.al_id] = addrlist
@ -1110,17 +1124,53 @@ re-import your addresses.
def make_reverse_dict(self,coinaddrs):
d = MMGenDict()
for al_id in self.al_ids:
d.update(self.al_ids[al_id].make_reverse_dict(coinaddrs))
d.update(self.al_ids[al_id].make_reverse_dict_addrlist(coinaddrs))
return d
class TwAddrData(AddrData,metaclass=aInitMeta):
def __new__(cls,*args,**kwargs):
return MMGenObject.__new__(altcoin_subclass(cls,'tw','TwAddrData'))
def __new__(cls,proto,*args,**kwargs):
return MMGenObject.__new__(altcoin_subclass(cls,proto,'tw'))
def __init__(self,*args,**kwargs):
def __init__(self,proto,*args,**kwargs):
pass
async def __ainit__(self,wallet=None):
async def __ainit__(self,proto,wallet=None):
self.proto = proto
from .rpc import rpc_init
self.rpc = await rpc_init(proto)
self.al_ids = {}
await self.add_tw_data(wallet)
async def get_tw_data(self,wallet=None):
vmsg('Getting address data from tracking wallet')
c = self.rpc
if 'label_api' in c.caps:
accts = await c.call('listlabels')
ll = await c.batch_call('getaddressesbylabel',[(k,) for k in accts])
alists = [list(a.keys()) for a in ll]
else:
accts = await c.call('listaccounts',0,True)
alists = await c.batch_call('getaddressesbyaccount',[(k,) for k in accts])
return list(zip(accts,alists))
async def add_tw_data(self,wallet):
twd = await self.get_tw_data(wallet)
out,i = {},0
for acct,addr_array in twd:
l = TwLabel(self.proto,acct,on_fail='silent')
if l and l.mmid.type == 'mmgen':
obj = l.mmid.obj
if len(addr_array) != 1:
die(2,self.msgs['too_many_acct_addresses'].format(acct))
al_id = AddrListID(SeedID(sid=obj.sid),self.proto.addr_type(obj.mmtype))
if al_id not in out:
out[al_id] = []
out[al_id].append(AddrListEntry(self.proto,idx=obj.idx,addr=addr_array[0],label=l.comment))
i += 1
vmsg('{n} {pnm} addresses found, {m} accounts total'.format(n=i,pnm=pnm,m=len(twd)))
for al_id in out:
self.add(AddrList(self.proto,al_id=al_id,adata=AddrListData(sorted(out[al_id],key=lambda a: a.idx))))

View file

@ -37,13 +37,13 @@ except:
def parse_abi(s):
return [s[:8]] + [s[8+x*64:8+(x+1)*64] for x in range(len(s[8:])//64)]
def create_method_id(sig): return keccak_256(sig.encode()).hexdigest()[:8]
def create_method_id(sig):
return keccak_256(sig.encode()).hexdigest()[:8]
class TokenBase(MMGenObject): # ERC20
@staticmethod
def transferdata2sendaddr(data): # online
return CoinAddr(parse_abi(data)[1][-40:])
def transferdata2sendaddr(self,data): # online
return CoinAddr(self.proto,parse_abi(data)[1][-40:])
def transferdata2amt(self,data): # online
return ETHAmt(int(parse_abi(data)[-1],16) * self.base_unit)
@ -52,7 +52,7 @@ class TokenBase(MMGenObject): # ERC20
data = create_method_id(method_sig) + method_args
if g.debug:
msg('ETH_CALL {}: {}'.format(method_sig,'\n '.join(parse_abi(data))))
ret = await g.rpc.call('eth_call',{ 'to': '0x'+self.addr, 'data': '0x'+data })
ret = await self.rpc.call('eth_call',{ 'to': '0x'+self.addr, 'data': '0x'+data })
if toUnit:
return int(ret,16) * self.base_unit
else:
@ -91,7 +91,7 @@ class TokenBase(MMGenObject): # ERC20
'total supply:', await self.get_total_supply())
async def code(self):
return (await g.rpc.call('eth_getCode','0x'+self.addr))[2:]
return (await self.rpc.call('eth_getCode','0x'+self.addr))[2:]
def create_data(self,to_addr,amt,method_sig='transfer(address,uint256)',from_addr=None):
from_arg = from_addr.rjust(64,'0') if from_addr else ''
@ -114,14 +114,13 @@ class TokenBase(MMGenObject): # ERC20
from .pyethereum.transactions import Transaction
if chain_id is None:
chain_id_method = ('parity_chainId','eth_chainId')['eth_chainId' in g.rpc.caps]
chain_id = int(await g.rpc.call(chain_id_method),16)
chain_id_method = ('parity_chainId','eth_chainId')['eth_chainId' in self.rpc.caps]
chain_id = int(await self.rpc.call(chain_id_method),16)
tx = Transaction(**tx_in).sign(key,chain_id)
hex_tx = rlp.encode(tx).hex()
coin_txid = CoinTxID(tx.hash.hex())
if tx.sender.hex() != from_addr:
m = "Sender address '{}' does not match address of key '{}'!"
die(3,m.format(from_addr,tx.sender.hex()))
die(3,f'Sender address {from_addr!r} does not match address of key {tx.sender.hex()!r}!')
if g.debug:
msg('TOKEN DATA:')
pp_msg(tx.to_dict())
@ -131,7 +130,7 @@ class TokenBase(MMGenObject): # ERC20
# The following are used for token deployment only:
async def txsend(self,hex_tx):
return (await g.rpc.call('eth_sendRawTransaction','0x'+hex_tx)).replace('0x','',1)
return (await self.rpc.call('eth_sendRawTransaction','0x'+hex_tx)).replace('0x','',1)
async def transfer( self,from_addr,to_addr,amt,key,start_gas,gasPrice,
method_sig='transfer(address,uint256)',
@ -140,7 +139,7 @@ class TokenBase(MMGenObject): # ERC20
tx_in = self.make_tx_in(
from_addr,to_addr,amt,
start_gas,gasPrice,
nonce = int(await g.rpc.call('parity_nextNonce','0x'+from_addr),16),
nonce = int(await self.rpc.call('parity_nextNonce','0x'+from_addr),16),
method_sig = method_sig,
from_addr2 = from_addr2 )
(hex_tx,coin_txid) = await self.txsign(tx_in,key,from_addr)
@ -148,20 +147,24 @@ class TokenBase(MMGenObject): # ERC20
class Token(TokenBase):
def __init__(self,addr,decimals):
self.addr = TokenAddr(addr)
def __init__(self,proto,addr,decimals,rpc=None):
self.proto = proto
self.addr = TokenAddr(proto,addr)
assert isinstance(decimals,int),f'decimals param must be int instance, not {type(decimals)}'
self.decimals = decimals
self.base_unit = Decimal('10') ** -self.decimals
self.rpc = rpc
class TokenResolve(TokenBase,metaclass=aInitMeta):
def __init__(self,addr):
def __init__(self,*args,**kwargs):
return super().__init__()
async def __ainit__(self,addr):
self.addr = TokenAddr(addr)
async def __ainit__(self,proto,rpc,addr):
self.proto = proto
self.rpc = rpc
self.addr = TokenAddr(proto,addr)
decimals = await self.get_decimals() # requires self.addr!
if not decimals:
raise TokenNotInBlockchain(f'Token {addr!r} not in blockchain')
Token.__init__(self,addr,decimals)
Token.__init__(self,proto,addr,decimals,rpc)

View file

@ -21,7 +21,7 @@ altcoins.eth.tw: Ethereum tracking wallet and related classes for the MMGen suit
"""
from mmgen.common import *
from mmgen.obj import ETHAmt,TwLabel,is_coin_addr,is_mmgen_id,MMGenListItem,ListItemAttr,ImmutableAttr
from mmgen.obj import ETHAmt,TwLabel,is_coin_addr,is_mmgen_id,ListItemAttr,ImmutableAttr
from mmgen.tw import TrackingWallet,TwAddrList,TwUnspentOutputs,TwGetBalance
from mmgen.addr import AddrData,TwAddrData
from .contract import Token,TokenResolve
@ -36,7 +36,7 @@ class EthereumTrackingWallet(TrackingWallet):
return addr in self.data_root
def init_empty(self):
self.data = { 'coin': g.coin, 'accounts': {}, 'tokens': {} }
self.data = { 'coin': self.proto.coin, 'accounts': {}, 'tokens': {} }
def upgrade_wallet_maybe(self):
@ -49,7 +49,7 @@ class EthereumTrackingWallet(TrackingWallet):
import json
self.data['accounts'] = json.loads(self.orig_data)
if not 'coin' in self.data:
self.data['coin'] = g.coin
self.data['coin'] = self.proto.coin
upgraded = True
def have_token_params_fields():
@ -75,7 +75,7 @@ class EthereumTrackingWallet(TrackingWallet):
msg('{} upgraded successfully!'.format(self.desc))
async def rpc_get_balance(self,addr):
return ETHAmt(int(await g.rpc.call('eth_getBalance','0x'+addr),16),'wei')
return ETHAmt(int(await self.rpc.call('eth_getBalance','0x'+addr),16),'wei')
@write_mode
async def batch_import_address(self,args_list):
@ -97,9 +97,9 @@ class EthereumTrackingWallet(TrackingWallet):
async def remove_address(self,addr):
r = self.data_root
if is_coin_addr(addr):
if is_coin_addr(self.proto,addr):
have_match = lambda k: k == addr
elif is_mmgen_id(addr):
elif is_mmgen_id(self.proto,addr):
have_match = lambda k: r[k]['mmid'] == addr
else:
die(1,f'{addr!r} is not an Ethereum address or MMGen ID')
@ -107,7 +107,7 @@ class EthereumTrackingWallet(TrackingWallet):
for k in r:
if have_match(k):
# return the addr resolved to mmid if possible
ret = r[k]['mmid'] if is_mmgen_id(r[k]['mmid']) else addr
ret = r[k]['mmid'] if is_mmgen_id(self.proto,r[k]['mmid']) else addr
del r[k]
self.write()
return ret
@ -152,30 +152,33 @@ class EthereumTokenTrackingWallet(EthereumTrackingWallet):
symbol = None
cur_eth_balances = {}
async def __ainit__(self,mode='r'):
await super().__ainit__(mode=mode)
async def __ainit__(self,proto,mode='r',token_addr=None):
await super().__ainit__(proto,mode=mode)
for v in self.data['tokens'].values():
self.conv_types(v)
if not is_coin_addr(g.token):
g.token = await self.sym2addr(g.token) # returns None on failure
if self.importing and token_addr:
if not is_coin_addr(proto,token_addr):
raise InvalidTokenAddress(f'{token_addr!r}: invalid token address')
else:
assert token_addr == None,'EthereumTokenTrackingWallet_chk1'
token_addr = await self.sym2addr(proto.tokensym) # returns None on failure
if not is_coin_addr(proto,token_addr):
raise UnrecognizedTokenSymbol(f'Specified token {proto.tokensym!r} could not be resolved!')
if not is_coin_addr(g.token):
if self.importing:
m = 'When importing addresses for a new token, the token must be specified by address, not symbol.'
raise InvalidTokenAddress(f'{g.token!r}: invalid token address\n{m}')
else:
raise UnrecognizedTokenSymbol(f'Specified token {g.token!r} could not be resolved!')
from mmgen.obj import TokenAddr
self.token = TokenAddr(proto,token_addr)
if g.token in self.data['tokens']:
self.decimals = self.data['tokens'][g.token]['params']['decimals']
self.symbol = self.data['tokens'][g.token]['params']['symbol']
elif not self.importing:
raise TokenNotInWallet('Specified token {!r} not in wallet!'.format(g.token))
if self.token in self.data['tokens']:
self.decimals = self.get_param('decimals')
self.symbol = self.get_param('symbol')
elif self.importing:
await self.import_token(self.token) # sets self.decimals, self.symbol
else:
raise TokenNotInWallet(f'Specified token {self.token!r} not in wallet!')
self.token = g.token
g.proto.dcoin = self.symbol
proto.tokensym = self.symbol
async def is_in_wallet(self,addr):
return addr in self.data['tokens'][self.token]
@ -189,7 +192,7 @@ class EthereumTokenTrackingWallet(EthereumTrackingWallet):
return 'token ' + self.get_param('symbol')
async def rpc_get_balance(self,addr):
return await Token(self.token,self.decimals).get_balance(addr)
return await Token(self.proto,self.token,self.decimals,self.rpc).get_balance(addr)
async def get_eth_balance(self,addr,force_rpc=False):
cache = self.cur_eth_balances
@ -204,21 +207,19 @@ class EthereumTokenTrackingWallet(EthereumTrackingWallet):
return self.data['tokens'][self.token]['params'][param]
@write_mode
async def import_token(tw):
async def import_token(self,tokenaddr):
"""
Token 'symbol' and 'decimals' values are resolved from the network by the system just
once, upon token import. Thereafter, token address, symbol and decimals are resolved
either from the tracking wallet (online operations) or transaction file (when signing).
"""
if not g.token in tw.data['tokens']:
t = await TokenResolve(g.token)
tw.token = g.token
tw.data['tokens'][tw.token] = {
'params': {
'symbol': await t.get_symbol(),
'decimals': t.decimals
}
t = await TokenResolve(self.proto,self.rpc,tokenaddr)
self.data['tokens'][tokenaddr] = {
'params': {
'symbol': await t.get_symbol(),
'decimals': t.decimals
}
}
# No unspent outputs with Ethereum, but naming must be consistent
class EthereumTwUnspentOutputs(TwUnspentOutputs):
@ -242,10 +243,10 @@ Actions: [q]uit view, [p]rint to file, pager [v]iew, [w]ide view,
'q':'a_quit','p':'a_print','v':'a_view','w':'a_view_wide',
'l':'a_lbl_add','D':'a_addr_delete','R':'a_balance_refresh' }
async def __ainit__(self,*args,**kwargs):
async def __ainit__(self,proto,*args,**kwargs):
if g.use_cached_balances:
self.hdr_fmt += '\n' + yellow('WARNING: Using cached balances. These may be out of date!')
await TwUnspentOutputs.__ainit__(self,*args,**kwargs)
await TwUnspentOutputs.__ainit__(self,proto,*args,**kwargs)
def do_sort(self,key=None,reverse=False):
if key == 'txid': return
@ -256,22 +257,15 @@ Actions: [q]uit view, [p]rint to file, pager [v]iew, [w]ide view,
if self.addrs:
wl = [d for d in wl if d['addr'] in self.addrs]
return [{
'account': TwLabel(d['mmid']+' '+d['comment'],on_fail='raise'),
'account': TwLabel(self.proto,d['mmid']+' '+d['comment'],on_fail='raise'),
'address': d['addr'],
'amount': await self.wallet.get_balance(d['addr']),
'confirmations': 0, # TODO
} for d in wl]
class MMGenTwUnspentOutput(MMGenListItem):
txid = ListItemAttr('CoinTxID')
vout = ListItemAttr(int,typeconv=False)
amt = ImmutableAttr(lambda val:g.proto.coin_amt(val),typeconv=False)
amt2 = ListItemAttr(lambda val:g.proto.coin_amt(val),typeconv=False)
label = ListItemAttr('TwComment',reassign_ok=True)
twmmid = ImmutableAttr('TwMMGenID')
addr = ImmutableAttr('CoinAddr')
confs = ImmutableAttr(int,typeconv=False)
skip = ListItemAttr(str,typeconv=False,reassign_ok=True)
class MMGenTwUnspentOutput(TwUnspentOutputs.MMGenTwUnspentOutput):
valid_attrs = {'txid','vout','amt','amt2','label','twmmid','addr','confs','skip'}
invalid_attrs = {'proto'}
def age_disp(self,o,age_fmt): # TODO
return None
@ -294,25 +288,26 @@ class EthereumTwAddrList(TwAddrList):
has_age = False
async def __ainit__(self,usr_addr_list,minconf,showempty,showbtcaddrs,all_labels,wallet=None):
async def __ainit__(self,proto,usr_addr_list,minconf,showempty,showbtcaddrs,all_labels,wallet=None):
self.wallet = wallet or await TrackingWallet(mode='w')
self.proto = proto
self.wallet = wallet or await TrackingWallet(self.proto,mode='w')
tw_dict = self.wallet.mmid_ordered_dict
self.total = g.proto.coin_amt('0')
self.total = self.proto.coin_amt('0')
from mmgen.obj import CoinAddr
for mmid,d in list(tw_dict.items()):
# if d['confirmations'] < minconf: continue # cannot get confirmations for eth account
label = TwLabel(mmid+' '+d['comment'],on_fail='raise')
label = TwLabel(self.proto,mmid+' '+d['comment'],on_fail='raise')
if usr_addr_list and (label.mmid not in usr_addr_list):
continue
bal = await self.wallet.get_balance(d['addr'])
if bal == 0 and not showempty:
if not label.comment or not all_labels:
continue
self[label.mmid] = {'amt': g.proto.coin_amt('0'), 'lbl': label }
self[label.mmid] = {'amt': self.proto.coin_amt('0'), 'lbl': label }
if showbtcaddrs:
self[label.mmid]['addr'] = CoinAddr(d['addr'])
self[label.mmid]['addr'] = CoinAddr(self.proto,d['addr'])
self[label.mmid]['lbl'].mmid.confs = None
self[label.mmid]['amt'] += bal
self.total += bal
@ -326,9 +321,9 @@ class EthereumTwGetBalance(TwGetBalance):
fs = '{w:13} {c}\n' # TODO - for now, just suppress display of meaningless data
async def __ainit__(self,*args,**kwargs):
self.wallet = await TrackingWallet(mode='w')
await TwGetBalance.__ainit__(self,*args,**kwargs)
async def __ainit__(self,proto,*args,**kwargs):
self.wallet = await TrackingWallet(proto,mode='w')
await TwGetBalance.__ainit__(self,proto,*args,**kwargs)
async def create_data(self):
data = self.wallet.mmid_ordered_dict
@ -336,7 +331,7 @@ class EthereumTwGetBalance(TwGetBalance):
if d.type == 'mmgen':
key = d.obj.sid
if key not in self.data:
self.data[key] = [g.proto.coin_amt('0')] * 4
self.data[key] = [self.proto.coin_amt('0')] * 4
else:
key = 'Non-MMGen'
@ -350,10 +345,9 @@ class EthereumTwGetBalance(TwGetBalance):
class EthereumTwAddrData(TwAddrData):
@classmethod
async def get_tw_data(cls,wallet=None):
async def get_tw_data(self,wallet=None):
vmsg('Getting address data from tracking wallet')
tw = (wallet or await TrackingWallet()).mmid_ordered_dict
tw = (wallet or await TrackingWallet(self.proto)).mmid_ordered_dict
# emulate the output of RPC 'listaccounts' and 'getaddressesbyaccount'
return [(mmid+' '+d['comment'],[d['addr']]) for mmid,d in list(tw.items())]

View file

@ -25,523 +25,534 @@ from mmgen.common import *
from mmgen.exception import TransactionChainMismatch
from mmgen.obj import *
from mmgen.tx import MMGenTX,MMGenBumpTX,MMGenSplitTX,MMGenTxForSigning
from mmgen.tx import MMGenTX
from mmgen.tw import TrackingWallet
from .contract import Token
class EthereumMMGenTX(MMGenTX):
desc = 'Ethereum transaction'
contract_desc = 'contract'
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
fee_fail_fs = 'Network fee estimation failed'
no_chg_msg = 'Warning: Transaction leaves account with zero balance'
rel_fee_desc = 'gas price'
rel_fee_disp = 'gas price in Gwei'
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 = 'Total in account: {i} {d}\nTotal to spend: {o} {d}\nTX fee: {a} {c}{r}\n'
txview_ftr_fs_short = 'In {i} {d} - Out {o} {d}\nFee {a} {c}{r}\n'
fmt_keys = ('from','to','amt','nonce')
usr_fee_prompt = 'Enter transaction fee or gas price: '
fn_fee_unit = 'Mwei'
usr_rel_fee = None # not in MMGenTX
disable_fee_check = False
txobj = None # ""
usr_contract_data = HexStr('')
class EthereumMMGenTX:
def __init__(self,*args,**kwargs):
MMGenTX.__init__(self,*args,**kwargs)
if hasattr(opt,'tx_gas') and opt.tx_gas:
self.tx_gas = self.start_gas = ETHAmt(int(opt.tx_gas),'wei')
if hasattr(opt,'contract_data') and opt.contract_data:
m = "'--contract-data' option may not be used with token transaction"
assert not 'Token' in type(self).__name__, m
self.usr_contract_data = HexStr(open(opt.contract_data).read().strip())
self.disable_fee_check = True
class Base(MMGenTX.Base):
def check_txfile_hex_data(self):
pass
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
@classmethod
async def get_exec_status(cls,txid,silent=False):
d = await g.rpc.call('eth_getTransactionReceipt','0x'+txid)
if not silent:
if 'contractAddress' in d and d['contractAddress']:
msg('Contract address: {}'.format(d['contractAddress'].replace('0x','')))
return int(d['status'],16)
# 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('fee_abs2rel() ==> {} ETH'.format(ret))
return ret if to_unit == 'eth' else ret.to_unit(to_unit,show_decimal=True)
def is_replaceable(self): return True
def get_fee(self):
return self.fee
def get_fee(self):
return self.fee
def get_hex_locktime(self):
return None # TODO
def check_fee(self):
assert self.disable_fee_check or (self.fee <= g.proto.max_tx_fee)
# given rel fee in wei, return absolute fee using tx_gas (not in MMGenTX)
def fee_rel2abs(self,rel_fee):
assert isinstance(rel_fee,int),"'{}': incorrect type for fee estimate (not an integer)".format(rel_fee)
return ETHAmt(rel_fee * self.tx_gas.toWei(),'wei')
def get_hex_locktime(self): return None # TODO
def check_pubkey_scripts(self): pass
def check_sigs(self,deserial_tx=None):
if is_hex_str(self.hex):
self.mark_signed()
def is_replaceable(self):
return True
return False
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(d['sender']),
'to': CoinAddr(d['to']) if d['to'] else Str(''), # NB: for token, 'to' is token address
'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
o['token_addr'] = TokenAddr(etx.creates.hex()) # NB: could be a non-token contract address
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.fee = self.fee_rel2abs(o['gasPrice'].toWei())
self.txobj = o
return d # 'token_addr','decimals' required by Token subclass
async def get_exec_status(self,txid,silent=False):
d = await self.rpc.call('eth_getTransactionReceipt','0x'+txid)
if not silent:
if 'contractAddress' in d and d['contractAddress']:
msg('Contract address: {}'.format(d['contractAddress'].replace('0x','')))
return int(d['status'],16)
async def get_nonce(self):
return ETHNonce(int(await g.rpc.call('parity_nextNonce','0x'+self.inputs[0].addr),16))
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: '
usr_rel_fee = None # not in MMGenTX
async def make_txobj(self): # called by create_raw()
chain_id_method = ('parity_chainId','eth_chainId')['eth_chainId' in g.rpc.caps]
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.usr_rel_fee or self.fee_abs2rel(self.fee,to_unit='eth'),
'startGas': self.start_gas,
'nonce': await self.get_nonce(),
'chainId': Int(await g.rpc.call(chain_id_method),16),
'data': self.usr_contract_data,
}
def __init__(self,*args,**kwargs):
MMGenTX.New.__init__(self,*args,**kwargs)
if getattr(opt,'tx_gas',None):
self.tx_gas = self.start_gas = ETHAmt(int(opt.tx_gas),'wei')
if getattr(opt,'contract_data',None):
m = "'--contract-data' option may not be used with token transaction"
assert not 'Token' in type(self).__name__, m
self.usr_contract_data = HexStr(open(opt.contract_data).read().strip())
self.disable_fee_check = True
# 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,'Transaction has {} output{} (should have {})'.format(o_num,suf(o_num),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()
async def get_nonce(self):
return ETHNonce(int(await self.rpc.call('parity_nextNonce','0x'+self.inputs[0].addr),16))
def del_output(self,idx):
pass
async def make_txobj(self): # called by create_raw()
chain_id_method = ('parity_chainId','eth_chainId')['eth_chainId' in self.rpc.caps]
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.usr_rel_fee or self.fee_abs2rel(self.fee,to_unit='eth'),
'startGas': self.start_gas,
'nonce': await self.get_nonce(),
'chainId': Int(await self.rpc.call(chain_id_method),16),
'data': self.usr_contract_data,
}
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())
# 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,'Transaction has {} output{} (should have {})'.format(o_num,suf(o_num),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 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:
fs = '{} output{} specified, but Ethereum transactions must have exactly one'
die(1,fs.format(lc,suf(lc)))
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())
for a in cmd_args:
self.process_cmd_arg(a,ad_f,ad_w)
def del_output(self,idx):
pass
def select_unspent(self,unspent):
prompt = 'Enter an account to spend from: '
while True:
reply = my_raw_input(prompt).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('Account number must be <= {}'.format(len(unspent)))
else:
return [int(reply)]
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')
# coin-specific fee routines:
@property
def relay_fee(self):
return ETHAmt('0') # TODO
for a in cmd_args:
self.process_cmd_arg(a,ad_f,ad_w)
# 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('fee_abs2rel() ==> {} ETH'.format(ret))
return ret if to_unit == 'eth' else ret.to_unit(to_unit,show_decimal=True)
def select_unspent(self,unspent):
prompt = 'Enter an account to spend from: '
while True:
reply = my_raw_input(prompt).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('Account number must be <= {}'.format(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 g.rpc.call('eth_gasPrice'),16),'eth_gasPrice' # ==> rel_fee,fe_type
# coin-specific fee routines:
@property
def relay_fee(self):
return ETHAmt('0') # TODO
# given rel fee and units, return absolute fee using tx_gas
def convert_fee_spec(self,foo,units,amt,unit):
self.usr_rel_fee = ETHAmt(int(amt),units[unit])
return ETHAmt(self.usr_rel_fee.toWei() * self.tx_gas.toWei(),'wei')
# 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
# given rel fee in wei, return absolute fee using tx_gas (not in MMGenTX)
def fee_rel2abs(self,rel_fee):
assert isinstance(rel_fee,int),"'{}': incorrect type for fee estimate (not an integer)".format(rel_fee)
return ETHAmt(rel_fee * self.tx_gas.toWei(),'wei')
def check_fee(self):
assert self.disable_fee_check or (self.fee <= self.proto.max_tx_fee)
# 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_rel2abs(rel_fee) * opt.tx_fee_adj
if opt.verbose:
msg('Estimated fee: {} ETH'.format(ret))
return ret
# given rel fee and units, return absolute fee using tx_gas
def convert_fee_spec(self,foo,units,amt,unit):
self.usr_rel_fee = ETHAmt(int(amt),units[unit])
return ETHAmt(self.usr_rel_fee.toWei() * self.tx_gas.toWei(),'wei')
def convert_and_check_fee(self,tx_fee,desc='Missing description'):
abs_fee = self.process_fee_spec(tx_fee,None)
if abs_fee == False:
return False
elif not self.disable_fee_check and (abs_fee > g.proto.max_tx_fee):
m = '{} {c}: {} fee too large (maximum fee: {} {c})'
msg(m.format(abs_fee.hl(),desc,g.proto.max_tx_fee.hl(),c=g.coin))
return False
else:
return abs_fee
# 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_rel2abs(rel_fee) * opt.tx_fee_adj
if opt.verbose:
msg('Estimated fee: {} ETH'.format(ret))
return ret
def update_change_output(self,change_amt):
if self.outputs and self.outputs[0].is_chg:
self.update_output_amt(0,ETHAmt(change_amt))
def update_send_amt(self,foo):
if self.outputs:
self.send_amt = self.outputs[0].amt
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','')
ld = len(self.txobj['data'])
return fs.format( *((self.txobj[k] if self.txobj[k] != '' else Str('None')).hl() for k in self.fmt_keys),
d='{}... ({} bytes)'.format(self.txobj['data'][:40],ld//2) if ld else Str('None'),
c=g.dcoin if len(self.outputs) else '',
g=yellow(str(self.txobj['gasPrice'].to_unit('Gwei',show_decimal=True))),
G=yellow(str(self.txobj['startGas'].toKwei())),
t_mmid=m['outputs'] if len(self.outputs) else '',
f_mmid=m['inputs'])
def format_view_abs_fee(self):
fee = self.fee_rel2abs(self.txobj['gasPrice'].toWei())
note = ' (max)' if self.txobj['data'] else ''
return fee.hl() + note
def format_view_rel_fee(self,terse): return ''
def format_view_verbose_footer(self): return '' # TODO
def resolve_g_token_from_txfile(self):
die(2,"The '--token' option must be specified for token transaction files")
def final_inputs_ok_msg(self,change_amt):
m = "Transaction leaves {} {} in the sender's account"
chg = '0' if (self.outputs and self.outputs[0].is_chg) else change_amt
return m.format(ETHAmt(chg).hl(),g.coin)
async def get_status(self,status=False):
class r(object): pass
async def is_in_mempool():
if not 'full_node' in g.rpc.caps:
def convert_and_check_fee(self,tx_fee,desc='Missing description'):
abs_fee = self.process_fee_spec(tx_fee,None)
if abs_fee == False:
return False
return '0x'+self.coin_txid in [x['hash'] for x in await g.rpc.call('parity_pendingTransactions')]
elif not self.disable_fee_check and (abs_fee > self.proto.max_tx_fee):
m = '{} {c}: {} fee too large (maximum fee: {} {c})'
msg(m.format(abs_fee.hl(),desc,self.proto.max_tx_fee.hl(),c=self.proto.coin))
return False
else:
return abs_fee
async def is_in_wallet():
d = await g.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 g.rpc.call('eth_blockNumber'),16) - int(d['blockNumber'],16)
r.exec_status = int(d['status'],16)
def update_change_output(self,change_amt):
if self.outputs and self.outputs[0].is_chg:
self.update_output_amt(0,ETHAmt(change_amt))
def update_send_amt(self,foo):
if self.outputs:
self.send_amt = self.outputs[0].amt
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,"'{}': not an MMGen ID or coin address".format(i))
return ret
def final_inputs_ok_msg(self,change_amt):
m = "Transaction leaves {} {} in the sender's account"
chg = '0' if (self.outputs and self.outputs[0].is_chg) else change_amt
return m.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 = 'Total in account: {i} {d}\nTotal to spend: {o} {d}\nTX fee: {a} {c}{r}\n'
txview_ftr_fs_short = 'In {i} {d} - Out {o} {d}\nFee {a} {c}{r}\n'
fmt_keys = ('from','to','amt','nonce')
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']
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'].toKwei())),
t_mmid = m['outputs'] if len(self.outputs) else '',
f_mmid = m['inputs'] )
def format_view_abs_fee(self):
fee = self.fee_rel2abs(self.txobj['gasPrice'].toWei())
note = ' (max)' if self.txobj['data'] else ''
return fee.hl() + note
def format_view_rel_fee(self,terse):
return ''
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
if await is_in_mempool():
msg('Transaction is in mempool' if status else 'Warning: transaction is in mempool!')
return
def check_pubkey_scripts(self):
pass
if status:
if await is_in_wallet():
if self.txobj['data']:
cd = capfirst(self.contract_desc)
if r.exec_status == 0:
msg('{} failed to execute!'.format(cd))
else:
msg('{} successfully executed with status {}'.format(cd,r.exec_status))
die(0,'Transaction has {} confirmation{}'.format(r.confs,suf(r.confs)))
die(1,'Transaction is neither in mempool nor blockchain!')
class Unsigned(Completed,MMGenTX.Unsigned):
hexdata_type = 'json'
desc = 'unsigned transaction'
async def send(self,prompt_user=True,exit_on_fail=False):
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': Int(d['chainId']),
'data': HexStr(d['data']) }
self.tx_gas = o['startGas'] # approximate, but better than nothing
self.fee = self.fee_rel2abs(o['gasPrice'].toWei())
self.txobj = o
return d # 'token_addr','decimals' required by Token subclass
if not self.marked_signed():
die(1,'Transaction is not signed!')
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']) }
self.check_correct_chain()
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')
fee = self.fee_rel2abs(self.txobj['gasPrice'].toWei())
from . import rlp
self.hex = rlp.encode(etx).hex()
self.coin_txid = CoinTxID(etx.hash.hex())
if not self.disable_fee_check and (fee > g.proto.max_tx_fee):
die(2,'Transaction fee ({}) greater than {} max_tx_fee ({} {})!'.format(
fee,
g.proto.name,
g.proto.max_tx_fee,
g.proto.coin ))
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())
await self.get_status()
assert self.check_sigs(),'Signature check failed'
if prompt_user:
self.confirm_send()
async def sign(self,tx_num_str,keys): # return TX object or False; don't exit or raise exception
if g.bogus_send:
ret = None
else:
try:
ret = await g.rpc.call('eth_sendRawTransaction','0x'+self.hex)
except:
raise
ret = False
self.check_correct_chain()
except TransactionChainMismatch:
return False
if ret == False:
msg(red('Send of MMGen transaction {} failed'.format(self.txid)))
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)'
self.desc = 'sent transaction'
msg(m.format(self.coin_txid.hl()))
self.add_timestamp()
self.add_blockcount()
return True
msg_r(f'Signing transaction{tx_num_str}...')
async def get_cmdline_input_addrs(self):
ret = []
if opt.inputs:
r = (await TrackingWallet()).data_root # must create new instance here
m = 'Address {!r} not in tracking wallet'
for i in opt.inputs.split(','):
if is_mmgen_id(i):
for addr in r:
if r[addr]['mmid'] == i:
ret.append(addr)
break
else:
raise UserAddressNotInWallet(m.format(i))
elif is_coin_addr(i):
if not i in r:
raise UserAddressNotInWallet(m.format(i))
ret.append(i)
else:
die(1,"'{}': not an MMGen ID or coin address".format(i))
return ret
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
def print_contract_addr(self):
if 'token_addr' in self.txobj:
msg('Contract address: {}'.format(self.txobj['token_addr'].hl()))
class Signed(Completed,MMGenTX.Signed):
class EthereumMMGenTxForSigning(EthereumMMGenTX,MMGenTxForSigning):
desc = 'signed transaction'
def parse_txfile_hex_data(self):
d = json.loads(self.hex)
o = {
'from': CoinAddr(d['from']),
'to': CoinAddr(d['to']) if d['to'] else Str(''), # NB: for token, 'to' is sendto address
'amt': ETHAmt(d['amt']),
'gasPrice': ETHAmt(d['gasPrice']),
'startGas': ETHAmt(d['startGas']),
'nonce': ETHNonce(d['nonce']),
'chainId': Int(d['chainId']),
'data': HexStr(d['data']) }
self.tx_gas = o['startGas'] # approximate, but better than nothing
self.fee = self.fee_rel2abs(o['gasPrice'].toWei())
self.txobj = o
return d # 'token_addr','decimals' required by Token subclass
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.fee = self.fee_rel2abs(o['gasPrice'].toWei())
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']) }
async def get_status(self,status=False):
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')
class r(object):
pass
from . import rlp
self.hex = rlp.encode(etx).hex()
self.coin_txid = CoinTxID(etx.hash.hex())
async def is_in_mempool():
if not 'full_node' in self.rpc.caps:
return False
return '0x'+self.coin_txid in [
x['hash'] for x in await self.rpc.call('parity_pendingTransactions') ]
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(etx.creates.hex())
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
assert self.check_sigs(),'Signature check failed'
if await is_in_mempool():
msg('Transaction is in mempool' if status else 'Warning: transaction is in mempool!')
return
async def sign(self,tx_num_str,keys): # return True or False; don't exit or raise exception
if status:
if await is_in_wallet():
if self.txobj['data']:
cd = capfirst(self.contract_desc)
if r.exec_status == 0:
msg('{} failed to execute!'.format(cd))
else:
msg('{} successfully executed with status {}'.format(cd,r.exec_status))
die(0,'Transaction has {} confirmation{}'.format(r.confs,suf(r.confs)))
die(1,'Transaction is neither in mempool nor blockchain!')
if self.marked_signed():
msg('Transaction is already signed!')
return False
async def send(self,prompt_user=True,exit_on_fail=False):
try:
self.check_correct_chain()
except TransactionChainMismatch:
return False
msg_r('Signing transaction{}...'.format(tx_num_str))
fee = self.fee_rel2abs(self.txobj['gasPrice'].toWei())
try:
await self.do_sign(keys[0].sec.wif,tx_num_str)
msg('OK')
return True
except Exception as e:
m = "{!r}: transaction signing failed!"
msg(m.format(e.args[0]))
if g.traceback:
import traceback
ymsg('\n'+''.join(traceback.format_exception(*sys.exc_info())))
return False
if not self.disable_fee_check and (fee > self.proto.max_tx_fee):
die(2,'Transaction fee ({}) greater than {} max_tx_fee ({} {})!'.format(
fee,
self.proto.name,
self.proto.max_tx_fee,
self.proto.coin ))
class EthereumTokenMMGenTX(EthereumMMGenTX):
desc = 'Ethereum token transaction'
contract_desc = 'token contract'
tx_gas = ETHAmt(52000,'wei')
start_gas = ETHAmt(60000,'wei')
fmt_keys = ('from','token_to','amt','nonce')
fee_is_approximate = True
await self.get_status()
def update_change_output(self,change_amt):
if self.outputs[0].is_chg:
self.update_output_amt(0,self.inputs[0].amt)
if prompt_user:
self.confirm_send()
# 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):
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)
if g.bogus_send:
ret = None
else:
try:
ret = await self.rpc.call('eth_sendRawTransaction','0x'+self.hex)
except:
raise
ret = False
def final_inputs_ok_msg(self,change_amt):
token_bal = ( ETHAmt('0') if self.outputs[0].is_chg else
self.inputs[0].amt - self.outputs[0].amt )
m = "Transaction leaves ≈{} {} and {} {} in the sender's account"
return m.format( change_amt.hl(), g.coin, token_bal.hl(), g.dcoin )
if ret == False:
msg(red('Send of MMGen transaction {} failed'.format(self.txid)))
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)'
self.desc = 'sent transaction'
msg(m.format(self.coin_txid.hl()))
self.add_timestamp()
self.add_blockcount()
return True
async def get_change_amt(self): # here we know the fee
eth_bal = await self.tw.get_eth_balance(self.inputs[0].addr)
return eth_bal - self.fee
def print_contract_addr(self):
if 'token_addr' in self.txobj:
msg('Contract address: {}'.format(self.txobj['token_addr'].hl()))
def resolve_g_token_from_txfile(self):
class Bump(MMGenTX.Bump,Completed,New):
@property
def min_fee(self):
return ETHAmt(self.fee * Decimal('1.101'))
def update_fee(self,foo,fee):
self.fee = fee
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,change_amt):
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):
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)
async def get_change_amt(self): # here we know the fee
eth_bal = await self.tw.get_eth_balance(self.inputs[0].addr)
return eth_bal - self.fee
def final_inputs_ok_msg(self,change_amt):
token_bal = ( ETHAmt('0') if self.outputs[0].is_chg else
self.inputs[0].amt - self.outputs[0].amt )
m = "Transaction leaves ≈{} {} and {} {} in the sender's account"
return m.format( change_amt.hl(), self.proto.coin, token_bal.hl(), self.proto.dcoin )
class Completed(Base,EthereumMMGenTX.Completed):
fmt_keys = ('from','token_to','amt','nonce')
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
async def make_txobj(self): # called by create_raw()
await super().make_txobj()
t = Token(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 parse_txfile_hex_data(self):
d = EthereumMMGenTX.parse_txfile_hex_data(self)
o = self.txobj
assert self.tw.token == o['to']
o['token_addr'] = TokenAddr(o['to'])
o['decimals'] = self.tw.decimals
t = Token(o['token_addr'],o['decimals'])
o['amt'] = t.transferdata2amt(o['data'])
o['token_to'] = type(t).transferdata2sendaddr(o['data'])
def format_view_body(self,*args,**kwargs):
return 'Token: {d} {c}\n{r}'.format(
d=self.txobj['token_addr'].hl(),
c=blue('(' + g.dcoin + ')'),
r=super().format_view_body(*args,**kwargs))
class EthereumTokenMMGenTxForSigning(EthereumTokenMMGenTX,EthereumMMGenTxForSigning):
def resolve_g_token_from_txfile(self):
d = json.loads(self.hex)
if g.token.upper() == self.dcoin:
g.token = d['token_addr']
elif g.token != d['token_addr']:
die(1,
"{!r}: invalid --token parameter for {t} {} token transaction file\nPlease use '--token={t}'".format(
g.token,
g.proto.name,
t = self.dcoin ))
def parse_txfile_hex_data(self):
d = EthereumMMGenTxForSigning.parse_txfile_hex_data(self)
o = self.txobj
o['token_addr'] = TokenAddr(d['token_addr'])
o['decimals'] = Int(d['decimals'])
t = Token(o['token_addr'],o['decimals'])
o['data'] = t.create_data(o['to'],o['amt'])
o['token_to'] = type(t).transferdata2sendaddr(o['data'])
async def do_sign(self,wif,tx_num_str):
o = self.txobj
t = Token(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 EthereumMMGenBumpTX(MMGenBumpTX,EthereumMMGenTxForSigning):
@property
def min_fee(self):
return ETHAmt(self.fee * Decimal('1.101'))
def update_fee(self,foo,fee):
self.fee = fee
async def get_nonce(self):
return self.txobj['nonce']
class EthereumTokenMMGenBumpTX(EthereumMMGenBumpTX,EthereumTokenMMGenTxForSigning):
pass
class EthereumMMGenSplitTX(MMGenSplitTX):
pass

View file

@ -26,217 +26,3 @@ from .globalvars import *
import mmgen.opts as opts
from .opts import opt
from .util import *
def help_notes(k):
from .obj import SubSeedIdxRange,SeedShareIdx,SeedShareCount,MasterShareIdx
from .wallet import Wallet
from .tx import MMGenTX
def fee_spec_letters(use_quotes=False):
cu = g.proto.coin_amt.units
sep,conj = ((',',' or '),("','","' or '"))[use_quotes]
return sep.join(u[0] for u in cu[:-1]) + ('',conj)[len(cu)>1] + cu[-1][0]
def fee_spec_names():
cu = g.proto.coin_amt.units
return ', '.join(cu[:-1]) + ('',' and ')[len(cu)>1] + cu[-1] + ('',',\nrespectively')[len(cu)>1]
return {
'rel_fee_desc': MMGenTX().rel_fee_desc,
'fee_spec_letters': fee_spec_letters(),
'seedsplit': """
COMMAND NOTES:
This command generates shares one at a time. Shares may be output to any
MMGen wallet format, with one limitation: only one share in a given split may
be in hidden incognito format, and it must be the master share in the case of
a master-share split.
If the command's optional first argument is omitted, the default wallet is
used for the split.
The last argument is a seed split specifier consisting of an optional split
ID, a share index, and a share count, all separated by colons. The split ID
must be a valid UTF-8 string. If omitted, the ID 'default' is used. The
share index (the index of the share being generated) must be in the range
{sia}-{sib} and the share count (the total number of shares in the split)
in the range {sca}-{scb}.
Master Shares
Each seed has a total of {msb} master shares, which can be used as the first
shares in multiple splits if desired. To generate a master share, use the
--master-share (-M) option with an index in the range {msa}-{msb} and omit
the last argument.
When creating and joining a split using a master share, ensure that the same
master share index is used in all split and join commands.
EXAMPLES:
Split a BIP39 seed phrase into two BIP39 shares. Rejoin the split:
$ echo 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong' > sample.bip39
$ mmgen-seedsplit -o bip39 sample.bip39 1:2
BIP39 mnemonic data written to file '03BAE887-default-1of2[D51CB683][128].bip39'
$ mmgen-seedsplit -o bip39 sample.bip39 2:2
BIP39 mnemonic data written to file '03BAE887-default-2of2[67BFD36E][128].bip39'
$ mmgen-seedjoin -o bip39 \\
'03BAE887-default-2of2[67BFD36E][128].bip39' \\
'03BAE887-default-1of2[D51CB683][128].bip39'
BIP39 mnemonic data written to file '03BAE887[128].bip39'
$ cat '03BAE887[128].bip39'
zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong
Create a 3-way default split of your default wallet, outputting all shares
to default wallet format. Rejoin the split:
$ mmgen-seedsplit 1:3 # Step A
$ mmgen-seedsplit 2:3 # Step B
$ mmgen-seedsplit 3:3 # Step C
$ mmgen-seedjoin <output_of_step_A> <output_of_step_B> <output_of_step_C>
Create a 2-way split of your default wallet with ID string 'alice',
outputting shares to MMGen native mnemonic format. Rejoin the split:
$ mmgen-seedsplit -o words alice:1:2 # Step D
$ mmgen-seedsplit -o words alice:2:2 # Step E
$ mmgen-seedjoin <output_of_step_D> <output_of_step_E>
Create a 2-way split of your default wallet with ID string 'bob' using
master share #7, outputting share #1 (the master share) to default wallet
format and share #2 to BIP39 format. Rejoin the split:
$ mmgen-seedsplit -M7 # Step X
$ mmgen-seedsplit -M7 -o bip39 bob:2:2 # Step Y
$ mmgen-seedjoin -M7 --id-str=bob <output_of_step_X> <output_of_step_Y>
Create a 2-way split of your default wallet with ID string 'alice' using
master share #7. Rejoin the split using master share #7 generated in the
previous example:
$ mmgen-seedsplit -M7 -o bip39 alice:2:2 # Step Z
$ mmgen-seedjoin -M7 --id-str=alice <output_of_step_X> <output_of_step_Z>
Create a 2-way default split of your default wallet with an incognito-format
master share hidden in file 'my.hincog' at offset 1325. Rejoin the split:
$ mmgen-seedsplit -M4 -o hincog -J my.hincog,1325 1:2 # Step M (share A)
$ mmgen-seedsplit -M4 -o bip39 2:2 # Step N (share B)
$ mmgen-seedjoin -M4 -H my.hincog,1325 <output_of_step_N>
""".strip().format(
sia=SeedShareIdx.min_val,sib=SeedShareIdx.max_val,
sca=SeedShareCount.min_val,scb=SeedShareCount.max_val,
msa=MasterShareIdx.min_val,msb=MasterShareIdx.max_val),
'subwallet': """
SUBWALLETS:
Subwallets (subseeds) are specified by a "Subseed Index" consisting of:
a) an integer in the range 1-{}, plus
b) an optional single letter, 'L' or 'S'
The letter designates the length of the subseed. If omitted, 'L' is assumed.
Long ('L') subseeds are the same length as their parent wallet's seed
(typically 256 bits), while short ('S') subseeds are always 128-bit.
The long and short subseeds for a given index are derived independently,
so both may be used.
MMGen has no notion of "depth", and to an outside observer subwallets are
identical to ordinary wallets. This is a feature rather than a bug, as it
denies an attacker any way of knowing whether a given wallet has a parent.
Since subwallets are just wallets, they may be used to generate other
subwallets, leading to hierarchies of arbitrary depth. However, this is
inadvisable in practice for two reasons: Firstly, it creates accounting
complexity, requiring the user to independently keep track of a derivation
tree. More importantly, however, it leads to the danger of Seed ID
collisions between subseeds at different levels of the hierarchy, as
MMGen checks and avoids ID collisions only among sibling subseeds.
An exception to this caveat would be a multi-user setup where sibling
subwallets are distributed to different users as their default wallets.
Since the subseeds derived from these subwallets are private to each user,
Seed ID collisions among them doesn't present a problem.
A safe rule of thumb, therefore, is for *each user* to derive all of his/her
subwallets from a single parent. This leaves each user with a total of two
million subwallets, which should be enough for most practical purposes.
""".strip().format(SubSeedIdxRange.max_idx),
'passwd': """
PASSPHRASE NOTE:
For passphrases all combinations of whitespace are equal, and leading and
trailing space are ignored. This permits reading passphrase or brainwallet
data from a multi-line file with free spacing and indentation.
""".strip(),
'brainwallet': """
BRAINWALLET NOTE:
To thwart dictionary attacks, it's recommended to use a strong hash preset
with brainwallets. For a brainwallet passphrase to generate the correct
seed, the same seed length and hash preset parameters must always be used.
""".strip(),
'txcreate': """
The transaction's outputs are specified on the command line, while its inputs
are chosen from a list of the user's unspent outputs via an interactive menu.
If the transaction fee is not specified on the command line (see FEE
SPECIFICATION below), it will be calculated dynamically using network fee
estimation for the default (or user-specified) number of confirmations.
If network fee estimation fails, the user will be prompted for a fee.
Network-estimated fees will be multiplied by the value of '--tx-fee-adj',
if specified.
Ages of transactions are approximate based on an average block discovery
interval of one per {g.proto.avg_bdi} seconds.
All addresses on the command line can be either {pnu} addresses or {pnm}
addresses of the form <seed ID>:<index>.
To send the value of all inputs (minus TX fee) to a single output, specify
one address with no amount on the command line.
""".format(g=g,pnm=g.proj_name,pnu=g.proto.name),
'fee': """
FEE SPECIFICATION: Transaction fees, both on the command line and at the
interactive prompt, may be specified as either absolute {c} amounts, using
a plain decimal number, or as {r}, using an integer followed by
'{l}', for {u}.
""".format( c=g.coin,
r=MMGenTX().rel_fee_desc,
l=fee_spec_letters(use_quotes=True),
u=fee_spec_names() ),
'txsign': """
Transactions may contain both {pnm} or non-{pnm} input addresses.
To sign non-{pnm} inputs, a {dn} wallet dump or flat key list is used
as the key source ('--keys-from-file' option).
To sign {pnm} inputs, key data is generated from a seed as with the
{pnl}-addrgen and {pnl}-keygen commands. Alternatively, a key-address file
may be used (--mmgen-keys-from-file option).
Multiple wallets or other seed files can be listed on the command line in
any order. If the seeds required to sign the transaction's inputs are not
found in these files (or in the default wallet), the user will be prompted
for seed data interactively.
To prevent an attacker from crafting transactions with bogus {pnm}-to-{pnu}
address mappings, all outputs to {pnm} addresses are verified with a seed
source. Therefore, seed files or a key-address file for all {pnm} outputs
must also be supplied on the command line if the data can't be found in the
default wallet.
""".format( dn=g.proto.daemon_name,
pnm=g.proj_name,
pnu=g.proto.name,
pnl=g.proj_name.lower())
}[k] + ('-α' if g.debug_utf8 else '')
def exit_if_mswin(feature):
if g.platform == 'win':
m = capfirst(feature) + ' not supported on the MSWin / MSYS2 platform'
ydie(1,m)

View file

@ -306,20 +306,20 @@ class CoinDaemon(Daemon):
'etc': cd('Ethereum Classic','Ethereum','parity', 'parity', 'parity.conf', None, 8545, 8545,8545)
}
def __new__(cls,network_id,test_suite=False,flags=None):
def __new__(cls,network_id=None,test_suite=False,flags=None,proto=None):
network_id = network_id.lower()
assert network_id in cls.network_ids, '{!r}: invalid network ID'.format(network_id)
assert network_id or proto, 'CoinDaemon_chk1'
assert not (network_id and proto), 'CoinDaemon_chk2'
if network_id.endswith('_rt'):
network = 'regtest'
daemon_id = network_id[:-3]
elif network_id.endswith('_tn'):
network = 'testnet'
daemon_id = network_id[:-3]
if proto:
network_id = proto.network_id
network = proto.network
daemon_id = proto.coin.lower()
else:
network = 'mainnet'
daemon_id = network_id
network_id = network_id.lower()
assert network_id in cls.network_ids, '{!r}: invalid network ID'.format(network_id)
from mmgen.protocol import CoinProtocol
daemon_id,network = CoinProtocol.Base.parse_network_id(network_id)
me = Daemon.__new__(globals()[cls.daemon_ids[daemon_id].cls_pfx+'Daemon'])
me.network_id = network_id
@ -336,22 +336,30 @@ class CoinDaemon(Daemon):
'regtest',
daemon_id )
else:
me.datadir = os.path.join(g.data_dir_root,'regtest',daemon_id)
datadir = os.path.join(g.data_dir_root,'regtest',daemon_id)
elif test_suite:
me.desc = 'test suite daemon'
rel_datadir = os.path.join('test','daemons',daemon_id)
else:
from .protocol import init_proto
me.datadir = init_proto(daemon_id,False).daemon_data_dir
if proto:
datadir = proto.daemon_data_dir
else:
from .protocol import init_proto
datadir = init_proto(coin=daemon_id,testnet=False).daemon_data_dir
if test_suite:
me.datadir = os.path.abspath(os.path.join(os.getcwd(),rel_datadir))
datadir = os.path.join(os.getcwd(),rel_datadir)
if g.daemon_data_dir: # user-set value must override
datadir = g.daemon_data_dir
me.datadir = os.path.abspath(datadir)
me.port_shift = 1237 if test_suite else 0
me.platform = g.platform
return me
def __init__(self,network_id,test_suite=False,flags=None):
def __init__(self,network_id=None,test_suite=False,flags=None,proto=None):
super().__init__()
self.testnet_arg = []
@ -386,6 +394,9 @@ class CoinDaemon(Daemon):
'regtest': self.dfl_rpc_rt,
}[self.network] + self.port_shift
if g.rpc_port: # user-set value must override
self.rpc_port = g.rpc_port
self.net_desc = '{} {}'.format(self.coin,self.network)
self.subclass_init()
@ -547,14 +558,11 @@ class EthereumDaemon(CoinDaemon):
# the following code does not work
async def do():
print(g.rpc)
ret = await g.rpc.call('eth_chainId')
print(ret)
ret = await self.rpc.call('eth_chainId')
return ('stopped','ready')[ret == '0x11']
from mmgen.protocol import init_proto
try:
return run_session(do(),proto=init_proto('eth')) # socket exception is not propagated
return run_session(do()) # socket exception is not propagated
except:# SocketError:
return 'stopped'

View file

@ -47,9 +47,11 @@ class TransactionChainMismatch(Exception):mmcode = 2
# 3: yellow hl, 'MMGen Error' + exception + message
class RPCFailure(Exception): mmcode = 3
class RPCChainMismatch(Exception): mmcode = 3
class BadTxSizeEstimate(Exception): mmcode = 3
class MaxInputSizeExceeded(Exception): mmcode = 3
class MaxFileSizeExceeded(Exception): mmcode = 3
class MaxFeeExceeded(Exception): mmcode = 3
class WalletFileError(Exception): mmcode = 3
class HexadecimalStringError(Exception): mmcode = 3
class SeedLengthError(Exception): mmcode = 3

View file

@ -72,6 +72,7 @@ class GlobalContext:
# Constant vars - some of these might be overridden in opts.py, but they don't change thereafter
coin = ''
token = ''
debug = False
debug_opts = False
@ -86,9 +87,6 @@ class GlobalContext:
accept_defaults = False
use_internal_keccak_module = False
chain = None
chains = ('mainnet','testnet','regtest')
# rpc:
rpc_host = ''
rpc_port = 0
@ -98,7 +96,6 @@ class GlobalContext:
monero_wallet_rpc_user = 'monero'
monero_wallet_rpc_password = ''
rpc_fail_on_command = ''
rpc = None # global RPC handle
aiohttp_rpc_queue_len = 16
use_cached_balances = False
@ -280,12 +277,4 @@ class GlobalContext:
if name[:11] == 'MMGEN_DEBUG':
os.environ[name] = '1'
@property
def coin(self):
return self.proto.coin
@property
def dcoin(self):
return self.proto.dcoin
g = GlobalContext()

256
mmgen/help.py Executable file
View file

@ -0,0 +1,256 @@
#!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
# Copyright (C)2013-2020 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/>.
"""
help.py: help notes for MMGen suite commands
"""
def help_notes_func(proto,k):
from .globalvars import g
def fee_spec_letters(use_quotes=False):
cu = proto.coin_amt.units
sep,conj = ((',',' or '),("','","' or '"))[use_quotes]
return sep.join(u[0] for u in cu[:-1]) + ('',conj)[len(cu)>1] + cu[-1][0]
def fee_spec_names():
cu = proto.coin_amt.units
return ', '.join(cu[:-1]) + ('',' and ')[len(cu)>1] + cu[-1] + ('',',\nrespectively')[len(cu)>1]
class help_notes:
def rel_fee_desc():
from .tx import MMGenTX
return MMGenTX.Base().rel_fee_desc
def fee_spec_letters():
return fee_spec_letters()
def fee():
from .tx import MMGenTX
return """
FEE SPECIFICATION: Transaction fees, both on the command line and at the
interactive prompt, may be specified as either absolute {c} amounts, using
a plain decimal number, or as {r}, using an integer followed by
'{l}', for {u}.
""".format(
c = proto.coin,
r = MMGenTX.Base().rel_fee_desc,
l = fee_spec_letters(use_quotes=True),
u = fee_spec_names() )
def passwd():
return """
PASSPHRASE NOTE:
For passphrases all combinations of whitespace are equal, and leading and
trailing space are ignored. This permits reading passphrase or brainwallet
data from a multi-line file with free spacing and indentation.
""".strip()
def brainwallet():
return """
BRAINWALLET NOTE:
To thwart dictionary attacks, it's recommended to use a strong hash preset
with brainwallets. For a brainwallet passphrase to generate the correct
seed, the same seed length and hash preset parameters must always be used.
""".strip()
def txcreate():
return f"""
The transaction's outputs are specified on the command line, while its inputs
are chosen from a list of the user's unspent outputs via an interactive menu.
If the transaction fee is not specified on the command line (see FEE
SPECIFICATION below), it will be calculated dynamically using network fee
estimation for the default (or user-specified) number of confirmations.
If network fee estimation fails, the user will be prompted for a fee.
Network-estimated fees will be multiplied by the value of '--tx-fee-adj',
if specified.
Ages of transactions are approximate based on an average block discovery
interval of one per {proto.avg_bdi} seconds.
All addresses on the command line can be either {proto.name} addresses or {g.proj_name}
addresses of the form <seed ID>:<index>.
To send the value of all inputs (minus TX fee) to a single output, specify
one address with no amount on the command line.
"""
def txsign():
return """
Transactions may contain both {pnm} or non-{pnm} input addresses.
To sign non-{pnm} inputs, a {dn} wallet dump or flat key list is used
as the key source ('--keys-from-file' option).
To sign {pnm} inputs, key data is generated from a seed as with the
{pnl}-addrgen and {pnl}-keygen commands. Alternatively, a key-address file
may be used (--mmgen-keys-from-file option).
Multiple wallets or other seed files can be listed on the command line in
any order. If the seeds required to sign the transaction's inputs are not
found in these files (or in the default wallet), the user will be prompted
for seed data interactively.
To prevent an attacker from crafting transactions with bogus {pnm}-to-{pnu}
address mappings, all outputs to {pnm} addresses are verified with a seed
source. Therefore, seed files or a key-address file for all {pnm} outputs
must also be supplied on the command line if the data can't be found in the
default wallet.
""".format(
dn = proto.daemon_name,
pnm = g.proj_name,
pnu = proto.name,
pnl = g.proj_name.lower() )
def seedsplit():
from .obj import SeedShareIdx,SeedShareCount,MasterShareIdx
return """
COMMAND NOTES:
This command generates shares one at a time. Shares may be output to any
MMGen wallet format, with one limitation: only one share in a given split may
be in hidden incognito format, and it must be the master share in the case of
a master-share split.
If the command's optional first argument is omitted, the default wallet is
used for the split.
The last argument is a seed split specifier consisting of an optional split
ID, a share index, and a share count, all separated by colons. The split ID
must be a valid UTF-8 string. If omitted, the ID 'default' is used. The
share index (the index of the share being generated) must be in the range
{si.min_val}-{si.max_val} and the share count (the total number of shares in the split)
in the range {sc.min_val}-{sc.max_val}.
Master Shares
Each seed has a total of {mi.max_val} master shares, which can be used as the first
shares in multiple splits if desired. To generate a master share, use the
--master-share (-M) option with an index in the range {mi.min_val}-{mi.max_val} and omit
the last argument.
When creating and joining a split using a master share, ensure that the same
master share index is used in all split and join commands.
EXAMPLES:
Split a BIP39 seed phrase into two BIP39 shares. Rejoin the split:
$ echo 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong' > sample.bip39
$ mmgen-seedsplit -o bip39 sample.bip39 1:2
BIP39 mnemonic data written to file '03BAE887-default-1of2[D51CB683][128].bip39'
$ mmgen-seedsplit -o bip39 sample.bip39 2:2
BIP39 mnemonic data written to file '03BAE887-default-2of2[67BFD36E][128].bip39'
$ mmgen-seedjoin -o bip39 \\
'03BAE887-default-2of2[67BFD36E][128].bip39' \\
'03BAE887-default-1of2[D51CB683][128].bip39'
BIP39 mnemonic data written to file '03BAE887[128].bip39'
$ cat '03BAE887[128].bip39'
zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong
Create a 3-way default split of your default wallet, outputting all shares
to default wallet format. Rejoin the split:
$ mmgen-seedsplit 1:3 # Step A
$ mmgen-seedsplit 2:3 # Step B
$ mmgen-seedsplit 3:3 # Step C
$ mmgen-seedjoin <output_of_step_A> <output_of_step_B> <output_of_step_C>
Create a 2-way split of your default wallet with ID string 'alice',
outputting shares to MMGen native mnemonic format. Rejoin the split:
$ mmgen-seedsplit -o words alice:1:2 # Step D
$ mmgen-seedsplit -o words alice:2:2 # Step E
$ mmgen-seedjoin <output_of_step_D> <output_of_step_E>
Create a 2-way split of your default wallet with ID string 'bob' using
master share #7, outputting share #1 (the master share) to default wallet
format and share #2 to BIP39 format. Rejoin the split:
$ mmgen-seedsplit -M7 # Step X
$ mmgen-seedsplit -M7 -o bip39 bob:2:2 # Step Y
$ mmgen-seedjoin -M7 --id-str=bob <output_of_step_X> <output_of_step_Y>
Create a 2-way split of your default wallet with ID string 'alice' using
master share #7. Rejoin the split using master share #7 generated in the
previous example:
$ mmgen-seedsplit -M7 -o bip39 alice:2:2 # Step Z
$ mmgen-seedjoin -M7 --id-str=alice <output_of_step_X> <output_of_step_Z>
Create a 2-way default split of your default wallet with an incognito-format
master share hidden in file 'my.hincog' at offset 1325. Rejoin the split:
$ mmgen-seedsplit -M4 -o hincog -J my.hincog,1325 1:2 # Step M (share A)
$ mmgen-seedsplit -M4 -o bip39 2:2 # Step N (share B)
$ mmgen-seedjoin -M4 -H my.hincog,1325 <output_of_step_N>
""".strip().format(
si = SeedShareIdx,
sc = SeedShareCount,
mi = MasterShareIdx )
def subwallet():
from .obj import SubSeedIdxRange
return f"""
SUBWALLETS:
Subwallets (subseeds) are specified by a "Subseed Index" consisting of:
a) an integer in the range 1-{SubSeedIdxRange.max_idx}, plus
b) an optional single letter, 'L' or 'S'
The letter designates the length of the subseed. If omitted, 'L' is assumed.
Long ('L') subseeds are the same length as their parent wallet's seed
(typically 256 bits), while short ('S') subseeds are always 128-bit.
The long and short subseeds for a given index are derived independently,
so both may be used.
MMGen has no notion of "depth", and to an outside observer subwallets are
identical to ordinary wallets. This is a feature rather than a bug, as it
denies an attacker any way of knowing whether a given wallet has a parent.
Since subwallets are just wallets, they may be used to generate other
subwallets, leading to hierarchies of arbitrary depth. However, this is
inadvisable in practice for two reasons: Firstly, it creates accounting
complexity, requiring the user to independently keep track of a derivation
tree. More importantly, however, it leads to the danger of Seed ID
collisions between subseeds at different levels of the hierarchy, as
MMGen checks and avoids ID collisions only among sibling subseeds.
An exception to this caveat would be a multi-user setup where sibling
subwallets are distributed to different users as their default wallets.
Since the subseeds derived from these subwallets are private to each user,
Seed ID collisions among them doesn't present a problem.
A safe rule of thumb, therefore, is for *each user* to derive all of his/her
subwallets from a single parent. This leaves each user with a total of two
million subwallets, which should be enough for most practical purposes.
""".strip()
return getattr(help_notes,k)() + ('-α' if g.debug_utf8 else '')

View file

@ -23,16 +23,18 @@ mmgen-addrgen: Generate a series or range of addresses from an MMGen
from .common import *
from .crypto import *
from .addr import *
from .addr import AddrList,KeyAddrList,KeyList,MMGenAddrType,AddrIdxList
from .wallet import Wallet
if g.prog_name == 'mmgen-keygen':
gen_what = 'keys'
gen_clsname = 'KeyAddrList'
gen_desc = 'secret keys'
opt_filter = None
note_addrkey = 'By default, both addresses and secret keys are generated.\n\n'
else:
gen_what = 'addresses'
gen_clsname = 'AddrList'
gen_desc = 'addresses'
opt_filter = 'hbcdeEiHOkKlpzPqrStUv-'
note_addrkey = ''
@ -102,16 +104,16 @@ FMT CODES:
"""
},
'code': {
'options': lambda s: s.format(
'options': lambda proto,s: s.format(
seed_lens=', '.join(map(str,g.seed_lens)),
dmat="'{}' or '{}'".format(g.proto.dfl_mmtype,MMGenAddrType.mmtypes[g.proto.dfl_mmtype].name),
dmat="'{}' or '{}'".format(proto.dfl_mmtype,MMGenAddrType.mmtypes[proto.dfl_mmtype].name),
kgs=' '.join(['{}:{}'.format(n,k) for n,k in enumerate(g.key_generators,1)]),
kg=g.key_generator,
pnm=g.proj_name,
what=gen_what,
g=g,
),
'notes': lambda s: s.format(
'notes': lambda help_notes,s: s.format(
n_addrkey=note_addrkey,
n_sw=help_notes('subwallet')+'\n\n',
n_pw=help_notes('passwd')+'\n\n',
@ -126,7 +128,14 @@ FMT CODES:
cmd_args = opts.init(opts_data,add_opts=['b16'],opt_filter=opt_filter)
errmsg = "'{}': invalid parameter for --type option".format(opt.type)
addr_type = MMGenAddrType(opt.type or g.proto.dfl_mmtype,errmsg=errmsg)
from .protocol import init_proto_from_opts
proto = init_proto_from_opts()
addr_type = MMGenAddrType(
proto = proto,
id_str = opt.type or proto.dfl_mmtype,
errmsg = errmsg )
if len(cmd_args) < 1: opts.usage()
@ -143,8 +152,15 @@ ss = Wallet(sf)
ss_seed = ss.seed if opt.subwallet is None else ss.seed.subseed(opt.subwallet,print_msg=True)
i = (gen_what=='addresses') or bool(opt.no_addresses)*2
al = (KeyAddrList,AddrList,KeyList)[i](seed=ss_seed,addr_idxs=idxs,mmtype=addr_type)
if opt.no_addresses:
gen_clsname = 'KeyList'
al = globals()[gen_clsname](
proto = proto,
seed = ss_seed,
addr_idxs = idxs,
mmtype = addr_type )
al.format()
if al.gen_addrs and opt.print_checksum:

View file

@ -24,7 +24,7 @@ import time
from .common import *
from .addr import AddrList,KeyAddrList
from .obj import TwLabel,is_coin_addr
from .obj import TwLabel
ai_msgs = lambda k: {
'rescan': """
@ -61,6 +61,7 @@ opts_data = {
-q, --quiet Suppress warnings
-r, --rescan Rescan the blockchain. Required if address to import is
in the blockchain and has a balance. Rescanning is slow.
-t, --token-addr=A Import addresses for ERC20 token with address 'A'
""",
'notes': """\n
This command can also be used to update the comment fields of addresses
@ -71,13 +72,12 @@ The --batch and --rescan options cannot be used together.
}
}
def parse_cmd_args(cmd_args):
def parse_cmd_args(rpc,cmd_args):
def import_mmgen_list(infile):
al = (AddrList,KeyAddrList)[bool(opt.keyaddr_file)](infile)
al = (AddrList,KeyAddrList)[bool(opt.keyaddr_file)](proto,infile)
if al.al_id.mmtype in ('S','B'):
from .tx import segwit_is_active
if not segwit_is_active():
if not rpc.info('segwit_is_active'):
rdie(2,'Segwit is not active on this chain. Cannot import Segwit addresses')
return al
@ -85,14 +85,14 @@ def parse_cmd_args(cmd_args):
infile = cmd_args[0]
check_infile(infile)
if opt.addrlist:
al = AddrList(addrlist=get_lines_from_file(
infile,
'non-{pnm} addresses'.format(pnm=g.proj_name),
trim_comments=True))
al = AddrList(
proto = proto,
addrlist = get_lines_from_file(infile,'non-{pnm} addresses'.format(pnm=g.proj_name),
trim_comments = True) )
else:
al = import_mmgen_list(infile)
elif len(cmd_args) == 0 and opt.address:
al = AddrList(addrlist=[opt.address])
al = AddrList(proto=proto,addrlist=[opt.address])
infile = 'command line'
else:
die(1,ai_msgs('bad_args'))
@ -145,17 +145,28 @@ def make_args_list(tw,al,batch,rescan):
label = '{}:{}'.format(al.al_id,e.idx) + (' ' + e.label if e.label else '')
add_msg = label
else:
label = '{}:{}'.format(g.proto.base_coin.lower(),e.addr)
label = '{}:{}'.format(proto.base_coin.lower(),e.addr)
add_msg = 'non-'+g.proj_name
if batch:
yield (e.addr,TwLabel(label),False)
yield (e.addr,TwLabel(proto,label),False)
else:
msg_args = ( f'{num}/{al.num_addrs}:', e.addr, '('+add_msg+')' )
yield (tw,e.addr,TwLabel(label),rescan,fs,msg_args)
yield (tw,e.addr,TwLabel(proto,label),rescan,fs,msg_args)
async def main():
al,infile = parse_cmd_args(cmd_args)
from .tw import TrackingWallet
if opt.token_addr:
proto.tokensym = 'foo' # hack to trigger 'Token' in altcoin_subclass()
tw = await TrackingWallet(
proto = proto,
token_addr = opt.token_addr,
mode = 'i' )
from .rpc import rpc_init
tw.rpc = await rpc_init(proto)
al,infile = parse_cmd_args(tw.rpc,cmd_args)
qmsg(
f'OK. {al.num_addrs} addresses'
@ -165,17 +176,8 @@ async def main():
f'Importing {len(al.data)} address{suf(al.data,"es")} from {infile}'
+ (' (batch mode)' if opt.batch else '') )
if not al.data[0].addr.is_for_chain(g.chain):
die(2,f'Address{(" list","")[bool(opt.address)]} incompatible with {g.chain} chain!')
from .tw import TrackingWallet
tw = await TrackingWallet(mode='i')
batch,rescan = check_opts(tw)
if g.token:
await tw.import_token()
args_list = make_args_list(tw,al,batch,rescan)
if batch:
@ -192,5 +194,7 @@ async def main():
del tw
cmd_args = opts.init(opts_data)
from .protocol import init_proto_from_opts
proto = init_proto_from_opts()
import asyncio
run_session(main())

View file

@ -134,17 +134,13 @@ async def check_daemons_running():
coins = ['BTC']
for coin in coins:
g.proto = init_proto(coin,g.proto.testnet)
if g.proto.sign_mode == 'daemon':
if g.test_suite:
g.proto.daemon_data_dir = 'test/daemons/' + coin.lower()
g.rpc_port = CoinDaemon(get_network_id(coin,g.proto.testnet),test_suite=True).rpc_port
proto = init_proto(coin,testnet=g.testnet)
if proto.sign_mode == 'daemon':
vmsg(f'Checking {coin} daemon')
try:
await rpc_init()
except SystemExit as e:
if e.code != 0:
ydie(1,f'{coin} daemon not running or not listening on port {g.proto.rpc_port}')
await rpc_init(proto)
except SocketError as e:
ydie(1,f'{coin} daemon not running or not listening on port {proto.rpc_port}')
def get_wallet_files():
try:
@ -175,45 +171,23 @@ def do_umount():
msg(f'Unmounting {mountpoint}')
run(['umount',mountpoint],check=True)
async def sign_tx_file(txfile,signed_txs):
async def sign_tx_file(txfile):
from .tx import MMGenTX
try:
g.proto = init_proto('BTC',testnet=False)
tmp_tx = mmgen.tx.MMGenTX(txfile,metadata_only=True)
g.proto = init_proto(tmp_tx.coin)
if tmp_tx.chain != 'mainnet':
if tmp_tx.chain == 'testnet' or (
hasattr(g.proto,'chain_name') and tmp_tx.chain != g.proto.chain_name):
g.proto = init_proto(tmp_tx.coin,testnet=True)
if hasattr(g.proto,'chain_name'):
if tmp_tx.chain != g.proto.chain_name:
die(2, f'Chains do not match! tx file: {tmp_tx.chain}, proto: {g.proto.chain_name}')
g.chain = tmp_tx.chain
g.token = tmp_tx.dcoin
g.proto.dcoin = tmp_tx.dcoin or g.proto.coin
tx = mmgen.tx.MMGenTxForSigning(txfile)
if g.proto.sign_mode == 'daemon':
if g.test_suite:
g.proto.daemon_data_dir = 'test/daemons/' + g.coin.lower()
g.rpc_port = CoinDaemon(get_network_id(g.coin,g.proto.testnet),test_suite=True).rpc_port
await rpc_init()
if await txsign(tx,wfs,None,None):
tx.write_to_file(ask_write=False)
signed_txs.append(tx)
return True
tx1 = MMGenTX.Unsigned(filename=txfile)
if tx1.proto.sign_mode == 'daemon':
tx1.rpc = await rpc_init(tx1.proto)
tx2 = await txsign(tx1,wfs,None,None)
if tx2:
tx2.write_to_file(ask_write=False)
return tx2
else:
return False
except Exception as e:
msg(f'An error occurred: {e.args[0]}')
if g.debug or g.traceback:
print_stack_trace(f'AUTOSIGN {txfile}')
ymsg(f'An error occurred with transaction {txfile!r}:\n {e!s}')
return False
except:
ymsg(f'An error occurred with transaction {txfile!r}')
return False
async def sign():
@ -224,8 +198,10 @@ async def sign():
if unsigned:
signed_txs,fails = [],[]
for txfile in unsigned:
ret = await sign_tx_file(txfile,signed_txs)
if not ret:
ret = await sign_tx_file(txfile)
if ret:
signed_txs.append(ret)
else:
fails.append(txfile)
qmsg('')
time.sleep(0.3)
@ -265,7 +241,6 @@ def print_summary(signed_txs):
bmsg('\nAutosign summary:\n')
def gen():
for tx in signed_txs:
g.proto = init_proto(tx.coin,testnet=tx.chain=='testnet')
yield tx.format_view(terse=True)
msg_r(''.join(gen()))
return
@ -444,4 +419,4 @@ async def main():
elif cmd_args[0] == 'wait':
await do_loop()
run_session(main(),do_rpc_init=False)
run_session(main())

View file

@ -120,7 +120,7 @@ FMT CODES:
dpf=PasswordList.dfl_pw_fmt,
kgs=' '.join(['{}:{}'.format(n,k) for n,k in enumerate(g.key_generators,1)])
),
'notes': lambda s: s.format(
'notes': lambda help_notes,s: s.format(
o=opts,g=g,i58=pwi['b58'],i32=pwi['b32'],i39=pwi['bip39'],
ml=MMGenPWIDString.max_len,
fs="', '".join(MMGenPWIDString.forbidden),
@ -147,7 +147,11 @@ sf = get_seed_file(cmd_args,1)
pw_fmt = opt.passwd_fmt or PasswordList.dfl_pw_fmt
pw_len = pwi[pw_fmt].dfl_len // 2 if opt.passwd_len in ('h','H') else opt.passwd_len
from .protocol import init_proto
proto = init_proto('btc') # TODO: get rid of dummy proto
PasswordList(
proto = proto,
pw_id_str = pw_id_str,
pw_len = pw_len,
pw_fmt = pw_fmt,
@ -158,6 +162,7 @@ do_license_msg()
ss = Wallet(sf)
al = PasswordList(
proto = proto,
seed = ss.seed,
pw_idxs = pw_idxs,
pw_id_str = pw_id_str,

View file

@ -82,7 +82,7 @@ FMT CODES:
ms_max=MasterShareIdx.max_val,
g=g,
),
'notes': lambda s: s.format(
'notes': lambda help_notes,s: s.format(
f='\n '.join(Wallet.format_fmt_codes().splitlines()),
n_pw=help_notes('passwd'),
)

View file

@ -80,19 +80,23 @@ transaction reconfirmed before the timelock expires. Use at your own risk.
""".format(pnm=g.proj_name)
},
'code': {
'options': lambda s: s.format(
oc=g.proto.forks[-1][2].upper(),
'options': lambda proto,s: s.format(
oc=proto.forks[-1][2].upper(),
bh='current block height'),
}
}
cmd_args = opts.init(opts_data,add_opts=['tx_fee','tx_fee_adj','comment_file'])
from .protocol import init_proto_from_opts
proto = init_proto_from_opts()
die(1,'This command is disabled')
opt.other_coin = opt.other_coin.upper() if opt.other_coin else g.proto.forks[-1][2].upper()
if opt.other_coin.lower() not in [e[2] for e in g.proto.forks if e[3] == True]:
die(1,"'{}': not a replayable fork of {} chain".format(opt.other_coin,g.coin))
# the following code is broken:
opt.other_coin = opt.other_coin.upper() if opt.other_coin else proto.forks[-1][2].upper()
if opt.other_coin.lower() not in [e[2] for e in proto.forks if e[3] == True]:
die(1,"'{}': not a replayable fork of {} chain".format(opt.other_coin,proto.coin))
if len(cmd_args) != 2:
fs = 'This command requires exactly two {} addresses as arguments'
@ -111,8 +115,8 @@ from .tx import MMGenSplitTX
from .protocol import init_proto
if opt.tx_fees:
for idx,g_coin in ((1,opt.other_coin),(0,g.coin)):
g.proto = init_proto(g_coin)
for idx,g_coin in ((1,opt.other_coin),(0,proto.coin)):
proto = init_proto(g_coin)
opt.tx_fee = opt.tx_fees.split(',')[idx]
opts.opt_is_tx_fee('foo',opt.tx_fee,'transaction fee') # raises exception on error
@ -120,8 +124,11 @@ tx1 = MMGenSplitTX()
opt.no_blank = True
async def main():
gmsg("Creating timelocked transaction for long chain ({})".format(g.coin))
locktime = int(opt.locktime or 0) or await g.rpc.call('getblockcount')
gmsg("Creating timelocked transaction for long chain ({})".format(proto.coin))
locktime = int(opt.locktime)
if not locktime:
rpc = rpc_init(proto)
locktime = rpc.call('getblockcount')
tx1.create(mmids[0],locktime)
tx1.format()
@ -129,7 +136,7 @@ async def main():
gmsg("\nCreating transaction for short chain ({})".format(opt.other_coin))
g.proto = init_proto(opt.other_coin)
proto = init_proto(opt.other_coin)
tx2 = MMGenSplitTX()
tx2.inputs = tx1.inputs

View file

@ -81,7 +81,7 @@ column below:
"""
},
'code': {
'options': lambda s: s.format(
'options': lambda help_notes,proto,s: s.format(
g=g,
pnm=g.proj_name,
pnl=g.proj_name.lower(),
@ -89,8 +89,8 @@ column below:
fu=help_notes('rel_fee_desc'),fl=help_notes('fee_spec_letters'),
kgs=' '.join(['{}:{}'.format(n,k) for n,k in enumerate(g.key_generators,1)]),
kg=g.key_generator,
cu=g.coin),
'notes': lambda s: s.format(
cu=proto.coin),
'notes': lambda help_notes,s: s.format(
help_notes('fee'),
help_notes('txsign'),
f='\n '.join(Wallet.format_fmt_codes().splitlines()))
@ -107,41 +107,56 @@ from .txsign import *
seed_files = get_seed_files(opt,cmd_args) if (cmd_args or opt.send) else None
kal = get_keyaddrlist(opt)
kl = get_keylist(opt)
sign_and_send = bool(seed_files or kl or kal)
do_license_msg()
silent = opt.yes and opt.tx_fee != None and opt.output_to_reduce != None
ext = get_extension(tx_file)
ext_data = {
MMGenTX.Unsigned.ext: 'Unsigned',
MMGenTX.Signed.ext: 'Signed',
}
if ext not in ext_data:
die(1,f'{ext!r}: unrecognized file extension')
async def main():
from .tw import TrackingWallet
tx = MMGenBumpTX(filename=tx_file,send=sign_and_send,tw=await TrackingWallet() if g.token else None)
orig_tx = getattr(MMGenTX,ext_data[ext])(filename=tx_file)
if not silent:
msg(green('ORIGINAL TRANSACTION'))
msg(tx.format_view(terse=True))
msg(orig_tx.format_view(terse=True))
kal = get_keyaddrlist(orig_tx.proto,opt)
kl = get_keylist(orig_tx.proto,opt)
sign_and_send = bool(seed_files or kl or kal)
from .tw import TrackingWallet
tx = MMGenTX.Bump(
data = orig_tx.__dict__,
send = sign_and_send,
tw = await TrackingWallet(orig_tx.proto) if orig_tx.proto.tokensym else None )
from .rpc import rpc_init
tx.rpc = await rpc_init(tx.proto)
tx.check_bumpable() # needs cached networkinfo['relayfee']
msg('Creating new transaction')
msg('Creating replacement transaction')
op_idx = tx.choose_output()
if not silent:
msg('Minimum fee for new transaction: {} {}'.format(tx.min_fee.hl(),g.coin))
msg('Minimum fee for new transaction: {} {}'.format(tx.min_fee.hl(),tx.proto.coin))
fee = tx.get_usr_fee_interactive(tx_fee=opt.tx_fee,desc='User-selected')
tx.update_fee(op_idx,fee)
d = tx.get_fee()
assert d == fee and d <= g.proto.max_tx_fee
assert d == fee and d <= tx.proto.max_tx_fee
if g.proto.base_proto == 'Bitcoin':
if tx.proto.base_proto == 'Bitcoin':
tx.outputs.sort_bip69() # output amts have changed, so re-sort
if not opt.yes:
@ -159,10 +174,12 @@ async def main():
msg_r(tx.format_view(terse=True))
if sign_and_send:
if await txsign(tx,seed_files,kl,kal):
tx.write_to_file(ask_write=False)
await tx.send(exit_on_fail=True)
tx.write_to_file(ask_write=False)
tx2 = MMGenTX.Unsigned(data=tx.__dict__)
tx3 = await txsign(tx2,seed_files,kl,kal)
if tx3:
tx3.write_to_file(ask_write=False)
await tx3.send(exit_on_fail=True)
tx3.write_to_file(ask_write=False)
else:
die(2,'Transaction could not be signed')
else:

View file

@ -61,14 +61,14 @@ opts_data = {
'notes': '\n{}{}',
},
'code': {
'options': lambda s: s.format(
'options': lambda proto,help_notes,s: s.format(
fu=help_notes('rel_fee_desc'),
fl=help_notes('fee_spec_letters'),
fe_all=fmt_list(g.autoset_opts['fee_estimate_mode'].choices,fmt='no_spc'),
fe_dfl=g.autoset_opts['fee_estimate_mode'].choices[0],
cu=g.coin,
cu=proto.coin,
g=g),
'notes': lambda s: s.format(
'notes': lambda help_notes,s: s.format(
help_notes('txcreate'),
help_notes('fee'))
}
@ -79,10 +79,27 @@ cmd_args = opts.init(opts_data)
g.use_cached_balances = opt.cached_balances
async def main():
from .protocol import init_proto_from_opts
proto = init_proto_from_opts()
from .tx import MMGenTX
from .tw import TrackingWallet
tx = MMGenTX(tw=await TrackingWallet() if g.token else None)
await tx.create(cmd_args,int(opt.locktime or 0),do_info=opt.info)
tx.write_to_file(ask_write=not opt.yes,ask_overwrite=not opt.yes,ask_write_default_yes=False)
tx1 = MMGenTX.New(
proto = proto,
tw = await TrackingWallet(proto) if proto.tokensym else None )
from .rpc import rpc_init
tx1.rpc = await rpc_init(proto)
tx2 = await tx1.create(
cmd_args = cmd_args,
locktime = int(opt.locktime or 0),
do_info = opt.info )
tx2.write_to_file(
ask_write = not opt.yes,
ask_overwrite = not opt.yes,
ask_write_default_yes = False )
run_session(main())

View file

@ -93,7 +93,7 @@ column below:
"""
},
'code': {
'options': lambda s: s.format(
'options': lambda proto,help_notes,s: s.format(
g=g,pnm=g.proj_name,pnl=g.proj_name.lower(),
kgs=' '.join(['{}:{}'.format(n,k) for n,k in enumerate(g.key_generators,1)]),
fu=help_notes('rel_fee_desc'),
@ -103,8 +103,8 @@ column below:
fe_all=fmt_list(g.autoset_opts['fee_estimate_mode'].choices,fmt='no_spc'),
fe_dfl=g.autoset_opts['fee_estimate_mode'].choices[0],
kg=g.key_generator,
cu=g.coin),
'notes': lambda s: s.format(
cu=proto.coin),
'notes': lambda help_notes,s: s.format(
help_notes('txcreate'),
help_notes('fee'),
help_notes('txsign'),
@ -121,24 +121,36 @@ from .txsign import *
seed_files = get_seed_files(opt,cmd_args)
kal = get_keyaddrlist(opt)
kl = get_keylist(opt)
if kl and kal:
kl.remove_dup_keys(kal)
async def main():
from .tw import TrackingWallet
tx1 = MMGenTX(caller='txdo',tw=await TrackingWallet() if g.token else None)
await tx1.create(cmd_args,int(opt.locktime or 0))
from .protocol import init_proto_from_opts
proto = init_proto_from_opts()
tx2 = MMGenTxForSigning(data=tx1.__dict__)
tx1 = MMGenTX.New(
proto = proto,
tw = await TrackingWallet(proto) if proto.tokensym else None )
if await txsign(tx2,seed_files,kl,kal):
tx2.write_to_file(ask_write=False)
await tx2.send(exit_on_fail=True)
tx2.write_to_file(ask_overwrite=False,ask_write=False)
tx2.print_contract_addr()
from .rpc import rpc_init
tx1.rpc = await rpc_init(proto)
tx2 = await tx1.create(
cmd_args = cmd_args,
locktime = int(opt.locktime or 0),
caller = 'txdo' )
kal = get_keyaddrlist(proto,opt)
kl = get_keylist(proto,opt)
if kl and kal:
kl.remove_dup_keys(kal)
tx3 = await txsign(tx2,seed_files,kl,kal)
if tx3:
tx3.write_to_file(ask_write=False)
await tx3.send(exit_on_fail=True)
tx3.write_to_file(ask_overwrite=False,ask_write=False)
tx3.print_contract_addr()
else:
die(2,'Transaction could not be signed')

View file

@ -41,37 +41,36 @@ opts_data = {
cmd_args = opts.init(opts_data)
if len(cmd_args) == 1:
infile = cmd_args[0]; check_infile(infile)
infile = cmd_args[0]
check_infile(infile)
else:
opts.usage()
if not opt.status:
do_license_msg()
from .tx import *
async def main():
from .tw import TrackingWallet
tx = MMGenTX(infile,quiet_open=True,tw=await TrackingWallet() if g.token else None)
from .tx import MMGenTX
if g.token:
from .tw import TrackingWallet
tx.tw = await TrackingWallet()
tx = MMGenTX.Signed(
filename = infile,
quiet_open = True,
tw = await MMGenTX.Signed.get_tracking_wallet(infile) )
vmsg("Signed transaction file '{}' is valid".format(infile))
from .rpc import rpc_init
tx.rpc = await rpc_init(tx.proto)
if not tx.marked_signed():
die(1,'Transaction is not signed!')
vmsg(f'Signed transaction file {infile!r} is valid')
if opt.status:
if tx.coin_txid:
qmsg('{} txid: {}'.format(g.coin,tx.coin_txid.hl()))
qmsg(f'{tx.proto.coin} txid: {tx.coin_txid.hl()}')
await tx.get_status(status=True)
sys.exit(0)
if not opt.yes:
tx.view_with_prompt('View transaction data?')
tx.view_with_prompt('View transaction details?')
if tx.add_comment(): # edits an existing comment, returns true if changed
tx.write_to_file(ask_write_default_yes=True)

View file

@ -77,17 +77,17 @@ column below:
"""
},
'code': {
'options': lambda s: s.format(
'options': lambda proto,s: s.format(
g=g,
pnm=g.proj_name,
pnl=g.proj_name.lower(),
dn=g.proto.daemon_name,
dn=proto.daemon_name,
kgs=' '.join(['{}:{}'.format(n,k) for n,k in enumerate(g.key_generators,1)]),
kg=g.key_generator,
ss=g.subseeds,
ss_max=SubSeedIdxRange.max_idx,
cu=g.coin),
'notes': lambda s: s.format(
cu=proto.coin),
'notes': lambda help_notes,s: s.format(
help_notes('txsign'),
f='\n '.join(Wallet.format_fmt_codes().splitlines()))
}
@ -108,43 +108,47 @@ from .txsign import *
tx_files = get_tx_files(opt,infiles)
seed_files = get_seed_files(opt,infiles)
kal = get_keyaddrlist(opt)
kl = get_keylist(opt)
if kl and kal:
kl.remove_dup_keys(kal)
async def main():
bad_tx_count = 0
tx_num_disp = ''
for tx_num,tx_file in enumerate(tx_files,1):
if len(tx_files) > 1:
msg('\nTransaction #{} of {}:'.format(tx_num,len(tx_files)))
tx_num_disp = f' #{tx_num}'
msg(f'\nTransaction{tx_num_disp} of {len(tx_files)}:')
tx = MMGenTxForSigning(tx_file)
if tx.marked_signed():
msg('Transaction is already signed!')
continue
tx1 = MMGenTX.Unsigned(filename=tx_file)
vmsg(f'Successfully opened transaction file {tx_file!r}')
if tx1.proto.sign_mode == 'daemon':
from .rpc import rpc_init
tx1.rpc = await rpc_init(tx1.proto)
if opt.tx_id:
msg(tx.txid)
msg(tx1.txid)
continue
if opt.info or opt.terse_info:
tx.view(pause=False,terse=opt.terse_info)
tx1.view(pause=False,terse=opt.terse_info)
continue
if not opt.yes:
tx.view_with_prompt(f'View data for transaction{tx_num_disp}?')
tx1.view_with_prompt(f'View data for transaction{tx_num_disp}?')
if await txsign(tx,seed_files,kl,kal,tx_num_disp):
kal = get_keyaddrlist(tx1.proto,opt)
kl = get_keylist(tx1.proto,opt)
if kl and kal:
kl.remove_dup_keys(kal)
tx2 = await txsign(tx1,seed_files,kl,kal,tx_num_disp)
if tx2:
if not opt.yes:
tx.add_comment() # edits an existing comment
tx.write_to_file(ask_write=not opt.yes,ask_write_default_yes=True,add_desc=tx_num_disp)
tx2.add_comment() # edits an existing comment
tx2.write_to_file(ask_write=not opt.yes,ask_write_default_yes=True,add_desc=tx_num_disp)
else:
ymsg('Transaction could not be signed')
bad_tx_count += 1
@ -152,7 +156,4 @@ async def main():
if bad_tx_count:
ydie(2,f'{bad_tx_count} transaction{suf(bad_tx_count)} could not be signed')
run_session(
main(),
do_rpc_init = g.proto.sign_mode == 'daemon'
)
run_session(main())

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