transaction: support all sighash types in legacy preimage
What changed, and why it matters
This commit expands Electrum's transaction-signing code to correctly handle several Bitcoin 'sighash' modes that were previously unsupported for old-style (legacy) inputs. Sighash flags tell the network which parts of a transaction the signature covers. Before this change, legacy inputs using SIGHASH_NONE, SIGHASH_SINGLE, or SIGHASH_ANYONECANPAY would fail. The patch also adds a 'strict' option: by default it rejects unusual sighash bytes (matching normal network policy), but with strict=False it accepts any byte the Bitcoin consensus rules allow. It includes tests that compare Electrum's output against Bitcoin Core's official sighash test vectors. There is no indication in the commit that this fixes an active security vulnerability; it appears to be a correctness and compatibility improvement.
Review as a normal correctness/compatibility improvement. No urgent security response is indicated by the commit itself. If Electrum is used to sign or verify non-standard legacy transactions, ensure callers set strict=False where consensus behavior is required, and keep strict=True for standard wallet operations.
Security signals we found
Correctness fix for legacy sighash preimage construction
Adds strict parameter to distinguish policy-standardness from consensus-validity
Handles SIGHASH_SINGLE without corresponding output (legacy consensus quirk)
Adds test vectors from Bitcoin Core to prevent regression
No mention of vulnerability, CVE, bug bounty, or security advisory in commit
Evidence from the diff
The change updates serialize_preimage in electrum/transaction.py to implement legacy sighash behavior for SIGHASH_NONE, SIGHASH_SINGLE, and SIGHASH_ANYONECANPAY, including the consensus quirk where SIGHASH_SINGLE without a matching output hashes to 1. It adds a strict parameter: when True (default), undefined legacy sighash bytes are rejected as non-standard; when False, any consensus-valid legacy sighash byte is accepted. Taproot inputs remain strictly validated regardless of strict. verify_sig_for_txin also gains the strict parameter and handles the SIGHASH_SINGLE-no-output case. serialize_to_network now accepts an optional nsequence override so the preimage can zero out sequence numbers for NONE/SINGLE. New unit tests cover Bitcoin Core’s legacy sighash vectors and the SIGHASH_SINGLE edge case.
Changed components
electrum/transaction.pytests/test_transaction.pytests/sighash-vectors.jsonInspect captured patch +590 / −12
### electrum/transaction.py
@@ -443,15 +443,22 @@ def to_json(self):
d['witness'] = [x.hex() for x in self.witness_elements()]
return d
- def serialize_to_network(self, *, script_sig: bytes | None = None) -> bytes:
+ def serialize_to_network(
+ self,
+ *,
+ script_sig: bytes | None = None,
+ nsequence: int | None = None,
+ ) -> bytes:
if script_sig is None:
script_sig = self.script_sig
+ if nsequence is None:
+ nsequence = self.nsequence
# Prev hash and index
s = self.prevout.serialize_to_network()
# Script length, script, sequence
s += var_int(len(script_sig))
s += script_sig
- s += int.to_bytes(self.nsequence, length=4, byteorder="little", signed=False)
+ s += int.to_bytes(nsequence, length=4, byteorder="little", signed=False)
return s
def witness_elements(self) -> Sequence[bytes]:
@@ -1057,6 +1064,7 @@ def serialize_preimage(
*,
sighash: Optional[int] = None,
sighash_cache: SighashCache | None = None,
+ strict: bool = True, # enforce policy/standardness
) -> bytes:
nVersion = int.to_bytes(self.version, length=4, byteorder="little", signed=True)
nLocktime = int.to_bytes(self.locktime, length=4, byteorder="little", signed=False)
@@ -1069,7 +1077,9 @@ def serialize_preimage(
if sighash is None:
sighash = Sighash.DEFAULT if txin.is_taproot() else Sighash.ALL
assert sighash is not None
- if not Sighash.is_valid(sighash, is_taproot=txin.is_taproot()):
+ if (strict or txin.is_taproot()) and not Sighash.is_valid(sighash, is_taproot=txin.is_taproot()):
+ # Undefined sighashes for legacy and segwit are non-standard but consensus-valid.
+ # Undefined sighashes for taproot are invalid by consensus.
raise Exception(f"SIGHASH_FLAG ({sighash}) not supported!")
if sighash_cache is None:
sighash_cache = SighashCache()
@@ -1137,13 +1147,28 @@ def serialize_preimage(
preimage = nVersion + hashPrevouts + hashSequence + outpoint + scriptCode + amount + nSequence + hashOutputs + nLocktime + nHashType
return preimage
else: # legacy sighash (pre-segwit)
- if sighash != Sighash.ALL:
- raise Exception(f"SIGHASH_FLAG ({sighash}) not supported! (for legacy sighash)")
+ # see https://github.com/bitcoin/bitcoin/blob/f86c614e69256b9814c27b0dd096ee46daa71aa3/src/script/interpreter.cpp#L1338
+ base_sighash = sighash & 0x1f
+ if base_sighash == Sighash.SINGLE and txin_index >= len(outputs):
+ raise Exception("Using SIGHASH_SINGLE without a corresponding output")
preimage_script = txin.get_scriptcode_for_sighash()
- txins = var_int(len(inputs)) + b"".join(
- txin.serialize_to_network(script_sig=preimage_script if txin_index==k else b"")
- for k, txin in enumerate(inputs))
- txouts = var_int(len(outputs)) + b"".join(o.serialize_to_network() for o in outputs)
+ def serialize_txin(k: int, txin_k: TxInput) -> bytes:
+ if k == txin_index:
+ return txin_k.serialize_to_network(script_sig=preimage_script)
+ else:
+ nsequence = 0 if base_sighash in (Sighash.NONE, Sighash.SINGLE) else txin_k.nsequence
+ return txin_k.serialize_to_network(script_sig=b"", nsequence=nsequence)
+ if sighash & Sighash.ANYONECANPAY:
+ txins = var_int(1) + serialize_txin(txin_index, txin)
+ else:
+ txins = var_int(len(inputs)) + b"".join(serialize_txin(k, txin_k) for k, txin_k in enumerate(inputs))
+ if base_sighash == Sighash.NONE:
+ txouts = var_int(0)
+ elif base_sighash == Sighash.SINGLE:
+ blank_txout = int.to_bytes(2**64 - 1, length=8, byteorder="little", signed=False) + var_int(0)
+ txouts = var_int(txin_index + 1) + blank_txout * txin_index + outputs[txin_index].serialize_to_network()
+ else:
+ txouts = var_int(len(outputs)) + b"".join(o.serialize_to_network() for o in outputs)
nHashType = int.to_bytes(sighash, length=4, byteorder="little", signed=False)
preimage = nVersion + txins + txouts + nLocktime + nHashType
return preimage
@@ -1156,15 +1181,20 @@ def verify_sig_for_txin(
pubkey_bytes: bytes,
sig: bytes,
sighash_cache: SighashCache | None = None,
+ strict: bool = True, # enforce policy/standardness
) -> bool:
txin = self.inputs()[txin_index]
if txin.is_taproot():
raise Exception("not implemented") # TODO
else:
der_sig, sighash = sig[:-1], sig[-1]
- pre_hash = self.serialize_preimage(txin_index, sighash=sighash, sighash_cache=sighash_cache)
+ if not txin.is_segwit() and sighash & 0x1f == Sighash.SINGLE and txin_index >= len(self.outputs()):
+ msg_hash = (1).to_bytes(32, byteorder="little") # legacy consensus quirk
+ else:
+ pre_hash = self.serialize_preimage(
+ txin_index, sighash=sighash, sighash_cache=sighash_cache, strict=strict)
+ msg_hash = sha256d(pre_hash)
pubkey = ecc.ECPubkey(pubkey_bytes)
- msg_hash = sha256d(pre_hash)
sig64 = ecc.ecdsa_sig64_from_der_sig(der_sig)
return pubkey.ecdsa_verify(sig64, msg_hash)
### tests/sighash-vectors.json
[binary or diff unavailable]
### tests/test_transaction.py
@@ -2,7 +2,7 @@
import os
from typing import NamedTuple, Union
-from electrum_ecc import ECPrivkey
+from electrum_ecc import ECPrivkey, ecdsa_der_sig_from_r_and_s
from electrum import transaction, bitcoin
from electrum.transaction import (convert_raw_tx_to_hex, tx_from_any, Transaction,
@@ -11,6 +11,7 @@
SCRIPTPUBKEY_TEMPLATE_ANYSEGWIT, TxOutput, script_GetOp,
MalformedBitcoinScript)
from electrum.util import bfh
+from electrum.crypto import sha256d
from electrum.bitcoin import (deserialize_privkey, opcodes,
construct_script, construct_witness)
from electrum import descriptor
@@ -1147,6 +1148,50 @@ def test_check_sighash_types_sighash_single_anyonecanpay(self):
sig.hex())
+class TestSighashLegacy(ElectrumTestCase):
+
+ def test_bitcoin_core_vectors(self):
+ # file identical to https://github.com/bitcoin/bitcoin/blob/v27.0/src/test/data/sighash.json
+ test_vector_file = os.path.join(os.path.dirname(__file__), "sighash-vectors.json")
+ with open(test_vector_file, "r") as f:
+ vectors = [v for v in json.load(f)]
+ vectors = vectors[1:] # drop header
+ self.assertEqual(500, len(vectors))
+ for raw_tx, script, txin_index, hash_type, expected_sighash in vectors:
+ with self.subTest(raw_tx=raw_tx, txin_index=txin_index, hash_type=hash_type):
+ tx = PartialTransaction.from_tx(Transaction(raw_tx))
+ txin = tx.inputs()[txin_index]
+ self.assertFalse(txin.is_segwit())
+ # legacy sighash removes OP_CODESEPARATOR from the scriptCode
+ script = bfh(script)
+ script_code = b""
+ start = 0
+ for op, _, end in script_GetOp(script):
+ if op != opcodes.OP_CODESEPARATOR:
+ script_code += script[start:end]
+ start = end
+ txin.get_scriptcode_for_sighash = lambda script_code=script_code: script_code
+ pre_hash = tx.serialize_preimage(txin_index, sighash=hash_type & 0xffffffff, strict=False)
+ self.assertEqual(expected_sighash, sha256d(pre_hash)[::-1].hex())
+
+ def test_verify_sighash_single_without_output(self):
+ # legacy SIGHASH_SINGLE signs the hash 1 if there is no output with the index of the input
+ privkey = ECPrivkey(bfh('730fff80e1413068a05b57d6a58261f07551163369787f349438ea38ca80fac6'))
+ pubkey = privkey.get_public_key_bytes(compressed=True)
+ txins = [PartialTxInput(prevout=TxOutpoint(txid=bytes([i]) * 32, out_idx=0)) for i in range(2)]
+ for txin in txins:
+ txin.script_descriptor = descriptor.get_singlesig_descriptor_from_legacy_leaf(
+ pubkey=pubkey.hex(), script_type='p2pkh')
+ txout = PartialTxOutput(scriptpubkey=bfh('76a914389ffce9cd9ae88dcc0631e88a821ffdbe9bfe2688ac'), value=1000)
+ tx = PartialTransaction.from_io(inputs=txins, outputs=[txout], locktime=0, version=1, BIP69_sort=False)
+ msg_hash = (1).to_bytes(32, byteorder="little")
+ sig = privkey.ecdsa_sign(msg_hash, sigencode=ecdsa_der_sig_from_r_and_s) + bytes([Sighash.SINGLE])
+ self.assertTrue(tx.verify_sig_for_txin(txin_index=1, pubkey_bytes=pubkey, sig=sig))
+ self.assertFalse(tx.verify_sig_for_txin(txin_index=0, pubkey_bytes=pubkey, sig=sig))
+ with self.assertRaisesRegex(Exception, "without a corresponding output"):
+ tx.serialize_preimage(1, sighash=Sighash.SINGLE)
+
+
class TestSighashBIP341(ElectrumTestCase):
def test_taproot_keypath_spending(self):Why this scored 30/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.