commit 76e67daadd658eb647669bd8e595c0f72cc93086
parent cf88e239d7e5d8d690aae0742f6daafb3fe0eb45
Author: SomberNight <somber.night@protonmail.com>
Date: Sat, 7 Apr 2018 17:01:38 +0200
changed some asserts to raise-exceptions in lib
Diffstat:
5 files changed, 34 insertions(+), 15 deletions(-)
diff --git a/lib/bitcoin.py b/lib/bitcoin.py
@@ -143,7 +143,8 @@ def rev_hex(s):
def int_to_hex(i, length=1):
- assert isinstance(i, int)
+ if not isinstance(i, int):
+ raise TypeError('{} instead of int'.format(i))
if i < 0:
# two's complement
i = pow(256, length) + i
@@ -342,7 +343,8 @@ def address_to_script(addr, *, net=None):
net = constants.net
witver, witprog = segwit_addr.decode(net.SEGWIT_HRP, addr)
if witprog is not None:
- assert (0 <= witver <= 16)
+ if not (0 <= witver <= 16):
+ raise BitcoinException('impossible witness version: {}'.format(witver))
OP_n = witver + 0x50 if witver > 0 else 0
script = bh2u(bytes([OP_n]))
script += push_script(bh2u(bytes(witprog)))
@@ -383,7 +385,8 @@ assert len(__b43chars) == 43
def base_encode(v, base):
""" encode v, which is a string of bytes, to base58."""
assert_bytes(v)
- assert base in (58, 43)
+ if base not in (58, 43):
+ raise ValueError('not supported base: {}'.format(base))
chars = __b58chars
if base == 43:
chars = __b43chars
@@ -413,7 +416,8 @@ def base_decode(v, length, base):
""" decode v into a string of len bytes."""
# assert_bytes(v)
v = to_bytes(v, 'ascii')
- assert base in (58, 43)
+ if base not in (58, 43):
+ raise ValueError('not supported base: {}'.format(base))
chars = __b58chars
if base == 43:
chars = __b43chars
@@ -497,7 +501,8 @@ def deserialize_privkey(key):
txin_type = None
if ':' in key:
txin_type, key = key.split(sep=':', maxsplit=1)
- assert txin_type in SCRIPT_TYPES
+ if txin_type not in SCRIPT_TYPES:
+ raise BitcoinException('unknown script type: {}'.format(txin_type))
try:
vch = DecodeBase58Check(key)
except BaseException:
@@ -509,9 +514,12 @@ def deserialize_privkey(key):
# keys exported in version 3.0.x encoded script type in first byte
txin_type = inv_dict(SCRIPT_TYPES)[vch[0] - constants.net.WIF_PREFIX]
else:
- assert vch[0] == constants.net.WIF_PREFIX
+ # all other keys must have a fixed first byte
+ if vch[0] != constants.net.WIF_PREFIX:
+ raise BitcoinException('invalid prefix ({}) for WIF key'.format(vch[0]))
- assert len(vch) in [33, 34]
+ if len(vch) not in [33, 34]:
+ raise BitcoinException('invalid vch len for WIF key: {}'.format(len(vch)))
compressed = len(vch) == 34
return txin_type, vch[1:33], compressed
@@ -963,7 +971,8 @@ def xpub_from_pubkey(xtype, cK):
def bip32_derivation(s):
- assert s.startswith('m/')
+ if not s.startswith('m/'):
+ raise ValueError('invalid bip32 derivation path: {}'.format(s))
s = s[2:]
for n in s.split('/'):
if n == '': continue
@@ -978,7 +987,9 @@ def is_bip32_derivation(x):
return False
def bip32_private_derivation(xprv, branch, sequence):
- assert sequence.startswith(branch)
+ if not sequence.startswith(branch):
+ raise ValueError('incompatible branch ({}) and sequence ({})'
+ .format(branch, sequence))
if branch == sequence:
return xprv, xpub_from_xprv(xprv)
xtype, depth, fingerprint, child_number, c, k = deserialize_xprv(xprv)
@@ -1000,7 +1011,9 @@ def bip32_private_derivation(xprv, branch, sequence):
def bip32_public_derivation(xpub, branch, sequence):
xtype, depth, fingerprint, child_number, c, cK = deserialize_xpub(xpub)
- assert sequence.startswith(branch)
+ if not sequence.startswith(branch):
+ raise ValueError('incompatible branch ({}) and sequence ({})'
+ .format(branch, sequence))
sequence = sequence[len(branch):]
for n in sequence.split('/'):
if n == '': continue
diff --git a/lib/mnemonic.py b/lib/mnemonic.py
@@ -173,7 +173,8 @@ class Mnemonic(object):
nonce += 1
i = entropy + nonce
seed = self.mnemonic_encode(i)
- assert i == self.mnemonic_decode(seed)
+ if i != self.mnemonic_decode(seed):
+ raise Exception('Cannot extract same entropy from mnemonic!')
if is_old_seed(seed):
continue
if is_new_seed(seed, prefix):
diff --git a/lib/network.py b/lib/network.py
@@ -140,7 +140,8 @@ def deserialize_proxy(s):
def deserialize_server(server_str):
host, port, protocol = str(server_str).rsplit(':', 2)
- assert protocol in 'st'
+ if protocol not in 'st':
+ raise ValueError('invalid network protocol: {}'.format(protocol))
int(port) # Throw if cannot be converted to int
return host, port, protocol
diff --git a/lib/storage.py b/lib/storage.py
@@ -480,7 +480,9 @@ class WalletStorage(PrintError):
def convert_version_15(self):
if not self._is_upgrade_method_needed(14, 14):
return
- assert self.get('seed_type') != 'segwit' # unsupported derivation
+ if self.get('seed_type') == 'segwit':
+ # should not get here; get_seed_version should have caught this
+ raise Exception('unsupported derivation (development segwit, v14)')
self.put('seed_version', 15)
def convert_version_16(self):
diff --git a/lib/transaction.py b/lib/transaction.py
@@ -538,7 +538,8 @@ def deserialize(raw):
is_segwit = (n_vin == 0)
if is_segwit:
marker = vds.read_bytes(1)
- assert marker == b'\x01'
+ if marker != b'\x01':
+ raise ValueError('invalid txn marker byte: {}'.format(marker))
n_vin = vds.read_compact_size()
d['inputs'] = [parse_input(vds) for i in range(n_vin)]
n_vout = vds.read_compact_size()
@@ -1032,7 +1033,8 @@ class Transaction:
private_key = bitcoin.MySigningKey.from_secret_exponent(secexp, curve = SECP256k1)
public_key = private_key.get_verifying_key()
sig = private_key.sign_digest_deterministic(pre_hash, hashfunc=hashlib.sha256, sigencode = ecdsa.util.sigencode_der)
- assert public_key.verify_digest(sig, pre_hash, sigdecode = ecdsa.util.sigdecode_der)
+ if not public_key.verify_digest(sig, pre_hash, sigdecode = ecdsa.util.sigdecode_der):
+ raise Exception('Sanity check verifying our own signature failed.')
txin['signatures'][j] = bh2u(sig) + '01'
#txin['x_pubkeys'][j] = pubkey
txin['pubkeys'][j] = pubkey # needed for fd keys