whitespace throughout

This commit is contained in:
The MMGen Project 2024-09-29 11:59:55 +00:00
commit 044c2a0b91
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
17 changed files with 95 additions and 89 deletions

View file

@ -151,7 +151,7 @@ class CoinAddr(HiliteStr, InitErrors, MMGenObject):
width = 1
trunc_ok = False
def __new__(cls,proto,addr):
def __new__(cls, proto, addr):
if isinstance(addr,cls):
return addr
try:

View file

@ -203,17 +203,17 @@ class AddrFile(MMGenObject):
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'
- 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()
@ -229,18 +229,18 @@ class AddrFile(MMGenObject):
from .proto.btc.params import mainnet
if lbl in [MMGenAddrType(mainnet,key).name for key in mainnet.mmtypes]:
coin,mmtype_key = ( 'BTC', lbl )
coin, mmtype_key = ('BTC', lbl)
elif ':' in lbl: # first component is coin, second is mmtype_key
coin,mmtype_key = lbl.split(':')
coin, mmtype_key = lbl.split(':')
else: # only component is coin
coin,mmtype_key = ( lbl, None )
coin, mmtype_key = (lbl, None)
proto = init_proto( p.cfg, coin=coin, network=network )
proto = init_proto(p.cfg, coin=coin, network=network)
if mmtype_key is None:
mmtype_key = proto.mmtypes[0]
return ( proto, proto.addr_type(mmtype_key) )
return (proto, proto.addr_type(mmtype_key))
p = self.parent

View file

@ -146,7 +146,7 @@ class AddrList(MMGenObject): # Address info for a single seed ID
gen_passwds = False
gen_keys = False
has_keys = False
chksum_rec_f = lambda foo,e: ( str(e.idx), e.addr )
chksum_rec_f = lambda foo, e: (str(e.idx), e.addr)
def dmsg_sc(self,desc,data):
Msg(f'sc_debug_{desc}: {data}')
@ -414,12 +414,12 @@ class KeyAddrList(AddrList):
gen_desc_pl = 's'
gen_keys = True
has_keys = True
chksum_rec_f = lambda foo,e: (str(e.idx), e.addr, e.sec.wif)
chksum_rec_f = lambda foo, e: (str(e.idx), e.addr, e.sec.wif)
class ViewKeyAddrList(KeyAddrList):
desc = 'viewkey-address'
gen_desc = 'viewkey/address pair'
chksum_rec_f = lambda foo,e: ( str(e.idx), e.addr )
chksum_rec_f = lambda foo, e: (str(e.idx), e.addr)
class KeyList(KeyAddrList):
desc = 'key'

View file

@ -45,7 +45,7 @@ long_opts_data = {
--, --color=0|1 Disable or enable color output (enabled by default)
--, --columns=N Force N columns of output with certain commands
--, --scroll Use the curses-like scrolling interface for
tracking wallet views
tracking wallet views
--, --force-256-color Force 256-color output when color is enabled
--, --pager Pipe output of certain commands to pager (WIP)
--, --data-dir=path Specify {pnm} data directory location

View file

@ -12,7 +12,7 @@
proto.btc.addrgen: Bitcoin address generation classes for the MMGen suite
"""
from ...addrgen import addr_generator,check_data
from ...addrgen import addr_generator, check_data
from ...addr import CoinAddr
from .common import hash160

View file

@ -12,8 +12,8 @@
proto.btc.params: Bitcoin protocol
"""
from ...protocol import CoinProtocol,decoded_wif,decoded_addr,_finfo,_nw
from .common import b58chk_decode,b58chk_encode,hash160
from ...protocol import CoinProtocol, decoded_wif, decoded_addr, _finfo, _nw
from .common import b58chk_decode, b58chk_encode, hash160
class mainnet(CoinProtocol.Secp256k1): # chainparams.cpp
"""
@ -90,25 +90,25 @@ class mainnet(CoinProtocol.Secp256k1): # chainparams.cpp
return self.decode_addr_bytes(b58chk_decode(addr))
def pubhash2addr(self,pubhash,p2sh):
def pubhash2addr(self, pubhash, p2sh):
assert len(pubhash) == self.addr_len, f'{len(pubhash)}: invalid length for pubkey hash'
return b58chk_encode(
self.addr_fmt_to_ver_bytes[('p2pkh','p2sh')[p2sh]] + pubhash
)
# Segwit:
def pubhash2redeem_script(self,pubhash):
def pubhash2redeem_script(self, pubhash):
# https://bitcoincore.org/en/segwit_wallet_dev/
# The P2SH redeemScript is always 22 bytes. It starts with a OP_0, followed
# by a canonical push of the keyhash (i.e. 0x0014{20-byte keyhash})
return bytes.fromhex(self.witness_vernum_hex + '14') + pubhash
def pubhash2segwitaddr(self,pubhash):
def pubhash2segwitaddr(self, pubhash):
return self.pubhash2addr(
hash160( self.pubhash2redeem_script(pubhash) ),
p2sh = True )
def pubhash2bech32addr(self,pubhash):
def pubhash2bech32addr(self, pubhash):
from ...contrib import bech32
return bech32.bech32_encode(
hrp = self.bech32_hrp,

View file

@ -159,7 +159,8 @@ class BitcoinTwTransaction:
yield fs1.format(
i = CoinTxID(e.txid).hl(color=color),
n = (nocolor,red)[color](str(e.data['n']).ljust(3)),
a = CoinAddr(self.proto,e.coin_addr).fmt( width=self.max_addrlen[src], color=color ),
a = CoinAddr(self.proto, e.coin_addr).fmt(
width=self.max_addrlen[src], color=color),
A = self.proto.coin_amt( e.data['value'] ).fmt(color=color)
).rstrip()
else:
@ -191,7 +192,7 @@ class BitcoinTwTransaction:
if not mmid:
if width and space_left < addr_w:
break
yield CoinAddr( self.proto, e.coin_addr ).fmt(width=addr_w,color=color)
yield CoinAddr(self.proto, e.coin_addr).fmt(width=addr_w, color=color)
space_left -= addr_w
elif mmid.type == 'mmgen':
mmid_disp = mmid + bal_star

View file

@ -33,11 +33,11 @@ def addr2scriptPubKey(proto,addr):
def scriptPubKey2addr(proto,s):
if len(s) == 50 and s[:6] == '76a914' and s[-4:] == '88ac':
return proto.pubhash2addr(bytes.fromhex(s[6:-4]),p2sh=False),'p2pkh'
return proto.pubhash2addr(bytes.fromhex(s[6:-4]), p2sh=False), 'p2pkh'
elif len(s) == 46 and s[:4] == 'a914' and s[-2:] == '87':
return proto.pubhash2addr(bytes.fromhex(s[4:-2]),p2sh=True),'p2sh'
return proto.pubhash2addr(bytes.fromhex(s[4:-2]), p2sh=True), 'p2sh'
elif len(s) == 44 and s[:4] == proto.witness_vernum_hex + '14':
return proto.pubhash2bech32addr(bytes.fromhex(s[4:])),'bech32'
return proto.pubhash2bech32addr(bytes.fromhex(s[4:])), 'bech32'
else:
raise NotImplementedError(f'Unknown scriptPubKey ({s})')
@ -284,17 +284,17 @@ class Base(TxBase.Base):
"""
def do_error(errmsg):
die( 'TxHexMismatch', errmsg+'\n'+hdr )
die('TxHexMismatch', errmsg+'\n'+hdr)
def check_equal(desc,hexio,mmio):
if mmio != hexio:
msg('\nMMGen {d}:\n{m}\nSerialized {d}:\n{h}'.format(
d = desc,
m = pp_fmt(mmio),
h = pp_fmt(hexio) ))
h = pp_fmt(hexio)))
do_error(
f'{desc.capitalize()} in serialized transaction data from coin daemon ' +
'do not match those in MMGen transaction!' )
'do not match those in MMGen transaction!')
hdr = 'A malicious or malfunctioning coin daemon or other program may have altered your data!'
@ -303,23 +303,22 @@ class Base(TxBase.Base):
if dtx.locktime != int(self.locktime or 0):
do_error(
f'Transaction hex nLockTime ({dtx.locktime}) ' +
f'does not match MMGen transaction nLockTime ({self.locktime})' )
f'does not match MMGen transaction nLockTime ({self.locktime})')
check_equal(
'sequence numbers',
[i['nSeq'] for i in dtx.txins],
['{:08x}'.format(i.sequence or self.proto.max_int) for i in self.inputs] )
['{:08x}'.format(i.sequence or self.proto.max_int) for i in self.inputs])
check_equal(
'inputs',
sorted((i['txid'],i['vout']) for i in dtx.txins),
sorted((i.txid,i.vout) for i in self.inputs) )
sorted((i['txid'], i['vout']) for i in dtx.txins),
sorted((i.txid, i.vout) for i in self.inputs))
check_equal(
'outputs',
sorted((o['address'],self.proto.coin_amt(o['amount'])) for o in dtx.txouts),
sorted((o.addr,o.amt) for o in self.outputs) )
sorted((o['address'], self.proto.coin_amt(o['amount'])) for o in dtx.txouts),
sorted((o.addr, o.amt) for o in self.outputs))
if str(self.txid) != make_chksum_6(bytes.fromhex(dtx.unsigned_hex)).upper():
do_error(
f'MMGen TxID ({self.txid}) does not match serialized transaction data!')
do_error(f'MMGen TxID ({self.txid}) does not match serialized transaction data!')

View file

@ -36,14 +36,15 @@ class TxInfo(TxInfo):
if len(getattr(tx,k)):
m[k] = getattr(tx,k)[0].mmid if len(getattr(tx,k)) else ''
m[k] = ' ' + m[k].hl() if m[k] else ' ' + MMGenID.hlc(nonmm_str)
fs = """From: {}{f_mmid}
To: {}{t_mmid}
Amount: {} {c}
Gas price: {g} Gwei
Start gas: {G} Kwei
Nonce: {}
Data: {d}
\n""".replace('\t','')
fs = """
From: {f}{f_mmid}
To: {t}{t_mmid}
Amount: {a} {c}
Gas price: {g} Gwei
Start gas: {G} Kwei
Nonce: {n}
Data: {d}
""".strip().replace('\t','')
t = tx.txobj
td = t['data']
return fs.format(
@ -53,7 +54,7 @@ class TxInfo(TxInfo):
g = yellow(str(t['gasPrice'].to_unit('Gwei',show_decimal=True))),
G = yellow(str(t['startGas'].to_unit('Kwei'))),
t_mmid = m['outputs'] if len(tx.outputs) else '',
f_mmid = m['inputs'] )
f_mmid = m['inputs']) + '\n\n'
def format_abs_fee(self,color,iwidth):
return self.tx.fee.fmt(color=color,iwidth=iwidth) + (' (max)' if self.tx.txobj['data'] else '')

View file

@ -56,7 +56,7 @@ class OnlineSigned(Signed,TxBase.OnlineSigned):
def print_contract_addr(self):
if 'token_addr' in self.txobj:
msg('Contract address: {}'.format( self.txobj['token_addr'].hl() ))
msg('Contract address: {}'.format(self.txobj['token_addr'].hl()))
class TokenOnlineSigned(TokenSigned,OnlineSigned):

View file

@ -48,11 +48,11 @@ class Unsigned(Completed,TxBase.Unsigned):
'gasprice': o['gasPrice'].toWei(),
'value': o['amt'].toWei() if o['amt'] else 0,
'nonce': o['nonce'],
'data': bytes.fromhex(o['data']) }
'data': bytes.fromhex(o['data'])}
from ..pyethereum.transactions import Transaction
etx = Transaction(**o_conv).sign(wif,o['chainId'])
assert etx.sender.hex() == o['from'],(
etx = Transaction(**o_conv).sign(wif, o['chainId'])
assert etx.sender.hex() == o['from'], (
'Sender address recovered from signature does not match true sender')
from .. import rlp

View file

@ -148,7 +148,7 @@ class tool_cmd(tool_cmd_base):
"convert a hexadecimal pubkey to a Segwit P2SH-P2WPKH redeem script"
assert self.mmtype.name == 'segwit','This command is meaningful only for --type=segwit'
from ..proto.btc.common import hash160
return self.proto.pubhash2redeem_script( hash160(bytes.fromhex(pubkeyhex)) ).hex()
return self.proto.pubhash2redeem_script(hash160(bytes.fromhex(pubkeyhex))).hex()
def redeem_script2addr(self,redeem_script_hex:'sstr'): # new
"convert a Segwit P2SH-P2WPKH redeem script to an address"
@ -156,19 +156,17 @@ class tool_cmd(tool_cmd_base):
assert redeem_script_hex[:4] == '0014', f'{redeem_script_hex!r}: invalid redeem script'
assert len(redeem_script_hex) == 44, f'{len(redeem_script_hex)//2} bytes: invalid redeem script length'
from ..proto.btc.common import hash160
return self.proto.pubhash2addr(
hash160( bytes.fromhex(redeem_script_hex) ),
p2sh = True )
return self.proto.pubhash2addr(hash160(bytes.fromhex(redeem_script_hex)), p2sh=True)
def pubhash2addr(self,pubhashhex:'sstr'):
"convert public key hash to address"
pubhash = bytes.fromhex(pubhashhex)
if self.mmtype.name == 'segwit':
return self.proto.pubhash2segwitaddr( pubhash )
return self.proto.pubhash2segwitaddr(pubhash)
elif self.mmtype.name == 'bech32':
return self.proto.pubhash2bech32addr( pubhash )
return self.proto.pubhash2bech32addr(pubhash)
else:
return self.proto.pubhash2addr( pubhash, self.mmtype.addr_fmt=='p2sh' )
return self.proto.pubhash2addr(pubhash, self.mmtype.addr_fmt=='p2sh')
def addr2pubhash(self,addr:'sstr'):
"convert coin address to public key hash"

View file

@ -62,13 +62,13 @@ class CmdTestMisc(CmdTestBase):
tmpdir_nums = [99]
passthru_opts = ('daemon_data_dir','rpc_port')
cmd_group = (
('rpc_backends', 'RPC backends'),
('xmrwallet_txview', "'mmgen-xmrwallet' txview"),
('xmrwallet_txlist', "'mmgen-xmrwallet' txlist"),
('coin_daemon_info', "'examples/coin-daemon-info.py'"),
('examples_bip_hd', "'examples/bip_hd.py'"),
('term_echo', "term.set('echo')"),
('term_cleanup', 'term.register_cleanup()'),
('rpc_backends', 'RPC backends'),
('xmrwallet_txview', "'mmgen-xmrwallet' txview"),
('xmrwallet_txlist', "'mmgen-xmrwallet' txlist"),
('coin_daemon_info', "'examples/coin-daemon-info.py'"),
('examples_bip_hd', "'examples/bip_hd.py'"),
('term_echo', "term.set('echo')"),
('term_cleanup', 'term.register_cleanup()'),
)
need_daemon = True
color = True

View file

@ -392,17 +392,17 @@ class CmdTestRef3Addr(CmdTestRef3Seed):
def refkeyaddrgen_bech32(self):
return self.call_addrgen('bech32','keyaddr')
def pwgen(self,ftype,id_str,pwfmt=None,pwlen=None,extra_args=[],stdout=False):
def pwgen(self, ftype, id_str, pwfmt=None, pwlen=None, extra_args=[], stdout=False):
wf = self.get_file_with_ext('mmdat')
pwfmt = (['--passwd-fmt='+pwfmt] if pwfmt else [])
pwlen = (['--passwd-len='+str(pwlen)] if pwlen else [])
return self.addrgen(
wf,
check_ref = True,
ftype = ftype,
id_str = id_str,
extra_args = pwfmt + pwlen + extra_args,
stdout = stdout)
wf,
check_ref = True,
ftype = ftype,
id_str = id_str,
extra_args = pwfmt + pwlen + extra_args,
stdout = stdout)
def refpasswdgen(self):
return self.pwgen('pass','alice@crypto.org')

View file

@ -164,7 +164,7 @@ def make_burn_addr(proto):
cfg = cfg,
cmdname = 'pubhash2addr',
proto = proto,
mmtype = 'compressed' ).pubhash2addr('00'*20)
mmtype = 'compressed').pubhash2addr('00'*20)
class CmdTestRegtest(CmdTestBase,CmdTestShared):
'transacting and tracking wallet operations via regtest mode'
@ -718,7 +718,14 @@ class CmdTestRegtest(CmdTestBase,CmdTestShared):
def fund_alice(self):
return self.fund_wallet('alice',('L','S')[self.proto.cap('segwit')],rtFundAmt)
def user_twview(self, user, chk=None, expect=None, cmdline=['twview'], sort='age', exit_val=None):
def user_twview(
self,
user,
chk = None,
expect = None,
cmdline = ['twview'],
sort = 'age',
exit_val = None):
t = self.spawn('mmgen-tool',[f'--{user}'] + cmdline + ['sort='+sort], exit_val=exit_val)
if chk:
t.expect(r'{}\b.*\D{}\b'.format(*chk),regex=True)
@ -739,7 +746,7 @@ class CmdTestRegtest(CmdTestBase,CmdTestShared):
return self.user_twview('bob', cmdline=['listaddresses'], expect='TOTAL:')
def bob_twview1(self):
return self.user_twview('bob', chk = ('1',rtAmts[0]) )
return self.user_twview('bob', chk=('1', rtAmts[0]))
def user_bal(self,user,bal,args=['showempty=1'],skip_check=False):
t = self.spawn('mmgen-tool',['--'+user,'listaddresses'] + args)

View file

@ -240,7 +240,7 @@ class CmdTestShared:
t.expect(['Passphrase is OK', 'Passphrase.* are correct'],regex=True)
chk = t.expect_getend(f'Valid {wcls.desc} for Seed ID ')[:8]
if sid:
cmp_or_die(chk,sid)
cmp_or_die(chk, sid)
return t
def addrgen(
@ -285,7 +285,7 @@ class CmdTestShared:
def keyaddrgen(self,wf,check_ref=False,mmtype=None):
if not mmtype:
mmtype = self.segwit_mmtype
args = ['-d',self.tmpdir,self.usr_rand_arg,wf,self.addr_idx_list]
args = ['-d', self.tmpdir, self.usr_rand_arg, wf, self.addr_idx_list]
t = self.spawn('mmgen-keygen',
([],['--type='+str(mmtype)])[bool(mmtype)] + args,
extra_desc=f'({mmtype})' if mmtype in ('segwit','bech32') else '')

View file

@ -59,14 +59,14 @@ from test.include.common import set_globals,init_coverage,end_msg,green
set_globals(cfg)
td = namedtuple('scrambletest_entry',['seed','str','id_str','lbl','addr'])
td = namedtuple('scrambletest_entry', ['seed', 'str', 'id_str', 'lbl', 'addr'])
bitcoin_data = {
# SCRAMBLED_SEED[:8] SCRAMBLE_KEY ID_STR LBL FIRST ADDR
'btc': td('456d7f5f1c4bfe3b','(none)', '', '', '1MU7EdgqYy9JX35L25hR6CmXXcSEBDAwyv'),
'btc_compressed':td('bf98a4af5464a4ef','compressed', '-C', 'COMPRESSED', '1F97Jd89wwmu4ELadesAdGDzg3d8Y6j5iP'),
'btc_segwit': td('b56962d829ffc678','segwit', '-S', 'SEGWIT', '36TvVzU5mxSjJ3D9qKAmYzCV7iUqtTDezF'),
'btc_bech32': td('d09eea818f9ad17f','bech32', '-B', 'BECH32', 'bc1q8snv94j6959y3gkqv4gku0cm5mersnpucsvw5z'),
# SCRAMBLED_SEED[:8] SCRAMBLE_KEY ID_STR LBL FIRST ADDR
'btc': td('456d7f5f1c4bfe3b','(none)', '', '', '1MU7EdgqYy9JX35L25hR6CmXXcSEBDAwyv'),
'btc_compressed':td('bf98a4af5464a4ef','compressed', '-C', 'COMPRESSED','1F97Jd89wwmu4ELadesAdGDzg3d8Y6j5iP'),
'btc_segwit': td('b56962d829ffc678','segwit', '-S', 'SEGWIT', '36TvVzU5mxSjJ3D9qKAmYzCV7iUqtTDezF'),
'btc_bech32': td('d09eea818f9ad17f','bech32', '-B', 'BECH32', 'bc1q8snv94j6959y3gkqv4gku0cm5mersnpucsvw5z'),
}
altcoin_data = {