handle MMGen exceptions via die()

- exception module is imported only after an error occurs
This commit is contained in:
The MMGen Project 2022-02-05 13:32:56 +00:00
commit aad252a077
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
50 changed files with 143 additions and 169 deletions

View file

@ -17,7 +17,7 @@ from collections import namedtuple
import mmgen.tx.base as TxBase
from ....opts import opt
from ....obj import MMGenObject,MMGenList,HexStr
from ....util import msg,dmsg,make_chksum_6
from ....util import msg,dmsg,make_chksum_6,die
def addr2pubhash(proto,addr):
ap = proto.parse_addr(addr)
@ -100,7 +100,7 @@ def DeserializeTX(proto,txhex):
if has_witness:
u = bshift(2,skip=True).hex()
if u != '0001':
raise IllegalWitnessFlagValue(f'{u!r}: Illegal value for flag in transaction!')
die( 'IllegalWitnessFlagValue', f'{u!r}: Illegal value for flag in transaction!' )
d['num_txins'] = readVInt()
@ -140,7 +140,7 @@ def DeserializeTX(proto,txhex):
d['witness_size'] = 0
if len(tx) - var.idx != 4:
raise TxHexParseError('TX hex has invalid length: {} extra bytes'.format(len(tx)-var.idx-4))
die( 'TxHexParseError', 'TX hex has invalid length: {} extra bytes'.format(len(tx)-var.idx-4) )
d['locktime'] = bytes2int(bshift(4))
d['unsigned_hex'] = var.raw_tx.hex()
@ -283,8 +283,7 @@ class Base(TxBase.Base):
"""
def do_error(errmsg):
from ....exception import TxHexMismatch
raise TxHexMismatch(errmsg+'\n'+hdr)
die( 'TxHexMismatch', errmsg+'\n'+hdr )
def check_equal(desc,hexio,mmio):
if mmio != hexio:

View file

@ -16,7 +16,7 @@ import mmgen.tx.new as TxBase
from .base import Base
from ....opts import opt
from ....obj import HexStr,MMGenTxID
from ....util import dmsg,vmsg,make_chksum_6
from ....util import dmsg,vmsg,make_chksum_6,die
class New(Base,TxBase.New):
usr_fee_prompt = 'Enter transaction fee: '
@ -98,7 +98,7 @@ class New(Base,TxBase.New):
fee = self.sum_inputs() - self.sum_outputs()
if fee > self.proto.max_tx_fee:
c = self.proto.coin
raise MaxFeeExceeded(f'Transaction fee of {fee} {c} too high! (> {self.proto.max_tx_fee} {c})')
die( 'MaxFeeExceeded', f'Transaction fee of {fee} {c} too high! (> {self.proto.max_tx_fee} {c})' )
def final_inputs_ok_msg(self,funds_left):
return 'Transaction produces {} {} in change'.format(

View file

@ -14,7 +14,7 @@ base_proto.bitcoin.tx.signed: Bitcoin signed transaction class
import mmgen.tx.signed as TxBase
from .completed import Completed
from ....util import fmt,vmsg
from ....util import fmt,vmsg,die
class Signed(Completed,TxBase.Signed):
@ -25,8 +25,7 @@ class Signed(Completed,TxBase.Signed):
vmsg(f'\nVsize: {vsize} (true) {est_vsize} (estimated)')
ratio = float(est_vsize) / vsize
if not (0.95 < ratio < 1.05): # allow for 5% error
from ....exception import BadTxSizeEstimate
raise BadTxSizeEstimate(fmt(f"""
die( 'BadTxSizeEstimate', fmt(f"""
Estimated transaction vsize is {ratio:1.2f} times the true vsize
Your transaction fee estimates will be inaccurate
Please re-create and re-sign the transaction using the option --vsize-adj={1/ratio:1.2f}

View file

@ -73,7 +73,7 @@ class Unsigned(Completed,TxBase.Unsigned):
new.compare_size_and_estimated_size(tx_decoded)
new.coin_txid = CoinTxID(self.deserialized.txid)
if not new.coin_txid == tx_decoded['txid']:
raise BadMMGenTxID('txid mismatch (after signing)')
die( 'BadMMGenTxID', 'txid mismatch (after signing)' )
msg('OK')
return new
except Exception as e:

View file

@ -174,5 +174,5 @@ class TokenResolve(TokenCommon,metaclass=AsyncInit):
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')
die( 'TokenNotInBlockchain', f'Token {addr!r} not in blockchain' )
Token.__init__(self,proto,addr,decimals,rpc)

View file

@ -20,7 +20,7 @@
altcoins.base_proto.ethereum.twctl: Ethereum tracking wallet control class
"""
from ...util import msg,ymsg,write_mode
from ...util import msg,ymsg,write_mode,die
from ...twctl import TrackingWallet
from ...addr import is_coin_addr,is_mmgen_id
from ...amt import ETHAmt
@ -160,13 +160,12 @@ class EthereumTokenTrackingWallet(EthereumTrackingWallet):
if self.importing and token_addr:
if not is_coin_addr(proto,token_addr):
raise InvalidTokenAddress(f'{token_addr!r}: invalid token address')
die( '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):
from ...exception import UnrecognizedTokenSymbol
raise UnrecognizedTokenSymbol(f'Specified token {proto.tokensym!r} could not be resolved!')
die( 'UnrecognizedTokenSymbol', f'Specified token {proto.tokensym!r} could not be resolved!' )
from ...addr import TokenAddr
self.token = TokenAddr(proto,token_addr)
@ -175,7 +174,7 @@ class EthereumTokenTrackingWallet(EthereumTrackingWallet):
if self.importing:
await self.import_token(self.token)
else:
raise TokenNotInWallet(f'Specified token {self.token!r} not in wallet!')
die( 'TokenNotInWallet', f'Specified token {self.token!r} not in wallet!' )
self.decimals = self.get_param('decimals')
self.symbol = self.get_param('symbol')

View file

@ -139,10 +139,10 @@ class New(Base,TxBase.New):
ret.append(waddr)
break
else:
raise UserAddressNotInWallet(errmsg.format(addr))
die( 'UserAddressNotInWallet', errmsg.format(addr) )
elif is_coin_addr(self.proto,addr):
if not addr in data_root:
raise UserAddressNotInWallet(errmsg.format(addr))
die( 'UserAddressNotInWallet', errmsg.format(addr) )
ret.append(addr)
else:
die(1,f'{addr!r}: not an MMGen ID or coin address')

View file

@ -22,7 +22,6 @@ baseconv.py: base conversion class for the MMGen suite
from collections import namedtuple
from .exception import BaseConversionError,BaseConversionPadError,HexadecimalStringError,SeedLengthError
from .util import die
def is_b58_str(s):
@ -123,7 +122,7 @@ class baseconv(object):
elif pad == 'seed':
return seed_pad_func()
else:
raise BaseConversionPadError(f"{pad!r}: illegal value for 'pad' (must be None,'seed' or int)")
die('BaseConversionPadError',f"{pad!r}: illegal value for 'pad' (must be None,'seed' or int)")
def tohex(self,words_arg,pad=None):
"convert string or list data of instance base to hex string"
@ -136,13 +135,13 @@ class baseconv(object):
desc = self.desc.short
if len(words) == 0:
raise BaseConversionError(f'empty {desc} data')
die('BaseConversionError',f'empty {desc} data')
def get_seed_pad():
assert hasattr(self,'seedlen_map_rev'), f'seed padding not supported for base {self.wl_id!r}'
d = self.seedlen_map_rev
if not len(words) in d:
raise BaseConversionError(
die( 'BaseConversionError',
f'{len(words)}: invalid length for seed-padded {desc} data in base conversion' )
return d[len(words)]
@ -151,7 +150,7 @@ class baseconv(object):
base = len(wl)
if not set(words) <= set(wl):
raise BaseConversionError(
die( 'BaseConversionError',
( 'seed data' if pad == 'seed' else f'{words_arg!r}:' ) +
f' not in {desc} format' )
@ -164,7 +163,7 @@ class baseconv(object):
from .util import is_hex_str
if not is_hex_str(hexstr):
raise HexadecimalStringError(
die( 'HexadecimalStringError',
( 'seed data' if pad == 'seed' else f'{hexstr!r}:' ) +
' not a hexadecimal string' )
@ -174,13 +173,13 @@ class baseconv(object):
"convert byte string to list or string data of instance base"
if not bytestr:
raise BaseConversionError('empty data not allowed in base conversion')
die( 'BaseConversionError', 'empty data not allowed in base conversion' )
def get_seed_pad():
assert hasattr(self,'seedlen_map'), f'seed padding not supported for base {self.wl_id!r}'
d = self.seedlen_map
if not len(bytestr) in d:
raise SeedLengthError(
die( 'SeedLengthError',
f'{len(bytestr)}: invalid byte length for seed data in seed-padded base conversion' )
return d[len(bytestr)]

View file

@ -22,9 +22,8 @@ bip39.py - Data and routines for BIP39 mnemonic seed phrases
from hashlib import sha256
from .exception import MnemonicError
from .baseconv import baseconv
from .util import is_hex_str
from .util import is_hex_str,die
def is_bip39_str(s):
return bool( bip39().tohex(s.split()) )
@ -59,7 +58,7 @@ class bip39(baseconv):
for k,v in cls.constants.items():
if v.mn_len == nwords:
return k//8 if in_bytes else k//4 if in_hex else k
raise MnemonicError(f'{nwords!r}: invalid word length for BIP39 mnemonic')
die( 'MnemonicError', f'{nwords!r}: invalid word length for BIP39 mnemonic' )
@classmethod
def seedlen2nwords(cls,seed_len,in_bytes=False,in_hex=False):
@ -83,7 +82,7 @@ class bip39(baseconv):
for n,w in enumerate(words):
if w not in wl:
raise MnemonicError(f'word #{n+1} is not in the BIP39 word list')
die( 'MnemonicError', f'word #{n+1} is not in the BIP39 word list' )
res = ''.join(['{:011b}'.format(wl.index(w)) for w in words])
@ -92,7 +91,7 @@ class bip39(baseconv):
bitlen = k
break
else:
raise MnemonicError(f'{len(words)}: invalid BIP39 seed phrase length')
die( 'MnemonicError', f'{len(words)}: invalid BIP39 seed phrase length' )
seed_bin = res[:bitlen]
chk_bin = res[bitlen:]
@ -105,7 +104,7 @@ class bip39(baseconv):
chk_bin_chk = '{:0{w}b}'.format(int(chk_hex_chk,16),w=256)[:chk_len]
if chk_bin != chk_bin_chk:
raise MnemonicError('invalid BIP39 seed phrase checksum')
die( 'MnemonicError', 'invalid BIP39 seed phrase checksum' )
return seed_hex

View file

@ -28,7 +28,6 @@ import sys,os,re
from collections import namedtuple
from .globalvars import *
from .exception import CfgFileParseError
from .util import *
def cfg_file(id_str):
@ -92,7 +91,7 @@ class CfgFile(object):
if m:
yield self.line_data(m[1],m[3],lineno,None)
else:
raise CfgFileParseError(f'Parse error in file {self.fn!r}, line {lineno}')
die( 'CfgFileParseError', f'Parse error in file {self.fn!r}, line {lineno}' )
return gen_lines()
@classmethod
@ -135,7 +134,7 @@ class CfgFileSample(CfgFile):
if m:
return self.line_data(m[2],m[4],lineno,chunk)
else:
raise CfgFileParseError(f'Parse error in file {self.fn!r}, line {lineno}')
die( 'CfgFileParseError', f'Parse error in file {self.fn!r}, line {lineno}' )
def gen_chunks(lines):
hdr = True
@ -163,7 +162,7 @@ class CfgFileSample(CfgFile):
chunk.append(line)
last_nonblank = lineno
else:
raise CfgFileParseError(f'Parse error in file {self.fn!r}, line {lineno}')
die( 'CfgFileParseError', f'Parse error in file {self.fn!r}, line {lineno}' )
if chunk:
yield process_chunk(chunk,last_nonblank)

View file

@ -80,8 +80,7 @@ class Daemon(Lockable):
try:
cp = run(cmd,check=False,stdout=out,stderr=out)
except Exception as e:
from .exception import MMGenCalledProcessError
raise MMGenCalledProcessError(f'Error starting executable: {type(e).__name__} [Errno {e.errno}]')
die( 'MMGenCalledProcessError', f'Error starting executable: {type(e).__name__} [Errno {e.errno}]' )
if self.debug:
print(cp)
return cp

View file

@ -54,16 +54,14 @@ class Filename(MMGenObject):
if base_class:
subclass = base_class.ext_to_type(self.ext,proto)
if not subclass:
from .exception import BadFileExtension
raise BadFileExtension(f'{self.ext!r}: not a recognized file extension for {base_class}')
die( 'BadFileExtension', f'{self.ext!r}: not a recognized file extension for {base_class}' )
self.subclass = subclass
try:
st = os.stat(fn)
except:
from .exception import FileNotFound
raise FileNotFound(f'{fn!r}: file not found')
die( 'FileNotFound', f'{fn!r}: file not found' )
import stat
if stat.S_ISBLK(st.st_mode):

View file

@ -89,8 +89,7 @@ def _check_file_type_and_access(fname,ftype,blkdev_ok=False):
try:
mode = os.stat(fname).st_mode
except:
from .exception import FileNotFound
raise FileNotFound(f'Requested {ftype} {fname!r} not found')
die( 'FileNotFound', f'Requested {ftype} {fname!r} not found' )
for t in ok_types:
if t[0](mode):
@ -289,8 +288,8 @@ def get_data_from_file(infile,desc='data',dash=False,silent=False,binary=False,q
data = data.decode()
if len(data) == g.max_input_size + 1:
from .exception import MaxInputSizeExceeded
raise MaxInputSizeExceeded(f'Too much input data! Max input data size: {f.max_input_size} bytes')
die( 'MaxInputSizeExceeded',
f'Too much input data! Max input data size: {f.max_input_size} bytes' )
return data

View file

@ -20,9 +20,8 @@
flags.py: Class flags and opts for the MMGen suite
"""
from .exception import ClassFlagsError
from .base_obj import AttrCtrl,Lockable
from .util import fmt_list
from .util import fmt_list,die
class ClassFlags(AttrCtrl):
_name = 'flags'
@ -35,10 +34,10 @@ class ClassFlags(AttrCtrl):
for a in self._available:
if a.startswith('_'):
raise ClassFlagsError(f'{a!r}: {self._desc} cannot begin with an underscore')
die( 'ClassFlagsError', f'{a!r}: {self._desc} cannot begin with an underscore' )
for b in self.reserved_attrs:
if a == b:
raise ClassFlagsError(f'{a!r}: {b} is a reserved name for {self._desc}')
die( 'ClassFlagsError', f'{a!r}: {b} is a reserved name for {self._desc}' )
if arg:
assert type(arg) in (list,tuple), f"{arg!r}: {self._name!r} must be list or tuple"
@ -69,14 +68,14 @@ class ClassFlags(AttrCtrl):
assert type(val) is bool, f'{val!r} not boolean'
old_val = getattr(self,name)
if val and old_val:
raise ClassFlagsError(f'{self._desc} {name!r} already set')
die( 'ClassFlagsError', f'{self._desc} {name!r} already set' )
if not val and not old_val:
raise ClassFlagsError(f'{self._desc} {name!r} not set, so cannot be unset')
die( 'ClassFlagsError', f'{self._desc} {name!r} not set, so cannot be unset' )
super().__setattr__(name,val)
def not_available_error(self,name):
raise ClassFlagsError('{!r}: unrecognized {} for {}: (available {}: {})'.format(
die( 'ClassFlagsError', '{!r}: unrecognized {} for {}: (available {}: {})'.format(
name,
self._desc,
type(self._parent).__name__,

View file

@ -83,9 +83,9 @@ class PrivKey(bytes,Hilite,InitErrors,MMGenObject):
me.wif = str.__new__(WifKey,wif) # check has been done
me.orig_bytes = None
if k.sec != proto.preprocess_key(k.sec,k.pubkey_type):
from .exception import PrivateKeyError
raise PrivateKeyError(
f'{proto.cls_name} WIF key {me.wif!r} encodes private key with invalid value {me}')
from .util import die
die( 'PrivateKeyError',
f'{proto.cls_name} WIF key {me.wif!r} encodes private key with invalid value {me}' )
me.proto = proto
return me
except Exception as e:

View file

@ -64,8 +64,9 @@ class keygen_backend:
try:
from .secp256k1 import priv2pub
if not priv2pub(bytes.fromhex('deadbeef'*8),1):
from .exception import ExtensionModuleError
raise ExtensionModuleError('Unable to execute priv2pub() from secp256k1 extension module')
from .util import die
die( 'ExtensionModuleError',
'Unable to execute priv2pub() from secp256k1 extension module' )
return True
except Exception as e:
if not silent:

View file

@ -69,8 +69,8 @@ class LEDControl:
except: pass
else: break
else:
from mmgen.exception import NoLEDSupport
raise NoLEDSupport('Control files not found! LED control not supported on this system')
from .util import die
die( 'NoLEDSupport', 'Control files not found! LED control not supported on this system' )
msg(f'{board.name} board detected')
@ -89,6 +89,7 @@ class LEDControl:
fp.write(f'{init_val}\n')
return True
except PermissionError:
from .util import die
die(2,'\n'+fmt(f"""
You do not have access to the {desc} file
To allow access, run the following command:

View file

@ -57,6 +57,7 @@ def launch(mod):
_o = namedtuple('exit_data',['color','exit_val','fs'])
d = {
0: _o(nocolor, 1, '{message}'),
1: _o(nocolor, 1, '{message}'),
2: _o(yellow, 2, '{message}'),
3: _o(yellow, 3, '\nMMGen Error ({name}): {message}'),

View file

@ -215,7 +215,7 @@ def process_args(cmd,cmd_args,cls):
# If we're reading from a pipe, replace '-' with output of previous command
if flag == 'STDIN_OK' and u_args and u_args[0] == '-':
if sys.stdin.isatty():
raise BadFilename("Standard input is a TTY. Can't use '-' as a filename")
die( 'BadFilename', "Standard input is a TTY. Can't use '-' as a filename" )
else:
max_dlen_spec = '10kB' # limit input to 10KB for now
max_dlen = parse_bytespec(max_dlen_spec)

View file

@ -23,7 +23,6 @@ obj.py: MMGen native classes
import sys,os,re,unicodedata
from .objmethods import *
from .exception import BadTwComment
def get_obj(objname,*args,**kwargs):
"""
@ -378,7 +377,7 @@ class MMGenWalletLabel(MMGenLabel):
class TwComment(MMGenLabel):
max_screen_width = 80
desc = 'tracking wallet comment'
exc = BadTwComment
exc = 'BadTwComment'
class MMGenTxLabel(MMGenLabel):
max_len = 72

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