Skip to content

Commit

Permalink
ecc: API changes: verify_message_hash to return bool instead of raising
Browse files Browse the repository at this point in the history
verify_message_hash and verify_message_for_address now return bool
instead of raising Exceptions on bad signatures.
  • Loading branch information
SomberNight committed Feb 16, 2022
1 parent 57583c0 commit 4f9e4c5
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 47 deletions.
69 changes: 33 additions & 36 deletions electrum/ecc.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ def from_sig_string(cls, sig_string: bytes, recid: int, msg_hash: bytes) -> 'ECP
assert_bytes(sig_string)
if len(sig_string) != 64:
raise Exception(f'wrong encoding used for signature? len={len(sig_string)} (should be 64)')
if recid < 0 or recid > 3:
if not (0 <= recid <= 3):
raise ValueError('recid is {}, but should be 0 <= recid <= 3'.format(recid))
sig65 = create_string_buffer(65)
ret = _libsecp256k1.secp256k1_ecdsa_recoverable_signature_parse_compact(
Expand All @@ -177,7 +177,7 @@ def from_signature65(cls, sig: bytes, msg_hash: bytes) -> Tuple['ECPubkey', bool
if len(sig) != 65:
raise Exception(f'wrong encoding used for signature? len={len(sig)} (should be 65)')
nV = sig[0]
if nV < 27 or nV >= 35:
if not (27 <= nV <= 34):
raise Exception("Bad encoding")
if nV >= 31:
compressed = True
Expand Down Expand Up @@ -290,33 +290,36 @@ def __lt__(self, other):
raise TypeError('comparison not defined for ECPubkey and {}'.format(type(other)))
return (self.x() or 0) < (other.x() or 0)

def verify_message_for_address(self, sig65: bytes, message: bytes, algo=lambda x: sha256d(msg_magic(x))) -> None:
def verify_message_for_address(self, sig65: bytes, message: bytes, algo=lambda x: sha256d(msg_magic(x))) -> bool:
assert_bytes(message)
h = algo(message)
public_key, compressed = self.from_signature65(sig65, h)
try:
public_key, compressed = self.from_signature65(sig65, h)
except Exception:
return False
# check public key
if public_key != self:
raise Exception("Bad signature")
return False
# check message
self.verify_message_hash(sig65[1:], h)
return self.verify_message_hash(sig65[1:], h)

# TODO return bool instead of raising
def verify_message_hash(self, sig_string: bytes, msg_hash: bytes) -> None:
def verify_message_hash(self, sig_string: bytes, msg_hash: bytes) -> bool:
assert_bytes(sig_string)
if len(sig_string) != 64:
raise Exception(f'wrong encoding used for signature? len={len(sig_string)} (should be 64)')
return False
if not (isinstance(msg_hash, bytes) and len(msg_hash) == 32):
raise Exception("msg_hash must be bytes, and 32 bytes exactly")
return False

sig = create_string_buffer(64)
ret = _libsecp256k1.secp256k1_ecdsa_signature_parse_compact(_libsecp256k1.ctx, sig, sig_string)
if not ret:
raise Exception("Bad signature")
return False
ret = _libsecp256k1.secp256k1_ecdsa_signature_normalize(_libsecp256k1.ctx, sig, sig)

pubkey = self._to_libsecp256k1_pubkey_ptr()
if 1 != _libsecp256k1.secp256k1_ecdsa_verify(_libsecp256k1.ctx, sig, msg_hash, pubkey):
raise Exception("Bad signature")
return False
return True

def encrypt_message(self, message: bytes, magic: bytes = b'BIE1') -> bytes:
"""
Expand Down Expand Up @@ -364,33 +367,28 @@ def msg_magic(message: bytes) -> bytes:


def verify_signature(pubkey: bytes, sig: bytes, h: bytes) -> bool:
try:
ECPubkey(pubkey).verify_message_hash(sig, h)
except:
return False
return True
return ECPubkey(pubkey).verify_message_hash(sig, h)


def verify_message_with_address(address: str, sig65: bytes, message: bytes, *, net=None):
def verify_message_with_address(address: str, sig65: bytes, message: bytes, *, net=None) -> bool:
from .bitcoin import pubkey_to_address
assert_bytes(sig65, message)
if net is None: net = constants.net
h = sha256d(msg_magic(message))
try:
h = sha256d(msg_magic(message))
public_key, compressed = ECPubkey.from_signature65(sig65, h)
# check public key using the address
pubkey_hex = public_key.get_public_key_hex(compressed)
for txin_type in ['p2pkh','p2wpkh','p2wpkh-p2sh']:
addr = pubkey_to_address(txin_type, pubkey_hex, net=net)
if address == addr:
break
else:
raise Exception("Bad signature")
# check message
public_key.verify_message_hash(sig65[1:], h)
return True
except Exception as e:
_logger.info(f"Verification error: {repr(e)}")
return False
# check public key using the address
pubkey_hex = public_key.get_public_key_hex(compressed)
for txin_type in ['p2pkh','p2wpkh','p2wpkh-p2sh']:
addr = pubkey_to_address(txin_type, pubkey_hex, net=net)
if address == addr:
break
else:
return False
# check message
return public_key.verify_message_hash(sig65[1:], h)


def is_secret_within_curve_range(secret: Union[int, bytes]) -> bool:
Expand Down Expand Up @@ -476,7 +474,8 @@ def sign_with_extra_entropy(extra_entropy):
r, s = sign_with_extra_entropy(extra_entropy=extra_entropy)

sig_string = sig_string_from_r_and_s(r, s)
self.verify_message_hash(sig_string, msg_hash)
if not self.verify_message_hash(sig_string, msg_hash):
raise Exception("sanity check failed: signature we just created does not verify!")

sig = sigencode(r, s)
return sig
Expand All @@ -488,11 +487,9 @@ def sign_message(self, message: bytes, is_compressed: bool, algo=lambda x: sha25
def bruteforce_recid(sig_string):
for recid in range(4):
sig65 = construct_sig65(sig_string, recid, is_compressed)
try:
self.verify_message_for_address(sig65, message, algo)
return sig65, recid
except Exception as e:
if not self.verify_message_for_address(sig65, message, algo):
continue
return sig65, recid
else:
raise Exception("error: cannot sign message. no recid fits..")

Expand Down
3 changes: 2 additions & 1 deletion electrum/lnaddr.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,8 @@ def lndecode(invoice: str, *, verbose=False, net=None) -> LnAddr:
#
# A reader MUST use the `n` field to validate the signature instead of
# performing signature recovery if a valid `n` field is provided.
ecc.ECPubkey(addr.pubkey).verify_message_hash(sigdecoded[:64], hrp_hash)
if not ecc.ECPubkey(addr.pubkey).verify_message_hash(sigdecoded[:64], hrp_hash):
raise LnDecodeException("bad signature")
pubkey_copy = addr.pubkey
class WrappedBytesKey:
serialize = lambda: pubkey_copy
Expand Down
6 changes: 1 addition & 5 deletions electrum/plugins/coldcard/coldcard.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,7 @@ def mitm_verify(self, sig, expect_xpub):
# verify a signature (65 bytes) over the session key, using the master bip32 node
# - customized to use specific EC library of Electrum.
pubkey = BIP32Node.from_xkey(expect_xpub).eckey
try:
pubkey.verify_message_hash(sig[1:65], self.session_key)
return True
except:
return False
return pubkey.verify_message_hash(sig[1:65], self.session_key)

except ImportError as e:
if not (isinstance(e, ModuleNotFoundError) and e.name == 'ckcc'):
Expand Down
2 changes: 1 addition & 1 deletion electrum/tests/test_bitcoin.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def _do_test_crypto(self, message):

signature = eck.sign_message(message, True)
#print signature
eck.verify_message_for_address(signature, message)
self.assertTrue(eck.verify_message_for_address(signature, message))

def test_ecc_sanity(self):
G = ecc.GENERATOR
Expand Down
5 changes: 1 addition & 4 deletions electrum/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -2025,10 +2025,7 @@ def update_signatures(self, signatures: Sequence[str]):
continue
pubkey_hex = public_key.get_public_key_hex(compressed=True)
if pubkey_hex in pubkeys:
try:
public_key.verify_message_hash(sig_string, pre_hash)
except Exception:
_logger.exception('')
if not public_key.verify_message_hash(sig_string, pre_hash):
continue
_logger.info(f"adding sig: txin_idx={i}, signing_pubkey={pubkey_hex}, sig={sig}")
self.add_signature_to_txin(txin_idx=i, signing_pubkey=pubkey_hex, sig=sig)
Expand Down

0 comments on commit 4f9e4c5

Please sign in to comment.