From bdf405d661b1b5ca2251faaf53fc9c16385d3652 Mon Sep 17 00:00:00 2001 From: notTanveer Date: Mon, 11 May 2026 15:47:53 +0530 Subject: [PATCH 1/8] psbt: add PSBTv2 per-input locktime fields and version-aware scope parsing - Add LOCKTIME_THRESHOLD constant (500000000) for locktime type discrimination - Add required_time_locktime and required_height_locktime fields to InputScope - Propagate those fields in InputScope.update() - Parse PSBT_IN_REQUIRED_TIME_LOCKTIME (0x11) and PSBT_IN_REQUIRED_HEIGHT_LOCKTIME (0x12) in InputScope.read_value(), with range validation - Serialize 0x11 and 0x12 in InputScope.write_to() under the version==2 block - Add version=None parameter to InputScope.read_value() and OutputScope.read_value() so callers can signal the PSBT version being parsed - Add InputScope.read_from() and OutputScope.read_from() classmethods that accept and forward the version parameter (supersede PSBTScope base classmethod for v2) - Propagate version in LInputScope.read_value() and LOutputScope.read_value() (pset.py) so the Liquid subclasses stay compatible - Pass version=self.version when PSBTView calls read_from() for input/output scopes so PSBTv2 scopes are parsed with the correct version context --- src/embit/liquid/pset.py | 8 ++-- src/embit/psbt.py | 89 ++++++++++++++++++++++++++++++++++++++-- src/embit/psbtview.py | 8 +++- 3 files changed, 96 insertions(+), 9 deletions(-) diff --git a/src/embit/liquid/pset.py b/src/embit/liquid/pset.py index 290c59ac..2a916ca0 100644 --- a/src/embit/liquid/pset.py +++ b/src/embit/liquid/pset.py @@ -140,10 +140,10 @@ def blinded_vin(self): witness=TxInWitness(self.issue_rangeproof, self.token_rangeproof), ) - def read_value(self, stream, k): + def read_value(self, stream, k, version=None): # standard bitcoin stuff if (b"\xfc\x08elements" not in k) and (b"\xfc\x04pset" not in k): - super().read_value(stream, k) + super().read_value(stream, k, version=version) elif k == b"\xfc\x04pset\x0e": # range proof is very large, # so we don't load it if compress flag is set. @@ -386,9 +386,9 @@ def reblind(self, nonce, blinding_pubkey=None, extra_message=b""): secp256k1.generator_parse(self.asset_commitment), ) - def read_value(self, stream, k): + def read_value(self, stream, k, version=None): if (b"\xfc\x08elements" not in k) and (b"\xfc\x04pset" not in k): - super().read_value(stream, k) + super().read_value(stream, k, version=version) # range proof and surjection proof are very large, # so we don't load them if compress flag is set. elif k in [b"\xfc\x08elements\x04", b"\xfc\x04pset\x04"]: diff --git a/src/embit/psbt.py b/src/embit/psbt.py index d20c88bb..306dab09 100644 --- a/src/embit/psbt.py +++ b/src/embit/psbt.py @@ -12,6 +12,9 @@ from io import BytesIO +LOCKTIME_THRESHOLD = 500000000 + + class PSBTError(EmbitError): pass @@ -89,7 +92,7 @@ def parse_unknowns(self): s.seek(0) self.read_value(s, k) - def read_value(self, stream, key, *args, **kwargs): + def read_value(self, stream, key, version=None): # separator if len(key) == 0: return @@ -148,6 +151,8 @@ def __init__(self, unknown: dict = {}, vin=None, compress=CompressMode.KEEP_ALL) self.final_scriptsig = None self.final_scriptwitness = None + self.required_time_locktime = None + self.required_height_locktime = None self.parse_unknowns() def clear_metadata(self, compress=CompressMode.CLEAR_ALL): @@ -193,6 +198,16 @@ def update(self, other): self.taproot_scripts.update(other.taproot_scripts) self.final_scriptsig = other.final_scriptsig or self.final_scriptsig self.final_scriptwitness = other.final_scriptwitness or self.final_scriptwitness + self.required_time_locktime = ( + other.required_time_locktime + if other.required_time_locktime is not None + else self.required_time_locktime + ) + self.required_height_locktime = ( + other.required_height_locktime + if other.required_height_locktime is not None + else self.required_height_locktime + ) @property def vin(self): @@ -245,7 +260,7 @@ def verify(self, ignore_missing=False): raise PSBTError("Missing non_witness_utxo") return False - def read_value(self, stream, k): + def read_value(self, stream, k, version=None): # separator if len(k) == 0: return @@ -345,6 +360,7 @@ def read_value(self, stream, k): else: raise PSBTError("Duplicated final scriptwitness") + # PSBTv2 fields elif k == b"\x0e": self.txid = bytes(reversed(v)) elif k == b"\x0f": @@ -352,6 +368,36 @@ def read_value(self, stream, k): elif k == b"\x10": self.sequence = int.from_bytes(v, "little") + # PSBT_IN_REQUIRED_TIME_LOCKTIME + elif k[0] == 0x11: + if version != 2: + raise PSBTError("PSBT_IN_REQUIRED_TIME_LOCKTIME not allowed in PSBTv0") + if len(k) != 1: + raise PSBTError("Invalid required time locktime key") + if self.required_time_locktime is not None: + raise PSBTError("Duplicated required time locktime") + locktime = int.from_bytes(v, "little") + if locktime < LOCKTIME_THRESHOLD: + raise PSBTError(f"Time-based locktime must be >= {LOCKTIME_THRESHOLD}") + self.required_time_locktime = locktime + + # PSBT_IN_REQUIRED_HEIGHT_LOCKTIME + elif k[0] == 0x12: + if version != 2: + raise PSBTError( + "PSBT_IN_REQUIRED_HEIGHT_LOCKTIME not allowed in PSBTv0" + ) + if len(k) != 1: + raise PSBTError("Invalid required height locktime key") + if self.required_height_locktime is not None: + raise PSBTError("Duplicated required height locktime") + locktime = int.from_bytes(v, "little") + if locktime >= LOCKTIME_THRESHOLD or locktime == 0: + raise PSBTError( + f"Height-based locktime must be > 0 and < {LOCKTIME_THRESHOLD}" + ) + self.required_height_locktime = locktime + # PSBT_IN_TAP_KEY_SIG elif k[0] == 0x13: # read the taproot key sig @@ -444,6 +490,20 @@ def write_to(self, stream, skip_separator=False, version=None, **kwargs) -> int: r += ser_string(stream, b"\x10") r += ser_string(stream, self.sequence.to_bytes(4, "little")) + # Add required time locktime if present + if self.required_time_locktime is not None: + r += ser_string(stream, b"\x11") + r += ser_string( + stream, self.required_time_locktime.to_bytes(4, "little") + ) + + # Add required height locktime if present + if self.required_height_locktime is not None: + r += ser_string(stream, b"\x12") + r += ser_string( + stream, self.required_height_locktime.to_bytes(4, "little") + ) + # PSBT_IN_TAP_KEY_SIG if self.taproot_key_sig is not None: r += ser_string(stream, b"\x13") @@ -489,6 +549,17 @@ def write_to(self, stream, skip_separator=False, version=None, **kwargs) -> int: r += stream.write(b"\x00") return r + @classmethod + def read_from(cls, stream, compress=CompressMode.KEEP_ALL, vin=None, version=None): + res = cls({}, vin=vin, compress=compress) + while True: + key = read_string(stream) + # separator + if len(key) == 0: + break + res.read_value(stream, key, version=version) + return res + class OutputScope(PSBTScope): def __init__(self, unknown: dict = {}, vout=None, compress=CompressMode.KEEP_ALL): @@ -531,7 +602,7 @@ def update(self, other): def vout(self): return TransactionOutput(self.value, self.script_pubkey) - def read_value(self, stream, k): + def read_value(self, stream, k, version=None): # separator if len(k) == 0: return @@ -562,6 +633,7 @@ def read_value(self, stream, k): else: self.bip32_derivations[pub] = DerivationPath.parse(v) + # PSBTv2 fields elif k == b"\x03": self.value = int.from_bytes(v, "little") elif k == b"\x04": @@ -633,6 +705,17 @@ def write_to(self, stream, skip_separator=False, version=None, **kwargs) -> int: r += stream.write(b"\x00") return r + @classmethod + def read_from(cls, stream, compress=CompressMode.KEEP_ALL, vout=None, version=None): + res = cls({}, vout=vout, compress=compress) + while True: + key = read_string(stream) + # separator + if len(key) == 0: + break + res.read_value(stream, key, version=version) + return res + class PSBT(EmbitBase): MAGIC = b"psbt\xff" diff --git a/src/embit/psbtview.py b/src/embit/psbtview.py index c66bcb5b..75b35e28 100644 --- a/src/embit/psbtview.py +++ b/src/embit/psbtview.py @@ -313,7 +313,9 @@ def input(self, i, compress=None): raise PSBTError("Invalid input index") vin = self.tx.vin(i) if self.tx else None self.seek_to_scope(i) - return self.PSBTIN_CLS.read_from(self.stream, vin=vin, compress=compress) + return self.PSBTIN_CLS.read_from( + self.stream, vin=vin, compress=compress, version=self.version + ) def output(self, i, compress=None): """Reads, parses and returns PSBT OutputScope #i""" @@ -323,7 +325,9 @@ def output(self, i, compress=None): raise PSBTError("Invalid output index") vout = self.tx.vout(i) if self.tx else None self.seek_to_scope(self.num_inputs + i) - return self.PSBTOUT_CLS.read_from(self.stream, vout=vout, compress=compress) + return self.PSBTOUT_CLS.read_from( + self.stream, vout=vout, compress=compress, version=self.version + ) # compress is not used here, but may be used by subclasses (liquid) def vin(self, i, compress=None): From 5ad265abc449fc920d34f06bb04f43b4104496bd Mon Sep 17 00:00:00 2001 From: notTanveer Date: Mon, 11 May 2026 15:56:31 +0530 Subject: [PATCH 2/8] psbt: implement PSBTv2 global parsing and serialization - Add TxModifiable class with INPUTS/OUTPUTS/SIGHASH_SINGLE bit flags - Add PSBT._validate_v2_output() classmethod to check required PSBTv2 output fields; PSET overrides it to allow value_commitment in place of value - Add tx_modifiable_flags field to PSBT.__init__() (None for v0/unset) - Update comment on self.version to note '2 for v2' - Add PSBT.determine_locktime(): implements BIP-370 locktime selection algorithm (height vs time preference, max-of-minimums) - Update PSBT.tx property to call determine_locktime() for PSBTv2 - Update PSBT.write_to(): serialize PSBT_GLOBAL_TX_MODIFIABLE (0x06) when set - Rewrite PSBT.read_from(): collect all global KVs into OrderedDict before branching on PSBTv2 vs PSBTv0; detect version from 0xfb; reject unsigned tx in PSBTv2 and reject v2-only keys in PSBTv0; validate required fields after parsing; call read_from with version=version on all scopes - Rewrite PSBT.parse_unknowns(): strip 0xfb/0x06; guard 0x02/0x03/0x04/0x05 behind version==2; track _raw_input_count_from_global and _raw_output_count_from_global for PSBTv2 scope parsing - Add version guards to InputScope.read_value() for 0x0e/0x0f/0x10: PSBT_IN_PREVIOUS_TXID, PSBT_IN_OUTPUT_INDEX, and PSBT_IN_SEQUENCE are rejected when version != 2 - Add version guards to OutputScope.read_value() for 0x03/0x04: PSBT_OUT_AMOUNT and PSBT_OUT_SCRIPT are rejected when version != 2 --- src/embit/liquid/pset.py | 12 ++ src/embit/psbt.py | 404 +++++++++++++++++++++++++++++++++------ 2 files changed, 353 insertions(+), 63 deletions(-) diff --git a/src/embit/liquid/pset.py b/src/embit/liquid/pset.py index 2a916ca0..b613ba95 100644 --- a/src/embit/liquid/pset.py +++ b/src/embit/liquid/pset.py @@ -503,6 +503,18 @@ class PSET(PSBT): PSBTOUT_CLS = LOutputScope TX_CLS = LTransaction + @classmethod + def _validate_v2_output(cls, out, i): + """PSET allows value_commitment as an alternative to value (blinded outputs).""" + if out.value is None and not getattr(out, "value_commitment", None): + raise PSBTError( + f"PSBTv2 output {i} missing required PSBT_OUT_AMOUNT (0x03)" + ) + if out.script_pubkey is None: + raise PSBTError( + f"PSBTv2 output {i} missing required PSBT_OUT_SCRIPT (0x04)" + ) + def unblind(self, blinding_key): for inp in self.inputs: inp.unblind(blinding_key) diff --git a/src/embit/psbt.py b/src/embit/psbt.py index 306dab09..cc25f093 100644 --- a/src/embit/psbt.py +++ b/src/embit/psbt.py @@ -272,9 +272,17 @@ def read_value(self, stream, k, version=None): raise PSBTError("Duplicated utxo value") else: l = compact.read_from(stream) + # For PSBTv2, PSBT_IN_OUTPUT_INDEX may follow PSBT_IN_NON_WITNESS_UTXO; + # use the pre-scanned vout (set by read_from) when the field hasn't + # been parsed yet so the OOM protection is key-order independent. + effective_vout = ( + self.vout + if self.vout is not None + else getattr(self, "_prescan_vout", None) + ) # we verified and saved utxo - if self.compress and self.txid and self.vout is not None: - txout, txhash = self.TX_CLS.read_vout(stream, self.vout) + if self.compress and self.txid and effective_vout is not None: + txout, txhash = self.TX_CLS.read_vout(stream, effective_vout) self._txhash = txhash self._utxo = txout else: @@ -362,35 +370,53 @@ def read_value(self, stream, k, version=None): # PSBTv2 fields elif k == b"\x0e": + if version != 2: + raise PSBTError("PSBT_IN_PREVIOUS_TXID not allowed in PSBTv0") + if len(v) != 32: + raise PSBTError("PSBT_IN_PREVIOUS_TXID must be 32 bytes") + if self.txid is not None: + raise PSBTError("Duplicated PSBT_IN_PREVIOUS_TXID") self.txid = bytes(reversed(v)) elif k == b"\x0f": + if version != 2: + raise PSBTError("PSBT_IN_OUTPUT_INDEX not allowed in PSBTv0") + if len(v) != 4: + raise PSBTError("PSBT_IN_OUTPUT_INDEX must be 4 bytes") + if self.vout is not None: + raise PSBTError("Duplicated PSBT_IN_OUTPUT_INDEX") self.vout = int.from_bytes(v, "little") elif k == b"\x10": + if version != 2: + raise PSBTError("PSBT_IN_SEQUENCE not allowed in PSBTv0") + if len(v) != 4: + raise PSBTError("PSBT_IN_SEQUENCE must be 4 bytes") + if self.sequence is not None: + raise PSBTError("Duplicated PSBT_IN_SEQUENCE") self.sequence = int.from_bytes(v, "little") # PSBT_IN_REQUIRED_TIME_LOCKTIME - elif k[0] == 0x11: + elif k == b"\x11": if version != 2: raise PSBTError("PSBT_IN_REQUIRED_TIME_LOCKTIME not allowed in PSBTv0") - if len(k) != 1: - raise PSBTError("Invalid required time locktime key") if self.required_time_locktime is not None: raise PSBTError("Duplicated required time locktime") + if len(v) != 4: + raise PSBTError("PSBT_IN_REQUIRED_TIME_LOCKTIME must be 4 bytes") locktime = int.from_bytes(v, "little") if locktime < LOCKTIME_THRESHOLD: raise PSBTError(f"Time-based locktime must be >= {LOCKTIME_THRESHOLD}") self.required_time_locktime = locktime # PSBT_IN_REQUIRED_HEIGHT_LOCKTIME - elif k[0] == 0x12: + elif k == b"\x12": if version != 2: raise PSBTError( "PSBT_IN_REQUIRED_HEIGHT_LOCKTIME not allowed in PSBTv0" ) - if len(k) != 1: - raise PSBTError("Invalid required height locktime key") if self.required_height_locktime is not None: raise PSBTError("Duplicated required height locktime") + if len(v) != 4: + raise PSBTError("PSBT_IN_REQUIRED_HEIGHT_LOCKTIME must be 4 bytes") locktime = int.from_bytes(v, "little") if locktime >= LOCKTIME_THRESHOLD or locktime == 0: raise PSBTError( @@ -552,12 +578,31 @@ def write_to(self, stream, skip_separator=False, version=None, **kwargs) -> int: @classmethod def read_from(cls, stream, compress=CompressMode.KEEP_ALL, vin=None, version=None): res = cls({}, vin=vin, compress=compress) + # For PSBTv2 with compress mode, pre-scan for PSBT_IN_OUTPUT_INDEX so the + # non-witness UTXO memory optimisation works regardless of key order. + # (BIP370 does not guarantee that 0x0f appears before 0x00.) + res._prescan_vout = None + if version == 2 and compress and res.vout is None: + try: + start_pos = stream.tell() + while True: + k = read_string(stream) + if len(k) == 0: + break + v = read_string(stream) + if k == b"\x0f" and len(v) == 4: + res._prescan_vout = int.from_bytes(v, "little") + break + stream.seek(start_pos) + except (AttributeError, OSError): + pass # stream not seekable; OOM protection may be unavailable while True: key = read_string(stream) # separator if len(key) == 0: break res.read_value(stream, key, version=version) + del res._prescan_vout return res @@ -635,8 +680,18 @@ def read_value(self, stream, k, version=None): # PSBTv2 fields elif k == b"\x03": - self.value = int.from_bytes(v, "little") + if version != 2: + raise PSBTError("PSBT_OUT_AMOUNT not allowed in PSBTv0") + if len(v) != 8: + raise PSBTError("PSBT_OUT_AMOUNT must be 8 bytes") + if self.value is not None: + raise PSBTError("Duplicated PSBT_OUT_AMOUNT") + self.value = int.from_bytes(v, "little", signed=True) elif k == b"\x04": + if version != 2: + raise PSBTError("PSBT_OUT_SCRIPT not allowed in PSBTv0") + if self.script_pubkey is not None: + raise PSBTError("Duplicated PSBT_OUT_SCRIPT") self.script_pubkey = Script(v) # PSBT_OUT_TAP_INTERNAL_KEY @@ -675,7 +730,8 @@ def write_to(self, stream, skip_separator=False, version=None, **kwargs) -> int: if version == 2: if self.value is not None: r += ser_string(stream, b"\x03") - r += ser_string(stream, self.value.to_bytes(8, "little")) + # BIP370: PSBT_OUT_AMOUNT is a signed 64-bit integer + r += ser_string(stream, self.value.to_bytes(8, "little", signed=True)) if self.script_pubkey is not None: r += ser_string(stream, b"\x04") r += self.script_pubkey.write_to(stream) @@ -717,6 +773,12 @@ def read_from(cls, stream, compress=CompressMode.KEEP_ALL, vout=None, version=No return res +class TxModifiable: + INPUTS = 0b00000001 + OUTPUTS = 0b00000010 + SIGHASH_SINGLE = 0b00000100 + + class PSBT(EmbitBase): MAGIC = b"psbt\xff" # for subclasses @@ -724,17 +786,33 @@ class PSBT(EmbitBase): PSBTOUT_CLS = OutputScope TX_CLS = Transaction - def __init__(self, tx=None, unknown={}, version=None): - self.version = version # None for v0 + @classmethod + def _validate_v2_output(cls, out, i): + """Check that a PSBTv2 output has all required fields. + Subclasses (e.g. PSET) may override this to accept alternative fields.""" + if out.value is None: + raise PSBTError( + f"PSBTv2 output {i} missing required PSBT_OUT_AMOUNT (0x03)" + ) + if out.script_pubkey is None: + raise PSBTError( + f"PSBTv2 output {i} missing required PSBT_OUT_SCRIPT (0x04)" + ) + + def __init__(self, tx=None, unknown=None, version=None): + self.version = version # None for v0, 2 for v2 self.inputs = [] self.outputs = [] self.tx_version = None self.locktime = None + self.tx_modifiable_flags = None + self._raw_input_count_from_global = None + self._raw_output_count_from_global = None if tx is not None: self.parse_tx(tx) - self.unknown = unknown + self.unknown = {} if unknown is None else unknown self.xpubs = OrderedDict() self.parse_unknowns() @@ -744,11 +822,89 @@ def parse_tx(self, tx): self.inputs = [self.PSBTIN_CLS(vin=vin) for vin in tx.vin] self.outputs = [self.PSBTOUT_CLS(vout=vout) for vout in tx.vout] + @staticmethod + def _classify_locktimes(inputs): + """Classify inputs by locktime requirement type. + + Returns a tuple of (height_locktimes, time_locktimes, inputs_with_requirements) + where the lists contain the respective locktime values and the count is the + number of inputs that express at least one locktime requirement. + """ + height_locktimes = [] + time_locktimes = [] + inputs_with_requirements = 0 + for inp in inputs: + has_requirement = False + if inp.required_height_locktime is not None: + height_locktimes.append(inp.required_height_locktime) + has_requirement = True + if inp.required_time_locktime is not None: + time_locktimes.append(inp.required_time_locktime) + has_requirement = True + if has_requirement: + inputs_with_requirements += 1 + return height_locktimes, time_locktimes, inputs_with_requirements + + def determine_locktime(self): + """ + Determines the appropriate locktime according to PSBTv2 rules. + Returns the locktime that should be used for the transaction. + """ + if self.version != 2: + return self.locktime or 0 + + height_locktimes, time_locktimes, inputs_with_locktime_requirements = ( + self._classify_locktimes(self.inputs) + ) + + # If no inputs have locktime requirements, use fallback + if inputs_with_locktime_requirements == 0: + return self.locktime or 0 + + # height preferred, if ALL inputs with requirements support it + if len(height_locktimes) == inputs_with_locktime_requirements: + return max(height_locktimes) + + # fall back to time if ALL inputs with requirements support it + if len(time_locktimes) == inputs_with_locktime_requirements: + return max(time_locktimes) + + raise PSBTError( + "Cannot determine locktime: inputs have conflicting height and time locktime requirements" + ) + + def _validate_locktime_compatibility(self, inputs): + """Verify that the given input list has mutually compatible locktime requirements. + + Raises PSBTError when no single locktime type (height or time) is supported + by every input that expresses a requirement. + """ + height_locktimes, time_locktimes, inputs_with_requirements = ( + self._classify_locktimes(inputs) + ) + if inputs_with_requirements == 0: + return + if ( + len(height_locktimes) == inputs_with_requirements + or len(time_locktimes) == inputs_with_requirements + ): + return + raise PSBTError( + "Input locktime requirements are incompatible with existing inputs" + ) + @property def tx(self): + if self.version == 2: + locktime = self.determine_locktime() + else: + locktime = self.locktime or 0 + + if self.version == 2 and self.tx_version is None: + raise PSBTError("PSBTv2 is missing required PSBT_GLOBAL_TX_VERSION") return self.TX_CLS( version=self.tx_version or 2, - locktime=self.locktime or 0, + locktime=locktime, vin=[inp.vin for inp in self.inputs], vout=[out.vout for out in self.outputs], ) @@ -801,9 +957,13 @@ def write_to(self, stream) -> int: r += ser_string(stream, self.xpubs[xpub].serialize()) if self.version == 2: - if self.tx_version is not None: - r += ser_string(stream, b"\x02") - r += ser_string(stream, self.tx_version.to_bytes(4, "little")) + if self.tx_version is None: + raise PSBTError( + "Cannot serialize PSBTv2: missing required PSBT_GLOBAL_TX_VERSION" + ) + r += ser_string(stream, b"\x02") + # BIP370: PSBT_GLOBAL_TX_VERSION is a signed int32 + r += ser_string(stream, self.tx_version.to_bytes(4, "little", signed=True)) if self.locktime is not None: r += ser_string(stream, b"\x03") r += ser_string(stream, self.locktime.to_bytes(4, "little")) @@ -811,6 +971,9 @@ def write_to(self, stream) -> int: r += ser_string(stream, compact.to_bytes(len(self.inputs))) r += ser_string(stream, b"\x05") r += ser_string(stream, compact.to_bytes(len(self.outputs))) + if self.tx_modifiable_flags is not None: + r += ser_string(stream, b"\x06") + r += ser_string(stream, bytes([self.tx_modifiable_flags])) r += ser_string(stream, b"\xfb") r += ser_string(stream, self.version.to_bytes(4, "little")) # unknown @@ -855,72 +1018,187 @@ def read_from(cls, stream, compress=CompressMode.KEEP_ALL): without storing them in memory and save the utxo internally for signing. This helps against out-of-memory errors. """ - tx = None - unknown = {} - version = None - # check magic if stream.read(len(cls.MAGIC)) != cls.MAGIC: raise PSBTError("Invalid PSBT magic") + + global_kvs = OrderedDict() while True: key = read_string(stream) - # separator - if len(key) == 0: + if len(key) == 0: # Separator break value = read_string(stream) - # tx - if key == b"\x00": - if tx is None: - tx = cls.TX_CLS.parse(value) - else: + if key in global_kvs: + raise PSBTError(f"Duplicated global key: {hexlify(key).decode()}") + global_kvs[key] = value + + # Determine PSBT version from PSBT_GLOBAL_VERSION (0xfb) + version = None + if b"\xfb" in global_kvs: + if len(global_kvs[b"\xfb"]) != 4: + raise PSBTError("PSBT_GLOBAL_VERSION must be 4 bytes") + parsed_version = int.from_bytes(global_kvs[b"\xfb"], "little") + if parsed_version == 2: + version = 2 + elif parsed_version == 0: + version = ( + None # explicit PSBT_GLOBAL_VERSION=0 is valid for v0 per BIP174 + ) + else: + raise PSBTError( + f"Unsupported PSBT_GLOBAL_VERSION value: {parsed_version}" + ) + + if version == 2: # PSBTv2 + if b"\x00" in global_kvs: # PSBT_GLOBAL_UNSIGNED_TX + raise PSBTError("PSBT_GLOBAL_UNSIGNED_TX is not allowed in PSBTv2") + # Pass all global KVs to unknown; __init__ calls parse_unknowns. + psbt = cls(tx=None, unknown=global_kvs, version=version) + + # Validate that input/output counts were processed by parse_unknowns + if psbt._raw_input_count_from_global is None: + raise PSBTError( + "PSBTv2 missing or invalid PSBT_GLOBAL_INPUT_COUNT (0x04)" + ) + if psbt._raw_output_count_from_global is None: + raise PSBTError( + "PSBTv2 missing or invalid PSBT_GLOBAL_OUTPUT_COUNT (0x05)" + ) + if psbt.tx_version is None: + raise PSBTError("PSBTv2 missing required PSBT_GLOBAL_TX_VERSION (0x02)") + else: # PSBTv0 (version is None or 0) + if b"\x00" not in global_kvs: + raise PSBTError("PSBT_GLOBAL_UNSIGNED_TX (0x00) is required for PSBTv0") + + # Check for forbidden v2-only global keys in v0 context. + # PSBT_GLOBAL_VERSION (0xfb) with value 0 is explicitly permitted by BIP174 + # and was already validated above, so it is excluded from this set. + v2_only_global_keys = {b"\x02", b"\x03", b"\x04", b"\x05", b"\x06"} + for k_v2_only in v2_only_global_keys: + if k_v2_only in global_kvs: raise PSBTError( - "Failed to parse PSBT - duplicated transaction field" + f"Global key {hexlify(k_v2_only).decode()} is not allowed in PSBTv0" ) - elif key == b"\xfb": - version = int.from_bytes(value, "little") - else: - if key in unknown: - raise PSBTError("Duplicated key") - unknown[key] = value - - if tx and version == 2: - raise PSBTError("Global TX field is not allowed in PSBTv2") - psbt = cls(tx, unknown, version=version) - # input scopes - for i, vin in enumerate(psbt.tx.vin): - psbt.inputs[i] = cls.PSBTIN_CLS.read_from( - stream, compress=compress, vin=vin - ) - # output scopes - for i, vout in enumerate(psbt.tx.vout): - psbt.outputs[i] = cls.PSBTOUT_CLS.read_from( - stream, compress=compress, vout=vout - ) + + tx_bytes = global_kvs.pop(b"\x00") # Remove so it's not in unknown + tx_for_v0 = cls.TX_CLS.parse(tx_bytes) + psbt = cls(tx=tx_for_v0, unknown=global_kvs, version=version) + + if version == 2: + num_inputs = psbt._raw_input_count_from_global + num_outputs = psbt._raw_output_count_from_global + + parsed_inputs = [] + for _ in range(num_inputs): + parsed_inputs.append( + cls.PSBTIN_CLS.read_from( + stream, + compress=compress, + vin=None, + version=version, + ) + ) + psbt.inputs = parsed_inputs + + for i, inp in enumerate(psbt.inputs): + if inp.txid is None: + raise PSBTError( + f"PSBTv2 input {i} missing required PSBT_IN_PREVIOUS_TXID (0x0e)" + ) + if inp.vout is None: + raise PSBTError( + f"PSBTv2 input {i} missing required PSBT_IN_OUTPUT_INDEX (0x0f)" + ) + + parsed_outputs = [] + for _ in range(num_outputs): + parsed_outputs.append( + cls.PSBTOUT_CLS.read_from( + stream, + compress=compress, + vout=None, + version=version, + ) + ) + psbt.outputs = parsed_outputs + + for i, out in enumerate(psbt.outputs): + cls._validate_v2_output(out, i) + else: + temp_inputs = [] + for i in range(len(psbt.inputs)): + temp_inputs.append( + cls.PSBTIN_CLS.read_from( + stream, + compress=compress, + vin=psbt.inputs[i].vin, + version=version, + ) + ) + psbt.inputs = temp_inputs + + temp_outputs = [] + for i in range(len(psbt.outputs)): + temp_outputs.append( + cls.PSBTOUT_CLS.read_from( + stream, + compress=compress, + vout=psbt.outputs[i].vout, + version=version, + ) + ) + psbt.outputs = temp_outputs + return psbt def parse_unknowns(self): + # Handle PSBT_GLOBAL_VERSION first + if b"\xfb" in self.unknown: + self.unknown.pop(b"\xfb", None) + + if b"\x06" in self.unknown: + flags_bytes = self.unknown.pop(b"\x06") + if len(flags_bytes) != 1: + raise PSBTError("PSBT_GLOBAL_TX_MODIFIABLE must be 1 byte") + self.tx_modifiable_flags = flags_bytes[0] + for k in list(self.unknown): # xpub field if k[0] == 0x01: xpub = bip32.HDKey.parse(k[1:]) self.xpubs[xpub] = DerivationPath.parse(self.unknown.pop(k)) elif k == b"\x02": - self.tx_version = int.from_bytes(self.unknown.pop(k), "little") + if self.version == 2: + v = self.unknown.pop(k) + if len(v) != 4: + raise PSBTError("PSBT_GLOBAL_TX_VERSION must be 4 bytes") + # BIP370: PSBT_GLOBAL_TX_VERSION is a signed int32 + self.tx_version = int.from_bytes(v, "little", signed=True) elif k == b"\x03": - self.locktime = int.from_bytes(self.unknown.pop(k), "little") + if self.version == 2: + v = self.unknown.pop(k) + if len(v) != 4: + raise PSBTError("PSBT_GLOBAL_FALLBACK_LOCKTIME must be 4 bytes") + self.locktime = int.from_bytes(v, "little") elif k == b"\x04": - if len(self.inputs) > 0: - raise PSBTError("Inputs already initialized") - self.inputs = [ - self.PSBTIN_CLS() - for _ in range(compact.from_bytes(self.unknown.pop(k))) - ] + if self.version == 2: + if self._raw_input_count_from_global is not None: + self.unknown.pop(k, None) + continue + self._raw_input_count_from_global = compact.from_bytes( + self.unknown.pop(k) + ) + # Store count only; do not pre-allocate objects to avoid + # attacker-controlled memory exhaustion. elif k == b"\x05": - if len(self.outputs) > 0: - raise PSBTError("Outputs already initialized") - self.outputs = [ - self.PSBTOUT_CLS() - for _ in range(compact.from_bytes(self.unknown.pop(k))) - ] + if self.version == 2: + if self._raw_output_count_from_global is not None: + self.unknown.pop(k, None) + continue + self._raw_output_count_from_global = compact.from_bytes( + self.unknown.pop(k) + ) + # Store count only; do not pre-allocate objects to avoid + # attacker-controlled memory exhaustion. def sighash(self, i, sighash=SIGHASH.ALL, **kwargs): inp = self.inputs[i] From 676ff7a34c0d254407fb5333001e8c0f2a5d0703 Mon Sep 17 00:00:00 2001 From: notTanveer Date: Mon, 11 May 2026 15:58:06 +0530 Subject: [PATCH 3/8] psbt: add GLOBAL_TX_MODIFIABLE API, add_input/add_output, update sign_with - Update sign_with(): after each legacy/segwit signature, update tx_modifiable_flags per BIP-370: clear INPUTS bit if not ANYONECANPAY, clear OUTPUTS bit if not NONE, set SIGHASH_SINGLE bit if sighash type is SINGLE - Add get_tx_modifiable() / set_tx_modifiable(flags): getter/setter for PSBT_GLOBAL_TX_MODIFIABLE; setter raises PSBTError on PSBTv0 - Add is_inputs_modifiable(): True if version!=2, tx_modifiable_flags is None, or INPUTS bit is set - Add is_outputs_modifiable(): True if version!=2, tx_modifiable_flags is None, or OUTPUTS bit is set - Add has_sighash_single(): True only if version==2, tx_modifiable_flags is not None, and SIGHASH_SINGLE bit is set - Add add_input(input_scope): appends an InputScope, gated on is_inputs_modifiable(); updates _raw_input_count_from_global for PSBTv2 - Add add_output(output_scope): appends an OutputScope, gated on is_outputs_modifiable(); updates _raw_output_count_from_global for PSBTv2 --- src/embit/psbt.py | 117 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 111 insertions(+), 6 deletions(-) diff --git a/src/embit/psbt.py b/src/embit/psbt.py index cc25f093..5332d536 100644 --- a/src/embit/psbt.py +++ b/src/embit/psbt.py @@ -11,7 +11,6 @@ from binascii import b2a_base64, a2b_base64, hexlify, unhexlify from io import BytesIO - LOCKTIME_THRESHOLD = 500000000 @@ -1357,7 +1356,7 @@ def sign_with(self, root, sighash=SIGHASH.DEFAULT) -> int: if fingerprint: # if taproot derivations are present add them for pub in inp.taproot_bip32_derivations: - (_leafs, derivation) = inp.taproot_bip32_derivations[pub] + _leafs, derivation = inp.taproot_bip32_derivations[pub] if derivation.fingerprint == fingerprint: # Add only if not already present if (pub, derivation) not in bip32_derivations: @@ -1395,7 +1394,7 @@ def sign_with(self, root, sighash=SIGHASH.DEFAULT) -> int: if inp.is_taproot: # try to sign with individual private key (WIF) # or with root without derivations - counter += self.sign_input_with_tapkey( + tap_sigs = self.sign_input_with_tapkey( root, i, inp, @@ -1403,12 +1402,15 @@ def sign_with(self, root, sighash=SIGHASH.DEFAULT) -> int: ) # sign with all derived keys for prv, pub in derived_keypairs: - counter += self.sign_input_with_tapkey( + tap_sigs += self.sign_input_with_tapkey( prv, i, inp, sighash=inp_sighash, ) + if tap_sigs > 0: + counter += tap_sigs + self._update_tx_modifiable(inp_sighash) continue # hash can be reused @@ -1418,13 +1420,116 @@ def sign_with(self, root, sighash=SIGHASH.DEFAULT) -> int: # check if root itself is included in the script if sec in sc.data or pkh in sc.data: sig = root.sign(h) - # sig plus sighash flag inp.partial_sigs[rootpub] = sig.serialize() + bytes([inp_sighash]) counter += 1 + self._update_tx_modifiable(inp_sighash) for prv, pub in derived_keypairs: sig = prv.sign(h) - # sig plus sighash flag inp.partial_sigs[pub] = sig.serialize() + bytes([inp_sighash]) counter += 1 + self._update_tx_modifiable(inp_sighash) + return counter + + def _update_tx_modifiable(self, inp_sighash: int) -> None: + """ + Update PSBT_GLOBAL_TX_MODIFIABLE after a signature is added. + BIP-370 Signer role: signer must update this field to reflect + the constraints imposed by the sighash type used. + """ + if self.version != 2: + return + + is_anyonecanpay = bool(inp_sighash & SIGHASH.ANYONECANPAY) + sighash_type = inp_sighash & 0x1F + + if self.tx_modifiable_flags is None: + self.tx_modifiable_flags = 0 + + if not is_anyonecanpay: + self.tx_modifiable_flags &= ~TxModifiable.INPUTS + if sighash_type != SIGHASH.NONE: + self.tx_modifiable_flags &= ~TxModifiable.OUTPUTS + if sighash_type == SIGHASH.SINGLE: + self.tx_modifiable_flags |= TxModifiable.SIGHASH_SINGLE + + def get_tx_modifiable(self): + return self.tx_modifiable_flags + + def set_tx_modifiable(self, flags): + if self.version != 2: + raise PSBTError("GLOBAL_TX_MODIFIABLE only supported in PSBTv2") + self.tx_modifiable_flags = flags + + def is_inputs_modifiable(self): + if self.version != 2: + return True + if self.tx_modifiable_flags is None: + return False + return bool(self.tx_modifiable_flags & TxModifiable.INPUTS) + + def is_outputs_modifiable(self): + if self.version != 2: + return True + if self.tx_modifiable_flags is None: + return False + return bool(self.tx_modifiable_flags & TxModifiable.OUTPUTS) + + def has_sighash_single(self): + if self.version != 2 or self.tx_modifiable_flags is None: + return False + return bool(self.tx_modifiable_flags & TxModifiable.SIGHASH_SINGLE) + + @classmethod + def create_v2(cls, tx_version=2, fallback_locktime=None, tx_modifiable=None): + """Creator role convenience factory: initialise an empty PSBTv2. + + BIP-370 Creator role: set PSBT_GLOBAL_VERSION=2, PSBT_GLOBAL_TX_VERSION, + and optionally PSBT_GLOBAL_FALLBACK_LOCKTIME and PSBT_GLOBAL_TX_MODIFIABLE + so the Constructor role can immediately begin adding inputs and outputs. + """ + if tx_modifiable is None: + tx_modifiable = TxModifiable.INPUTS | TxModifiable.OUTPUTS + psbt = cls(tx=None, version=2) + psbt.tx_version = tx_version + psbt.locktime = fallback_locktime + psbt.tx_modifiable_flags = tx_modifiable + return psbt + + def add_input(self, input_scope): + if not self.is_inputs_modifiable(): + raise PSBTError("Inputs are not modifiable") + if self.version == 2: + # BIP370 Constructor role: validate required fields + if input_scope.txid is None: + raise PSBTError("PSBTv2 input must have PSBT_IN_PREVIOUS_TXID") + if input_scope.vout is None: + raise PSBTError("PSBTv2 input must have PSBT_IN_OUTPUT_INDEX") + # Validate locktime compatibility before mutating state + if ( + input_scope.required_height_locktime is not None + or input_scope.required_time_locktime is not None + ): + self._validate_locktime_compatibility(self.inputs + [input_scope]) + # SIGHASH_SINGLE: each added input must have a paired output + if self.has_sighash_single() and len(self.inputs) >= len(self.outputs): + raise PSBTError( + "Cannot add input without a corresponding output when SIGHASH_SINGLE is set" + ) + self.inputs.append(input_scope) + if self.version == 2: + self._raw_input_count_from_global = len(self.inputs) + + def add_output(self, output_scope): + if not self.is_outputs_modifiable(): + raise PSBTError("Outputs are not modifiable") + if self.version == 2: + # BIP370 Constructor role: validate required fields + if output_scope.value is None: + raise PSBTError("PSBTv2 output must have PSBT_OUT_AMOUNT") + if output_scope.script_pubkey is None: + raise PSBTError("PSBTv2 output must have PSBT_OUT_SCRIPT") + self.outputs.append(output_scope) + if self.version == 2: + self._raw_output_count_from_global = len(self.outputs) From 6c6e040af8032b962c098827d3424a93b36a3079 Mon Sep 17 00:00:00 2001 From: notTanveer Date: Mon, 11 May 2026 16:01:24 +0530 Subject: [PATCH 4/8] tests: add BIP-370 PSBTv2 test vectors Add test_psbtV2.py with 48 tests covering PSBTv2 parsing, serialization, locktime selection, TxModifiable flags, and add_input/add_output API. --- tests/tests/test_psbtV2.py | 583 +++++++++++++++++++++++++++++++++++++ 1 file changed, 583 insertions(+) create mode 100644 tests/tests/test_psbtV2.py diff --git a/tests/tests/test_psbtV2.py b/tests/tests/test_psbtV2.py new file mode 100644 index 00000000..a296299f --- /dev/null +++ b/tests/tests/test_psbtV2.py @@ -0,0 +1,583 @@ +""" +BIP 370 Test Vectors for PSBTv2 +https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#user-content-Test_Vectors +""" + +import pytest +from binascii import unhexlify +from io import BytesIO +from embit.psbt import PSBT, PSBTError, TxModifiable, InputScope, OutputScope +from embit.psbtview import PSBTView +from embit.script import Script +from embit.transaction import SIGHASH + + +class TestPSBTVectors: + """Test vectors for PSBT parsing and validation""" + + def test_invalid_psbtv0_with_version_field(self): + """PSBTv0 but with PSBT_GLOBAL_VERSION set to 2 should be invalid""" + hex_data = "70736274ff01007102000000010b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc80000000000feffffff020008af2f00000000160014c430f64c4756da310dbd1a085572ef299926272c8bbdeb0b00000000160014a07dac8ab6ca942d379ed795f835ba71c9cc68850000000001fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e01086b02473044022005275a485734e0ae1f3b971237586f0e72dc85833d278c0e474cd23112c0fa5e02206b048c83cebc3c41d0b93cc7da76185cedbd030d005b08018be2b98bbacbdf7b012103760dcca05f3997dc65b293060f7f29f1514c8c527048e12802b041d4fc340a2700220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a000000002202036efe2c255621986553ba9d65c3ddc64165ca1436e05aa35a4c6eb02451cf796d18f69d873e540000800100008000000080010000006200000000" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv0_with_tx_version(self): + """PSBTv0 but with PSBT_GLOBAL_TX_VERSION should be invalid""" + hex_data = "70736274ff01007102000000010b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc80000000000feffffff020008af2f00000000160014c430f64c4756da310dbd1a085572ef299926272c8bbdeb0b00000000160014a07dac8ab6ca942d379ed795f835ba71c9cc68850000000001020402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e01086b02473044022005275a485734e0ae1f3b971237586f0e72dc85833d278c0e474cd23112c0fa5e02206b048c83cebc3c41d0b93cc7da76185cedbd030d005b08018be2b98bbacbdf7b012103760dcca05f3997dc65b293060f7f29f1514c8c527048e12802b041d4fc340a2700220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a000000002202036efe2c255621986553ba9d65c3ddc64165ca1436e05aa35a4c6eb02451cf796d18f69d873e540000800100008000000080010000006200000000" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv0_with_fallback_locktime(self): + """PSBTv0 but with PSBT_GLOBAL_FALLBACK_LOCKTIME should be invalid""" + hex_data = "70736274ff01007102000000010b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc80000000000feffffff020008af2f00000000160014c430f64c4756da310dbd1a085572ef299926272c8bbdeb0b00000000160014a07dac8ab6ca942d379ed795f835ba71c9cc68850000000001030402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e01086b02473044022005275a485734e0ae1f3b971237586f0e72dc85833d278c0e474cd23112c0fa5e02206b048c83cebc3c41d0b93cc7da76185cedbd030d005b08018be2b98bbacbdf7b012103760dcca05f3997dc65b293060f7f29f1514c8c527048e12802b041d4fc340a2700220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a000000002202036efe2c255621986553ba9d65c3ddc64165ca1436e05aa35a4c6eb02451cf796d18f69d873e540000800100008000000080010000006200000000" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv0_with_input_count(self): + """PSBTv0 but with PSBT_GLOBAL_INPUT_COUNT should be invalid""" + hex_data = "70736274ff01007102000000010b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc80000000000feffffff020008af2f00000000160014c430f64c4756da310dbd1a085572ef299926272c8bbdeb0b00000000160014a07dac8ab6ca942d379ed795f835ba71c9cc68850000000001040102000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e01086b02473044022005275a485734e0ae1f3b971237586f0e72dc85833d278c0e474cd23112c0fa5e02206b048c83cebc3c41d0b93cc7da76185cedbd030d005b08018be2b98bbacbdf7b012103760dcca05f3997dc65b293060f7f29f1514c8c527048e12802b041d4fc340a2700220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a000000002202036efe2c255621986553ba9d65c3ddc64165ca1436e05aa35a4c6eb02451cf796d18f69d873e540000800100008000000080010000006200000000" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv0_with_output_count(self): + """PSBTv0 but with PSBT_GLOBAL_OUTPUT_COUNT should be invalid""" + hex_data = "70736274ff01007102000000010b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc80000000000feffffff020008af2f00000000160014c430f64c4756da310dbd1a085572ef299926272c8bbdeb0b00000000160014a07dac8ab6ca942d379ed795f835ba71c9cc68850000000001050102000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e01086b02473044022005275a485734e0ae1f3b971237586f0e72dc85833d278c0e474cd23112c0fa5e02206b048c83cebc3c41d0b93cc7da76185cedbd030d005b08018be2b98bbacbdf7b012103760dcca05f3997dc65b293060f7f29f1514c8c527048e12802b041d4fc340a2700220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a000000002202036efe2c255621986553ba9d65c3ddc64165ca1436e05aa35a4c6eb02451cf796d18f69d873e540000800100008000000080010000006200000000" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv0_with_tx_modifiable(self): + """PSBTv0 but with PSBT_GLOBAL_TX_MODIFIABLE should be invalid""" + hex_data = "70736274ff01007102000000010b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc80000000000feffffff020008af2f00000000160014c430f64c4756da310dbd1a085572ef299926272c8bbdeb0b00000000160014a07dac8ab6ca942d379ed795f835ba71c9cc68850000000001060100000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e01086b02473044022005275a485734e0ae1f3b971237586f0e72dc85833d278c0e474cd23112c0fa5e02206b048c83cebc3c41d0b93cc7da76185cedbd030d005b08018be2b98bbacbdf7b012103760dcca05f3997dc65b293060f7f29f1514c8c527048e12802b041d4fc340a2700220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a000000002202036efe2c255621986553ba9d65c3ddc64165ca1436e05aa35a4c6eb02451cf796d18f69d873e540000800100008000000080010000006200000000" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv0_with_previous_txid(self): + """PSBTv0 but with PSBT_IN_PREVIOUS_TXID should be invalid""" + hex_data = "70736274ff01007102000000010b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc80000000000feffffff020008af2f00000000160014c430f64c4756da310dbd1a085572ef299926272c8bbdeb0b00000000160014a07dac8ab6ca942d379ed795f835ba71c9cc688500000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e01086b02473044022005275a485734e0ae1f3b971237586f0e72dc85833d278c0e474cd23112c0fa5e02206b048c83cebc3c41d0b93cc7da76185cedbd030d005b08018be2b98bbacbdf7b012103760dcca05f3997dc65b293060f7f29f1514c8c527048e12802b041d4fc340a27010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc800220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a000000002202036efe2c255621986553ba9d65c3ddc64165ca1436e05aa35a4c6eb02451cf796d18f69d873e540000800100008000000080010000006200000000" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv0_with_output_index(self): + """PSBTv0 but with PSBT_IN_OUTPUT_INDEX should be invalid""" + hex_data = "70736274ff01007102000000010b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc80000000000feffffff020008af2f00000000160014c430f64c4756da310dbd1a085572ef299926272c8bbdeb0b00000000160014a07dac8ab6ca942d379ed795f835ba71c9cc688500000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e01086b02473044022005275a485734e0ae1f3b971237586f0e72dc85833d278c0e474cd23112c0fa5e02206b048c83cebc3c41d0b93cc7da76185cedbd030d005b08018be2b98bbacbdf7b012103760dcca05f3997dc65b293060f7f29f1514c8c527048e12802b041d4fc340a27010f040000000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a000000002202036efe2c255621986553ba9d65c3ddc64165ca1436e05aa35a4c6eb02451cf796d18f69d873e540000800100008000000080010000006200000000" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv0_with_sequence(self): + """PSBTv0 but with PSBT_IN_SEQUENCE should be invalid""" + hex_data = "70736274ff01007102000000010b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc80000000000feffffff020008af2f00000000160014c430f64c4756da310dbd1a085572ef299926272c8bbdeb0b00000000160014a07dac8ab6ca942d379ed795f835ba71c9cc688500000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e01086b02473044022005275a485734e0ae1f3b971237586f0e72dc85833d278c0e474cd23112c0fa5e02206b048c83cebc3c41d0b93cc7da76185cedbd030d005b08018be2b98bbacbdf7b012103760dcca05f3997dc65b293060f7f29f1514c8c527048e12802b041d4fc340a27011004ffffffff00220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a000000002202036efe2c255621986553ba9d65c3ddc64165ca1436e05aa35a4c6eb02451cf796d18f69d873e540000800100008000000080010000006200000000" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv0_with_required_time_locktime(self): + """PSBTv0 but with PSBT_IN_REQUIRED_TIME_LOCKTIME should be invalid""" + hex_data = "70736274ff01007102000000010b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc80000000000feffffff020008af2f00000000160014c430f64c4756da310dbd1a085572ef299926272c8bbdeb0b00000000160014a07dac8ab6ca942d379ed795f835ba71c9cc688500000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e01086b02473044022005275a485734e0ae1f3b971237586f0e72dc85833d278c0e474cd23112c0fa5e02206b048c83cebc3c41d0b93cc7da76185cedbd030d005b08018be2b98bbacbdf7b012103760dcca05f3997dc65b293060f7f29f1514c8c527048e12802b041d4fc340a270111048c8dc46200220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a000000002202036efe2c255621986553ba9d65c3ddc64165ca1436e05aa35a4c6eb02451cf796d18f69d873e540000800100008000000080010000006200000000" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv0_with_required_height_locktime(self): + """PSBTv0 but with PSBT_IN_REQUIRED_HEIGHT_LOCKTIME should be invalid""" + hex_data = "70736274ff01007102000000010b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc80000000000feffffff020008af2f00000000160014c430f64c4756da310dbd1a085572ef299926272c8bbdeb0b00000000160014a07dac8ab6ca942d379ed795f835ba71c9cc688500000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e01086b02473044022005275a485734e0ae1f3b971237586f0e72dc85833d278c0e474cd23112c0fa5e02206b048c83cebc3c41d0b93cc7da76185cedbd030d005b08018be2b98bbacbdf7b012103760dcca05f3997dc65b293060f7f29f1514c8c527048e12802b041d4fc340a270112041027000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a000000002202036efe2c255621986553ba9d65c3ddc64165ca1436e05aa35a4c6eb02451cf796d18f69d873e540000800100008000000080010000006200000000" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv0_with_output_amount(self): + """PSBTv0 but with PSBT_OUT_AMOUNT should be invalid""" + hex_data = "70736274ff01007102000000010b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc80000000000feffffff020008af2f00000000160014c430f64c4756da310dbd1a085572ef299926272c8bbdeb0b00000000160014a07dac8ab6ca942d379ed795f835ba71c9cc688500000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e01086b02473044022005275a485734e0ae1f3b971237586f0e72dc85833d278c0e474cd23112c0fa5e02206b048c83cebc3c41d0b93cc7da76185cedbd030d005b08018be2b98bbacbdf7b012103760dcca05f3997dc65b293060f7f29f1514c8c527048e12802b041d4fc340a2700220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f00000000002202036efe2c255621986553ba9d65c3ddc64165ca1436e05aa35a4c6eb02451cf796d18f69d873e540000800100008000000080010000006200000000" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv0_with_output_script(self): + """PSBTv0 but with PSBT_OUT_SCRIPT should be invalid""" + hex_data = "70736274ff01007102000000010b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc80000000000feffffff020008af2f00000000160014c430f64c4756da310dbd1a085572ef299926272c8bbdeb0b00000000160014a07dac8ab6ca942d379ed795f835ba71c9cc688500000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e01086b02473044022005275a485734e0ae1f3b971237586f0e72dc85833d278c0e474cd23112c0fa5e02206b048c83cebc3c41d0b93cc7da76185cedbd030d005b08018be2b98bbacbdf7b012103760dcca05f3997dc65b293060f7f29f1514c8c527048e12802b041d4fc340a2700220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000104160014a07dac8ab6ca942d379ed795f835ba71c9cc6885002202036efe2c255621986553ba9d65c3ddc64165ca1436e05aa35a4c6eb02451cf796d18f69d873e540000800100008000000080010000006200000000" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv2_global_unsigned_tx(self): + """PSBTv2 with PSBT_GLOBAL_UNSIGNED_TX should be invalid""" + hex_data = "70736274ff0100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e00000000010204020000000103040000000001040101010501020106010701fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f0400000000011004feffffff0111048c8dc4620112041027000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv2_missing_input_count(self): + """PSBTv2 missing PSBT_GLOBAL_INPUT_COUNT should be invalid""" + hex_data = "70736274ff01020402000000010304000000000105010201fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f0400000000011004feffffff00220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv2_missing_output_count(self): + """PSBTv2 missing PSBT_GLOBAL_OUTPUT_COUNT should be invalid""" + hex_data = "70736274ff01020402000000010304000000000104010101fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f0400000000011004feffffff00220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv2_missing_tx_version(self): + """PSBTv2 missing PSBT_GLOBAL_TX_VERSION should be invalid""" + hex_data = "70736274ff010401010105010201fb040200000000010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f0400000000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv2_missing_previous_txid(self): + """PSBTv2 input missing PSBT_IN_PREVIOUS_TXID should be invalid""" + hex_data = "70736274ff0102040200000001030400000000010401010105010201fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010f0400000000011004feffffff00220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv2_missing_output_index(self): + """PSBTv2 input missing PSBT_IN_OUTPUT_INDEX should be invalid""" + hex_data = "70736274ff0102040200000001030400000000010401010105010201fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8011004feffffff00220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv2_missing_output_amount(self): + """PSBTv2 output missing PSBT_OUT_AMOUNT should be invalid""" + hex_data = "70736274ff0102040200000001030400000000010401010105010201fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f0400000000011004feffffff00220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv2_missing_output_script(self): + """PSBTv2 output missing PSBT_OUT_SCRIPT should be invalid""" + hex_data = "70736274ff0102040200000001030400000000010401010105010201fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f0400000000011004feffffff00220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f0000000000220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv2_invalid_time_locktime(self): + """PSBTv2 with PSBT_IN_REQUIRED_TIME_LOCKTIME less than 500000000 should be invalid""" + hex_data = "70736274ff01020402000000010401010105010201fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f0400000000011104ff64cd1d00220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv2_invalid_height_locktime(self): + """PSBTv2 with PSBT_IN_REQUIRED_HEIGHT_LOCKTIME >= 500000000 should be invalid""" + hex_data = "70736274ff01020402000000010401010105010201fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f04000000000112040065cd1d00220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + def test_invalid_psbtv2_height_locktime_zero(self): + """PSBTv2 with PSBT_IN_REQUIRED_HEIGHT_LOCKTIME == 0 should be invalid""" + hex_data = "70736274ff010204020000000103040000000001040101010501020106010701fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f0400000000011004feffffff0111048c8dc4620112040000000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + with pytest.raises(PSBTError): + PSBT.parse(unhexlify(hex_data)) + + # Valid PSBTs + def test_valid_psbtv2_minimal(self): + """1 input, 2 output PSBTv2, required fields only should be valid""" + hex_data = "70736274ff01020402000000010401010105010201fb040200000000010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f0400000000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert len(psbt.inputs) == 1 + assert len(psbt.outputs) == 2 + + def test_valid_psbtv2_updated(self): + """1 input, 2 output updated PSBTv2 should be valid""" + hex_data = "70736274ff01020402000000010401010105010201fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f040000000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert len(psbt.inputs) == 1 + assert len(psbt.outputs) == 2 + + def test_valid_psbtv2_with_sequence(self): + """1 input, 2 output PSBTv2 with sequence should be valid""" + hex_data = "70736274ff01020402000000010401010105010201fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f0400000000011004feffffff00220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert psbt.inputs[0].sequence == 0xFFFFFFFE + + def test_valid_psbtv2_with_sequence_and_locktime(self): + """PSBTv2 with all possible fields should be valid, including sequence""" + hex_data = "70736274ff0102040200000001030400000000010401010105010201fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f0400000000011004feffffff0111048c8dc4620112041027000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert psbt.inputs[0].sequence == 0xFFFFFFFE + assert psbt.inputs[0].required_time_locktime == 1657048460 + assert psbt.inputs[0].required_height_locktime == 10000 + + def test_inputs_modifiable_flag(self): + """Inputs Modifiable Flag (bit 0) only""" + hex_data = "70736274ff0102040200000001040101010501020106010101fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f040000000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert len(psbt.inputs) == 1 + assert len(psbt.outputs) == 2 + assert psbt.tx_modifiable_flags == 0x01 + assert psbt.is_inputs_modifiable() + assert not psbt.is_outputs_modifiable() + assert not psbt.has_sighash_single() + + def test_outputs_modifiable_flag(self): + """Outputs Modifiable Flag (bit 1) only""" + hex_data = "70736274ff0102040200000001040101010501020106010201fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f040000000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert len(psbt.inputs) == 1 + assert len(psbt.outputs) == 2 + assert psbt.tx_modifiable_flags == 0x02 + assert not psbt.is_inputs_modifiable() + assert psbt.is_outputs_modifiable() + assert not psbt.has_sighash_single() + + def test_sighash_single_flag(self): + """Has SIGHASH_SINGLE Flag (bit 2) only""" + hex_data = "70736274ff0102040200000001040101010501020106010401fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f040000000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert len(psbt.inputs) == 1 + assert len(psbt.outputs) == 2 + assert psbt.tx_modifiable_flags == 0x04 + assert not psbt.is_inputs_modifiable() + assert not psbt.is_outputs_modifiable() + assert psbt.has_sighash_single() + + def test_undefined_flag_bit3(self): + """Undefined flag (bit 3) — parser must not reject it""" + hex_data = "70736274ff0102040200000001040101010501020106010801fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f040000000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert len(psbt.inputs) == 1 + assert len(psbt.outputs) == 2 + assert psbt.tx_modifiable_flags == 0x08 + # bits 0/1/2 are all clear + assert not psbt.is_inputs_modifiable() + assert not psbt.is_outputs_modifiable() + assert not psbt.has_sighash_single() + + def test_inputs_and_outputs_modifiable(self): + """Inputs Modifiable (bit 0) + Outputs Modifiable (bit 1)""" + hex_data = "70736274ff0102040200000001040101010501020106010301fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f040000000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert len(psbt.inputs) == 1 + assert len(psbt.outputs) == 2 + assert psbt.tx_modifiable_flags == 0x03 + assert psbt.is_inputs_modifiable() + assert psbt.is_outputs_modifiable() + assert not psbt.has_sighash_single() + + def test_inputs_modifiable_and_sighash_single(self): + """Inputs Modifiable (bit 0) + Has SIGHASH_SINGLE (bit 2)""" + hex_data = "70736274ff0102040200000001040101010501020106010501fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f040000000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert len(psbt.inputs) == 1 + assert len(psbt.outputs) == 2 + assert psbt.tx_modifiable_flags == 0x05 + assert psbt.is_inputs_modifiable() + assert not psbt.is_outputs_modifiable() + assert psbt.has_sighash_single() + + def test_outputs_modifiable_and_sighash_single(self): + """Outputs Modifiable (bit 1) + Has SIGHASH_SINGLE (bit 2)""" + hex_data = "70736274ff0102040200000001040101010501020106010601fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f040000000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert len(psbt.inputs) == 1 + assert len(psbt.outputs) == 2 + assert psbt.tx_modifiable_flags == 0x06 + assert not psbt.is_inputs_modifiable() + assert psbt.is_outputs_modifiable() + assert psbt.has_sighash_single() + + def test_all_defined_flags(self): + """All defined flags set: Inputs (bit 0) + Outputs (bit 1) + SIGHASH_SINGLE (bit 2)""" + hex_data = "70736274ff0102040200000001040101010501020106010701fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f040000000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert len(psbt.inputs) == 1 + assert len(psbt.outputs) == 2 + assert psbt.tx_modifiable_flags == 0x07 + assert psbt.is_inputs_modifiable() + assert psbt.is_outputs_modifiable() + assert psbt.has_sighash_single() + + def test_all_possible_flags(self): + """All 8 bits set (0xFF) — defined + undefined flags""" + hex_data = "70736274ff010204020000000104010101050102010601ff01fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f040000000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert len(psbt.inputs) == 1 + assert len(psbt.outputs) == 2 + assert psbt.tx_modifiable_flags == 0xFF + assert psbt.is_inputs_modifiable() + assert psbt.is_outputs_modifiable() + assert psbt.has_sighash_single() + # undefined bits preserved as-is + assert psbt.tx_modifiable_flags & ~( + TxModifiable.INPUTS | TxModifiable.OUTPUTS | TxModifiable.SIGHASH_SINGLE + ) + + def test_valid_psbtv2_with_all_fields(self): + """PSBTv2 with all possible fields should be valid""" + hex_data = "70736274ff010204020000000103040000000001040101010501020106010701fb0402000000000100520200000001c1aa256e214b96a1822f93de42bff3b5f3ff8d0519306e3515d7515a5e805b120000000000ffffffff0118c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e0000000001011f18c69a3b00000000160014b0a3af144208412693ca7d166852b52db0aef06e010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f0400000000011004feffffff0111048c8dc4620112041027000000220202d601f84846a6755f776be00e3d9de8fb10acc935fb83c45fb0162d4cad5ab79218f69d873e540000800100008000000080000000002a0000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c00220202e36fbff53dd534070cf8fd396614680f357a9b85db7340bf1cfa745d2ad7b34018f69d873e54000080010000800000008001000000640000000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.version == 2 + assert psbt.inputs[0].required_time_locktime == 1657048460 + assert psbt.inputs[0].required_height_locktime == 10000 + + +class TestPSBTLocktime: + """Test locktime determination algorithm for PSBTv2""" + + def test_locktime_no_locktimes_specified(self): + """No locktimes specified should return 0""" + hex_data = "70736274ff01020402000000010401010105010201fb040200000000010e200b0ad921419c1c8719735d72dc739f9ea9e0638d1fe4c1eef0f9944084815fc8010f0400000000000103080008af2f000000000104160014c430f64c4756da310dbd1a085572ef299926272c000103088bbdeb0b0000000001041600144dd193ac964a56ac1b9e1cca8454fe2f474f851300" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.determine_locktime() == 0 + + def test_locktime_fallback_zero(self): + """Fallback locktime of 0 should return 0""" + hex_data = "70736274ff0102040200000001030400000000010401020105010101fb040200000000010e200f758dbfbd4da7c16c8a3309c3c81e1100f561ea646db5b01752c485e1bdde9f010f040100000000010e203a1b3b3c837d6489ea7a31d8e6c7dd503c001bef3e06958e7574808d68ca78a5010f0400000000000103084f9335770000000001041600140b1352cacd03cf6aa1b7f3c8d6388671b34a5e1100" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.determine_locktime() == 0 + + def test_locktime_height_10000(self): + """Height locktime of 10000 should return 10000""" + hex_data = "70736274ff0102040200000001030400000000010401020105010101fb040200000000010e200f758dbfbd4da7c16c8a3309c3c81e1100f561ea646db5b01752c485e1bdde9f010f04010000000112041027000000010e203a1b3b3c837d6489ea7a31d8e6c7dd503c001bef3e06958e7574808d68ca78a5010f0400000000000103084f9335770000000001041600140b1352cacd03cf6aa1b7f3c8d6388671b34a5e1100" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert psbt.determine_locktime() == 10000 + + def test_locktime_max_height(self): + """Multiple height locktimes should return maximum""" + hex_data = "70736274ff0102040200000001030400000000010401020105010101fb040200000000010e200f758dbfbd4da7c16c8a3309c3c81e1100f561ea646db5b01752c485e1bdde9f010f04010000000112041027000000010e203a1b3b3c837d6489ea7a31d8e6c7dd503c001bef3e06958e7574808d68ca78a5010f040000000001120428230000000103084f9335770000000001041600140b1352cacd03cf6aa1b7f3c8d6388671b34a5e1100" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert len(psbt.inputs) == 2 + assert psbt.determine_locktime() == 10000 # max(10000, 9000) + + def test_locktime_height_and_time(self): + """1 input with Height and other with height and time locktimes should return max height value""" + hex_data = "70736274ff0102040200000001030400000000010401020105010101fb040200000000010e200f758dbfbd4da7c16c8a3309c3c81e1100f561ea646db5b01752c485e1bdde9f010f04010000000112041027000000010e203a1b3b3c837d6489ea7a31d8e6c7dd503c001bef3e06958e7574808d68ca78a5010f04000000000111048c8dc46201120428230000000103084f9335770000000001041600140b1352cacd03cf6aa1b7f3c8d6388671b34a5e1100" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert len(psbt.inputs) == 2 + assert psbt.determine_locktime() == 10000 + + def test_locktime_height_preferred_over_time(self): + """Height locktime should be preferred when both present (BIP-370: height preferred on tie)""" + hex_data = "70736274ff0102040200000001030400000000010401020105010101fb040200000000010e200f758dbfbd4da7c16c8a3309c3c81e1100f561ea646db5b01752c485e1bdde9f010f04010000000111048b8dc4620112041027000000010e203a1b3b3c837d6489ea7a31d8e6c7dd503c001bef3e06958e7574808d68ca78a5010f04000000000111048c8dc46201120428230000000103084f9335770000000001041600140b1352cacd03cf6aa1b7f3c8d6388671b34a5e1100" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert len(psbt.inputs) == 2 + assert psbt.determine_locktime() == 10000 # Height takes priority over time + + def test_locktime_time_only(self): + """Time locktime only should return time value""" + hex_data = "70736274ff0102040200000001030400000000010401020105010101fb040200000000010e200f758dbfbd4da7c16c8a3309c3c81e1100f561ea646db5b01752c485e1bdde9f010f04010000000111048b8dc46200010e203a1b3b3c837d6489ea7a31d8e6c7dd503c001bef3e06958e7574808d68ca78a5010f04000000000111048c8dc46201120428230000000103084f9335770000000001041600140b1352cacd03cf6aa1b7f3c8d6388671b34a5e1100" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert len(psbt.inputs) == 2 + assert psbt.determine_locktime() == 1657048460 + + def test_locktime_max_time(self): + """Multiple time locktimes should return maximum""" + hex_data = "70736274ff0102040200000001030400000000010401020105010101fb040200000000010e200f758dbfbd4da7c16c8a3309c3c81e1100f561ea646db5b01752c485e1bdde9f010f040100000000010e203a1b3b3c837d6489ea7a31d8e6c7dd503c001bef3e06958e7574808d68ca78a5010f04000000000111048c8dc462000103084f9335770000000001041600140b1352cacd03cf6aa1b7f3c8d6388671b34a5e1100" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert len(psbt.inputs) == 2 + assert psbt.determine_locktime() == 1657048460 + + def test_locktime_time_wins_when_not_all_support_height(self): + """Input 1 has height 10000 and time 1657048459, Input 2 has time 1657048460 only should return max time 1657048460""" + hex_data = "70736274ff0102040200000001030400000000010401020105010101fb040200000000010e200f758dbfbd4da7c16c8a3309c3c81e1100f561ea646db5b01752c485e1bdde9f010f04010000000111048b8dc4620112041027000000010e203a1b3b3c837d6489ea7a31d8e6c7dd503c001bef3e06958e7574808d68ca78a5010f04000000000111048c8dc462000103084f9335770000000001041600140b1352cacd03cf6aa1b7f3c8d6388671b34a5e1100" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert len(psbt.inputs) == 2 + assert psbt.determine_locktime() == 1657048460 + + def test_locktime_uncomputable(self): + """Input with height only and input with time only should raise PSBTError""" + hex_data = "70736274ff0102040200000001030400000000010401020105010101fb040200000000010e200f758dbfbd4da7c16c8a3309c3c81e1100f561ea646db5b01752c485e1bdde9f010f04010000000112041027000000010e203a1b3b3c837d6489ea7a31d8e6c7dd503c001bef3e06958e7574808d68ca78a5010f04000000000111048c8dc462000103084f9335770000000001041600140b1352cacd03cf6aa1b7f3c8d6388671b34a5e1100" + + psbt = PSBT.parse(unhexlify(hex_data)) + assert len(psbt.inputs) == 2 + with pytest.raises(PSBTError): + psbt.determine_locktime() + + +class TestPSBTv2Constructor: + """Test BIP-370 Creator / Constructor role: create_v2(), add_input(), add_output()""" + + def test_create_v2_defaults(self): + """create_v2() produces a version-2 PSBT with sensible defaults""" + psbt = PSBT.create_v2() + assert psbt.version == 2 + assert psbt.tx_version == 2 + assert psbt.locktime is None + assert psbt.tx_modifiable_flags == TxModifiable.INPUTS | TxModifiable.OUTPUTS + assert len(psbt.inputs) == 0 + assert len(psbt.outputs) == 0 + + def test_create_v2_custom_params(self): + """create_v2() accepts custom tx_version, fallback_locktime and tx_modifiable""" + psbt = PSBT.create_v2( + tx_version=1, + fallback_locktime=600000, + tx_modifiable=TxModifiable.INPUTS, + ) + assert psbt.tx_version == 1 + assert psbt.locktime == 600000 + assert psbt.tx_modifiable_flags == TxModifiable.INPUTS + + def test_add_input_appends_and_updates_count(self): + """add_input() appends the scope and increments the global input count""" + psbt = PSBT.create_v2() + inp = InputScope() + inp.txid = bytes(32) + inp.vout = 0 + psbt.add_input(inp) + assert len(psbt.inputs) == 1 + assert psbt._raw_input_count_from_global == 1 + + def test_add_input_requires_inputs_modifiable(self): + """add_input() raises when INPUTS bit is clear""" + psbt = PSBT.create_v2(tx_modifiable=TxModifiable.OUTPUTS) + inp = InputScope() + inp.txid = bytes(32) + inp.vout = 0 + with pytest.raises(PSBTError): + psbt.add_input(inp) + + def test_add_input_requires_txid(self): + """add_input() raises when PSBT_IN_PREVIOUS_TXID is absent""" + psbt = PSBT.create_v2() + inp = InputScope() + inp.vout = 0 + with pytest.raises(PSBTError): + psbt.add_input(inp) + + def test_add_input_requires_vout(self): + """add_input() raises when PSBT_IN_OUTPUT_INDEX is absent""" + psbt = PSBT.create_v2() + inp = InputScope() + inp.txid = bytes(32) + with pytest.raises(PSBTError): + psbt.add_input(inp) + + def test_add_output_appends_and_updates_count(self): + """add_output() appends the scope and increments the global output count""" + psbt = PSBT.create_v2() + out = OutputScope() + out.value = 100000 + out.script_pubkey = Script(b"\x00\x14" + bytes(20)) + psbt.add_output(out) + assert len(psbt.outputs) == 1 + assert psbt._raw_output_count_from_global == 1 + + def test_add_output_requires_outputs_modifiable(self): + """add_output() raises when OUTPUTS bit is clear""" + psbt = PSBT.create_v2(tx_modifiable=TxModifiable.INPUTS) + out = OutputScope() + out.value = 100000 + out.script_pubkey = Script(b"\x00\x14" + bytes(20)) + with pytest.raises(PSBTError): + psbt.add_output(out) + + def test_add_output_requires_amount(self): + """add_output() raises when PSBT_OUT_AMOUNT is absent""" + psbt = PSBT.create_v2() + out = OutputScope() + out.script_pubkey = Script(b"\x00\x14" + bytes(20)) + with pytest.raises(PSBTError): + psbt.add_output(out) + + def test_add_output_requires_script(self): + """add_output() raises when PSBT_OUT_SCRIPT is absent""" + psbt = PSBT.create_v2() + out = OutputScope() + out.value = 100000 + with pytest.raises(PSBTError): + psbt.add_output(out) + + +class TestTxModifiableUpdate: + """Test BIP-370 Signer role: _update_tx_modifiable() correctly restricts future modifications""" + + def test_sighash_all_clears_inputs_and_outputs(self): + """SIGHASH_ALL (not ANYONECANPAY) must clear both INPUTS and OUTPUTS bits""" + psbt = PSBT.create_v2() + psbt.tx_modifiable_flags = TxModifiable.INPUTS | TxModifiable.OUTPUTS + psbt._update_tx_modifiable(SIGHASH.ALL) + assert not psbt.is_inputs_modifiable() + assert not psbt.is_outputs_modifiable() + assert not psbt.has_sighash_single() + + def test_sighash_none_clears_inputs_preserves_outputs(self): + """SIGHASH_NONE clears INPUTS bit but must not touch the OUTPUTS bit""" + psbt = PSBT.create_v2() + psbt.tx_modifiable_flags = TxModifiable.INPUTS | TxModifiable.OUTPUTS + psbt._update_tx_modifiable(SIGHASH.NONE) + assert not psbt.is_inputs_modifiable() + assert psbt.is_outputs_modifiable() + + def test_sighash_single_sets_flag_and_clears_inputs(self): + """SIGHASH_SINGLE sets SIGHASH_SINGLE flag and clears INPUTS and OUTPUTS bits""" + psbt = PSBT.create_v2() + psbt.tx_modifiable_flags = TxModifiable.INPUTS | TxModifiable.OUTPUTS + psbt._update_tx_modifiable(SIGHASH.SINGLE) + assert not psbt.is_inputs_modifiable() + assert not psbt.is_outputs_modifiable() + assert psbt.has_sighash_single() + + def test_sighash_all_anyonecanpay_preserves_inputs_clears_outputs(self): + """SIGHASH_ALL|ANYONECANPAY preserves INPUTS bit and clears OUTPUTS bit""" + psbt = PSBT.create_v2() + psbt.tx_modifiable_flags = TxModifiable.INPUTS | TxModifiable.OUTPUTS + psbt._update_tx_modifiable(SIGHASH.ALL | SIGHASH.ANYONECANPAY) + assert psbt.is_inputs_modifiable() + assert not psbt.is_outputs_modifiable() + + def test_update_creates_flags_when_absent(self): + """_update_tx_modifiable initialises the field to 0 when it was absent""" + psbt = PSBT.create_v2() + psbt.tx_modifiable_flags = None + psbt._update_tx_modifiable(SIGHASH.ALL) + assert psbt.tx_modifiable_flags == 0 + + def test_no_op_for_psbtv0(self): + """_update_tx_modifiable is a no-op for PSBTv0 (PSBT_GLOBAL_TX_MODIFIABLE is v2-only)""" + psbt = PSBT.create_v2() + psbt.version = None # downgrade to v0 + psbt.tx_modifiable_flags = TxModifiable.INPUTS | TxModifiable.OUTPUTS + psbt._update_tx_modifiable(SIGHASH.ALL) + # must remain untouched because version != 2 + assert psbt.tx_modifiable_flags == TxModifiable.INPUTS | TxModifiable.OUTPUTS From 513722256fb683e922f7fa8ac012360d00e31641 Mon Sep 17 00:00:00 2001 From: notTanveer Date: Wed, 13 May 2026 23:26:53 +0530 Subject: [PATCH 5/8] psbtview: add PSBTv2 support --- src/embit/psbtview.py | 204 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 180 insertions(+), 24 deletions(-) diff --git a/src/embit/psbtview.py b/src/embit/psbtview.py index 75b35e28..99a536f5 100644 --- a/src/embit/psbtview.py +++ b/src/embit/psbtview.py @@ -13,6 +13,7 @@ Makes sense to run gc.collect() after processing of each scope to free memory. """ + # TODO: refactor, a lot of code is duplicated here from transaction.py from collections import OrderedDict import hashlib @@ -26,6 +27,8 @@ CompressMode, InputScope, OutputScope, + TxModifiable, + LOCKTIME_THRESHOLD, read_string, ser_string, skip_string, @@ -180,6 +183,7 @@ def __init__( version=None, tx_offset=None, compress=CompressMode.KEEP_ALL, + global_kvs=None, ): if version != 2 and tx_offset is None: raise PSBTError("Global tx is not found, but PSBT version is %d" % version) @@ -196,8 +200,35 @@ def __init__( self.compress = compress self._tx_version = self.tx.version if self.tx else None self._locktime = self.tx.locktime if self.tx else None + # For PSBTv2: dict of all global key→value pairs (excluding the \x00 global tx). + # This is the single source of truth for every global field, including + # PSBT_GLOBAL_TX_MODIFIABLE (\x06). None for PSBTv0 where the global + # scope is streamed verbatim. + self._global_kvs = global_kvs self.clear_cache() + @property + def tx_modifiable_flags(self): + """PSBT_GLOBAL_TX_MODIFIABLE byte (PSBTv2 only). None when absent or for PSBTv0.""" + if self._global_kvs is None: + return None + v = self._global_kvs.get(b"\x06") + if v is None: + return None + if len(v) != 1: + raise PSBTError("Invalid PSBT_GLOBAL_TX_MODIFIABLE length") + return int.from_bytes(v, "little") + + @tx_modifiable_flags.setter + def tx_modifiable_flags(self, value): + """Setting to None removes the field; ignored for PSBTv0.""" + if self._global_kvs is None: + return + if value is None: + self._global_kvs.pop(b"\x06", None) + else: + self._global_kvs[b"\x06"] = bytes([value]) + def clear_cache(self): # cache for digests self._hash_prevouts = None @@ -222,6 +253,9 @@ def view(cls, stream, offset=None, compress=CompressMode.KEEP_ALL): num_inputs = None num_outputs = None tx_offset = None + # Collect all non-global-tx key-value pairs for PSBTv2 global scope rewriting. + # The global scope is small, so materialising it avoids byte-level injection. + global_kvs = {} while True: # read key and update cursor key = read_string(stream) @@ -229,19 +263,10 @@ def view(cls, stream, offset=None, compress=CompressMode.KEEP_ALL): # separator if len(key) == 0: break - if key in [b"\xfb", b"\x04", b"\x05"]: - value = read_string(stream) - cur += len(value) + len(compact.to_bytes(len(value))) - if key == b"\xfb": - version = int.from_bytes(value, "little") - elif key == b"\x04": - num_inputs = compact.from_bytes(value) - elif key == b"\x05": - num_outputs = compact.from_bytes(value) - elif key == b"\x00": - # we found global transaction - if version == 2: - raise PSBTError("Global transaction with version 2 PSBT") + if key == b"\x00": + # we found global transaction; defer version==2 check until after the loop + # so that PSBT_GLOBAL_UNSIGNED_TX is rejected even when it appears before + # PSBT_GLOBAL_VERSION (key order is not guaranteed). if (num_inputs is not None) or (num_outputs is not None): raise PSBTError("Invalid global transaction") tx_len = compact.read_from(stream) @@ -254,8 +279,21 @@ def view(cls, stream, offset=None, compress=CompressMode.KEEP_ALL): stream.seek(tx_offset + tx_len) cur += tx_len else: - cur += skip_string(stream) + value = read_string(stream) + cur += len(value) + len(compact.to_bytes(len(value))) + if key in global_kvs: + raise PSBTError("Duplicate global key: %s" % key) + global_kvs[key] = value + if key == b"\xfb": + version = int.from_bytes(value, "little") + elif key == b"\x04": + num_inputs = compact.from_bytes(value) + elif key == b"\x05": + num_outputs = compact.from_bytes(value) first_scope = cur + # PSBTv2 must not have a global unsigned transaction, regardless of key order + if tx_offset is not None and version == 2: + raise PSBTError("Global transaction with version 2 PSBT") if None in [version or tx_offset, num_inputs, num_outputs]: raise PSBTError("Missing something important in PSBT") return cls( @@ -267,6 +305,7 @@ def view(cls, stream, offset=None, compress=CompressMode.KEEP_ALL): version, tx_offset, compress, + global_kvs=global_kvs if version == 2 else None, ) def _skip_scope(self): @@ -345,7 +384,7 @@ def vin(self, i, compress=None): vout = int.from_bytes(v, "little") self.seek_to_scope(i) - v = self.get_value(b"\x10", from_current=True) or b"\xFF\xFF\xFF\xFF" + v = self.get_value(b"\x10", from_current=True) or b"\xff\xff\xff\xff" sequence = int.from_bytes(v, "little") return TransactionInput(txid, vout, sequence=sequence) @@ -370,15 +409,92 @@ def vout(self, i, compress=None): @property def locktime(self): if self._locktime is None: - v = self.get_value(b"\x03") - self._locktime = int.from_bytes(v, "little") if v is not None else 0 + if self.version == 2: + self._locktime = self._determine_locktime_v2() + else: + v = self.get_value(b"\x03") + self._locktime = int.from_bytes(v, "little") if v is not None else 0 return self._locktime + def _determine_locktime_v2(self): + """BIP370 locktime determination for PSBTv2. + + Derives the transaction locktime from per-input required locktime fields. + Falls back to PSBT_GLOBAL_FALLBACK_LOCKTIME (or 0) when no input imposes + a requirement. + """ + v = self.get_value(b"\x03") + if v is not None: + if len(v) != 4: + raise PSBTError("PSBT_GLOBAL_FALLBACK_LOCKTIME must be 4 bytes") + fallback = int.from_bytes(v, "little") + else: + fallback = 0 + + height_locktimes = [] + time_locktimes = [] + inputs_with_requirements = 0 + + for i in range(self.num_inputs): + self.seek_to_scope(i) + v_height = self.get_value(b"\x12", from_current=True) + self.seek_to_scope(i) + v_time = self.get_value(b"\x11", from_current=True) + + has_requirement = False + if v_height is not None: + if len(v_height) != 4: + raise PSBTError("PSBT_IN_REQUIRED_HEIGHT_LOCKTIME must be 4 bytes") + height_locktime = int.from_bytes(v_height, "little") + if height_locktime == 0 or height_locktime >= LOCKTIME_THRESHOLD: + raise PSBTError( + f"Height-based locktime must be > 0 and < {LOCKTIME_THRESHOLD}" + ) + height_locktimes.append(height_locktime) + has_requirement = True + if v_time is not None: + if len(v_time) != 4: + raise PSBTError("PSBT_IN_REQUIRED_TIME_LOCKTIME must be 4 bytes") + time_locktime = int.from_bytes(v_time, "little") + if time_locktime < LOCKTIME_THRESHOLD: + raise PSBTError( + f"Time-based locktime must be >= {LOCKTIME_THRESHOLD}" + ) + time_locktimes.append(time_locktime) + has_requirement = True + if has_requirement: + inputs_with_requirements += 1 + + if inputs_with_requirements == 0: + return fallback + + inputs_supporting_height = len(height_locktimes) + inputs_supporting_time = len(time_locktimes) + + # Prefer height-based locktime if every input with requirements supports it + if inputs_supporting_height == inputs_with_requirements: + return max(height_locktimes) + # Fall back to time-based locktime if every input with requirements supports it + if inputs_supporting_time == inputs_with_requirements: + return max(time_locktimes) + + raise PSBTError( + "Cannot determine locktime: inputs have conflicting height and time locktime requirements" + ) + @property def tx_version(self): if self._tx_version is None: v = self.get_value(b"\x02") - self._tx_version = int.from_bytes(v, "little") if v is not None else 0 + if v is None: + if self.version == 2: + raise PSBTError("Missing PSBT_GLOBAL_TX_VERSION in PSBTv2") + self._tx_version = 0 + else: + if len(v) != 4: + raise PSBTError("Invalid PSBT_GLOBAL_TX_VERSION length") + # BIP370: PSBT_GLOBAL_TX_VERSION is a signed int32 + self._tx_version = int.from_bytes(v, "little", signed=True) return self._tx_version def seek_to_value(self, key_start, from_current=False): @@ -468,7 +584,7 @@ def sighash_taproot( sh, anyonecanpay = SIGHASH.check(sighash) h = hashes.tagged_hash_init("TapSighash", b"\x00") h.update(bytes([sighash])) - h.update(self.tx_version.to_bytes(4, "little")) + h.update(self.tx_version.to_bytes(4, "little", signed=True)) h.update(self.locktime.to_bytes(4, "little")) if not anyonecanpay: h.update(self.hash_prevouts()) @@ -516,7 +632,7 @@ def sighash_segwit(self, input_index, script_pubkey, value, sighash=SIGHASH.ALL) inp = self.vin(input_index) zero = b"\x00" * 32 # for sighashes h = hashlib.sha256() - h.update(self.tx_version.to_bytes(4, "little")) + h.update(self.tx_version.to_bytes(4, "little", signed=True)) if anyonecanpay: h.update(zero) else: @@ -556,7 +672,7 @@ def sighash_legacy(self, input_index, script_pubkey, sighash=SIGHASH.ALL): return b"\x00" * 31 + b"\x01" h = hashlib.sha256() - h.update(self.tx_version.to_bytes(4, "little")) + h.update(self.tx_version.to_bytes(4, "little", signed=True)) # ANYONECANPAY - only one input is serialized if anyonecanpay: h.update(compact.to_bytes(1)) @@ -690,6 +806,23 @@ def sign_input_with_tapkey( counter += 1 return counter + def _update_tx_modifiable(self, inp_sighash: int) -> None: + if self.version != 2: + return + + is_anyonecanpay = bool(inp_sighash & SIGHASH.ANYONECANPAY) + sighash_type = inp_sighash & 0x1F + + if self.tx_modifiable_flags is None: + self.tx_modifiable_flags = 0 + + if not is_anyonecanpay: + self.tx_modifiable_flags &= ~TxModifiable.INPUTS + if sighash_type != SIGHASH.NONE: + self.tx_modifiable_flags &= ~TxModifiable.OUTPUTS + if sighash_type == SIGHASH.SINGLE: + self.tx_modifiable_flags |= TxModifiable.SIGHASH_SINGLE + def sign_input( self, i, root, sig_stream, sighash=SIGHASH.DEFAULT, extra_scope_data=None ) -> int: @@ -753,7 +886,7 @@ def sign_input( if fingerprint: # if taproot derivations are present add them for pub in inp.taproot_bip32_derivations: - (_leafs, derivation) = inp.taproot_bip32_derivations[pub] + _leafs, derivation = inp.taproot_bip32_derivations[pub] if derivation.fingerprint == fingerprint: # Add only if not already present if (pub, derivation) not in bip32_derivations: @@ -813,6 +946,8 @@ def sign_input( for pub, leaf in inp.taproot_sigs: ser_string(sig_stream, b"\x14" + pub.xonly() + leaf) ser_string(sig_stream, inp.taproot_sigs[(pub, leaf)]) + if counter > 0: + self._update_tx_modifiable(inp_sighash) return counter h = self.sighash(i, sighash=inp_sighash, input_scope=inp) @@ -824,11 +959,13 @@ def sign_input( # sig plus sighash flag inp.partial_sigs[rootpub] = sig.serialize() + bytes([inp_sighash]) counter += 1 + self._update_tx_modifiable(inp_sighash) for prv, pub in derived_keypairs: sig = prv.sign(h) # sig plus sighash flag inp.partial_sigs[pub] = sig.serialize() + bytes([inp_sighash]) counter += 1 + self._update_tx_modifiable(inp_sighash) for pub in inp.partial_sigs: ser_string(sig_stream, b"\x02" + pub.serialize()) ser_string(sig_stream, inp.partial_sigs[pub]) @@ -856,6 +993,11 @@ def sign_with(self, root, sig_stream, sighash=SIGHASH.DEFAULT) -> int: counter += self.sign_input(i, root, sig_stream, sighash=sighash) # add separator sig_stream.write(b"\x00") + # BIP-370: signer must set PSBT_GLOBAL_TX_MODIFIABLE for PSBTv2. + # Default to 0 (nothing modifiable) when no signing occurred and the + # field was absent — avoids leaving the field missing after a sign pass. + if self.version == 2 and self.tx_modifiable_flags is None: + self.tx_modifiable_flags = 0 return counter def write_to( @@ -879,8 +1021,22 @@ def write_to( compress = self.compress # first we write global scope - self.stream.seek(self.offset) - res = read_write(self.stream, writable_stream, self.first_scope - self.offset) + if self._global_kvs is not None: + # PSBTv2: reconstruct global scope from the materialised key-value dict. + # This sidesteps byte-level injection and gives deterministic key ordering. + writable_stream.write(self.MAGIC) + res = len(self.MAGIC) + for k in sorted(self._global_kvs.keys()): + res += ser_string(writable_stream, k) + res += ser_string(writable_stream, self._global_kvs[k]) + writable_stream.write(b"\x00") # global scope separator + res += 1 + else: + # PSBTv0: stream global scope directly from source (includes global tx). + self.stream.seek(self.offset) + res = read_write( + self.stream, writable_stream, self.first_scope - self.offset + ) # write all inputs for i in range(self.num_inputs): From 9958d7001f63751d57a1a1e1163874841413e544 Mon Sep 17 00:00:00 2001 From: odudex Date: Thu, 14 May 2026 10:21:51 -0300 Subject: [PATCH 6/8] fix: tighten PSBTv2 review follow-ups - reject BIP370-only globals in PSBTView v0 parsing - preserve signed and zero tx versions when synthesizing transactions - serialize transaction versions as signed int32 - keep PSBTv2 compressed non-witness UTXO parsing key-order independent - add regression coverage for the follow-up findings --- src/embit/psbt.py | 24 +++++++----- src/embit/psbtview.py | 13 +++++++ src/embit/transaction.py | 12 +++--- tests/tests/test_psbtV2.py | 77 +++++++++++++++++++++++++++++++++++++- 4 files changed, 109 insertions(+), 17 deletions(-) diff --git a/src/embit/psbt.py b/src/embit/psbt.py index 5332d536..7c4afa31 100644 --- a/src/embit/psbt.py +++ b/src/embit/psbt.py @@ -270,7 +270,7 @@ def read_value(self, stream, k, version=None): elif self.non_witness_utxo is not None: raise PSBTError("Duplicated utxo value") else: - l = compact.read_from(stream) + compact.read_from(stream) # For PSBTv2, PSBT_IN_OUTPUT_INDEX may follow PSBT_IN_NON_WITNESS_UTXO; # use the pre-scanned vout (set by read_from) when the field hasn't # been parsed yet so the OOM protection is key-order independent. @@ -280,7 +280,7 @@ def read_value(self, stream, k, version=None): else getattr(self, "_prescan_vout", None) ) # we verified and saved utxo - if self.compress and self.txid and effective_vout is not None: + if self.compress and effective_vout is not None: txout, txhash = self.TX_CLS.read_vout(stream, effective_vout) self._txhash = txhash self._utxo = txout @@ -577,9 +577,9 @@ def write_to(self, stream, skip_separator=False, version=None, **kwargs) -> int: @classmethod def read_from(cls, stream, compress=CompressMode.KEEP_ALL, vin=None, version=None): res = cls({}, vin=vin, compress=compress) - # For PSBTv2 with compress mode, pre-scan for PSBT_IN_OUTPUT_INDEX so the - # non-witness UTXO memory optimisation works regardless of key order. - # (BIP370 does not guarantee that 0x0f appears before 0x00.) + # PSBT maps are unordered, so PSBTv2 input maps may provide the output + # index after the non-witness UTXO. Peek only at compact-sized keys and + # skip values to keep compressed parsing independent of key order. res._prescan_vout = None if version == 2 and compress and res.vout is None: try: @@ -588,10 +588,15 @@ def read_from(cls, stream, compress=CompressMode.KEEP_ALL, vin=None, version=Non k = read_string(stream) if len(k) == 0: break - v = read_string(stream) - if k == b"\x0f" and len(v) == 4: - res._prescan_vout = int.from_bytes(v, "little") + if k == b"\x0f": + v = read_string(stream) + if len(v) == 4: + res._prescan_vout = int.from_bytes(v, "little") + else: + # Let the real parse raise the precise validation error. + pass break + skip_string(stream) stream.seek(start_pos) except (AttributeError, OSError): pass # stream not seekable; OOM protection may be unavailable @@ -901,8 +906,9 @@ def tx(self): if self.version == 2 and self.tx_version is None: raise PSBTError("PSBTv2 is missing required PSBT_GLOBAL_TX_VERSION") + tx_version = self.tx_version if self.tx_version is not None else 2 return self.TX_CLS( - version=self.tx_version or 2, + version=tx_version, locktime=locktime, vin=[inp.vin for inp in self.inputs], vout=[out.vout for out in self.outputs], diff --git a/src/embit/psbtview.py b/src/embit/psbtview.py index 99a536f5..03b93bff 100644 --- a/src/embit/psbtview.py +++ b/src/embit/psbtview.py @@ -16,6 +16,7 @@ # TODO: refactor, a lot of code is duplicated here from transaction.py from collections import OrderedDict +from binascii import hexlify import hashlib from . import compact from . import ec @@ -285,15 +286,27 @@ def view(cls, stream, offset=None, compress=CompressMode.KEEP_ALL): raise PSBTError("Duplicate global key: %s" % key) global_kvs[key] = value if key == b"\xfb": + if len(value) != 4: + raise PSBTError("PSBT_GLOBAL_VERSION must be 4 bytes") version = int.from_bytes(value, "little") elif key == b"\x04": num_inputs = compact.from_bytes(value) elif key == b"\x05": num_outputs = compact.from_bytes(value) first_scope = cur + if version not in (None, 0, 2): + raise PSBTError("Unsupported PSBT_GLOBAL_VERSION value: %d" % version) + if version == 0: + version = None # PSBTv2 must not have a global unsigned transaction, regardless of key order if tx_offset is not None and version == 2: raise PSBTError("Global transaction with version 2 PSBT") + if version != 2: + for k in {b"\x02", b"\x03", b"\x04", b"\x05", b"\x06"}: + if k in global_kvs: + raise PSBTError( + "Global key %s is not allowed in PSBTv0" % hexlify(k).decode() + ) if None in [version or tx_offset, num_inputs, num_outputs]: raise PSBTError("Missing something important in PSBT") return cls( diff --git a/src/embit/transaction.py b/src/embit/transaction.py index 6eec9b87..083c7f5a 100644 --- a/src/embit/transaction.py +++ b/src/embit/transaction.py @@ -76,7 +76,7 @@ def is_segwit(self): def write_to(self, stream): """Returns the byte serialization of the transaction""" - res = stream.write(self.version.to_bytes(4, "little")) + res = stream.write(self.version.to_bytes(4, "little", signed=True)) if self.is_segwit: res += stream.write(b"\x00\x01") # segwit marker and flag res += stream.write(compact.to_bytes(len(self.vin))) @@ -93,7 +93,7 @@ def write_to(self, stream): def hash(self): h = hashlib.sha256() - h.update(self.version.to_bytes(4, "little")) + h.update(self.version.to_bytes(4, "little", signed=True)) h.update(compact.to_bytes(len(self.vin))) for inp in self.vin: h.update(inp.serialize()) @@ -144,7 +144,7 @@ def read_vout(cls, stream, idx): @classmethod def read_from(cls, stream): - ver = int.from_bytes(stream.read(4), "little") + ver = int.from_bytes(stream.read(4), "little", signed=True) num_vin = compact.read_from(stream) # if num_vin is zero it is a segwit transaction is_segwit = num_vin == 0 @@ -221,7 +221,7 @@ def sighash_taproot( sh, anyonecanpay = SIGHASH.check(sighash) h = hashes.tagged_hash_init("TapSighash", b"\x00") h.update(bytes([sighash])) - h.update(self.version.to_bytes(4, "little")) + h.update(self.version.to_bytes(4, "little", signed=True)) h.update(self.locktime.to_bytes(4, "little")) if not anyonecanpay: h.update(self.hash_prevouts()) @@ -268,7 +268,7 @@ def sighash_segwit(self, input_index, script_pubkey, value, sighash=SIGHASH.ALL) inp = self.vin[input_index] zero = b"\x00" * 32 # for sighashes h = hashlib.sha256() - h.update(self.version.to_bytes(4, "little")) + h.update(self.version.to_bytes(4, "little", signed=True)) if anyonecanpay: h.update(zero) else: @@ -307,7 +307,7 @@ def sighash_legacy(self, input_index, script_pubkey, sighash=SIGHASH.ALL): return b"\x00" * 31 + b"\x01" h = hashlib.sha256() - h.update(self.version.to_bytes(4, "little")) + h.update(self.version.to_bytes(4, "little", signed=True)) # ANYONECANPAY - only one input is serialized if anyonecanpay: h.update(compact.to_bytes(1)) diff --git a/tests/tests/test_psbtV2.py b/tests/tests/test_psbtV2.py index a296299f..2830728e 100644 --- a/tests/tests/test_psbtV2.py +++ b/tests/tests/test_psbtV2.py @@ -6,10 +6,17 @@ import pytest from binascii import unhexlify from io import BytesIO -from embit.psbt import PSBT, PSBTError, TxModifiable, InputScope, OutputScope +from embit.psbt import ( + PSBT, + PSBTError, + TxModifiable, + InputScope, + OutputScope, + CompressMode, +) from embit.psbtview import PSBTView from embit.script import Script -from embit.transaction import SIGHASH +from embit.transaction import SIGHASH, Transaction, TransactionInput, TransactionOutput class TestPSBTVectors: @@ -581,3 +588,69 @@ def test_no_op_for_psbtv0(self): psbt._update_tx_modifiable(SIGHASH.ALL) # must remain untouched because version != 2 assert psbt.tx_modifiable_flags == TxModifiable.INPUTS | TxModifiable.OUTPUTS + + +class TestPSBTViewV2Validation: + def test_psbtview_rejects_v2_only_global_in_v0(self): + """PSBTView should enforce the same v0/v2 global separation as PSBT""" + psbt = PSBT(Transaction()) + raw = psbt.serialize() + stream = BytesIO(raw) + stream.read(len(PSBT.MAGIC)) + while True: + pos = stream.tell() + key_len = stream.read(1)[0] + if key_len == 0: + separator = pos + break + stream.seek(key_len, 1) + value_len = stream.read(1)[0] + stream.seek(value_len, 1) + + tx_version_kv = b"\x01\x02\x04\x02\x00\x00\x00" + invalid = raw[:separator] + tx_version_kv + raw[separator:] + with pytest.raises(PSBTError): + PSBTView.view(BytesIO(invalid)) + + +class TestPSBTv2TransactionVersion: + def test_psbt_tx_preserves_zero_and_negative_versions(self): + """PSBT_GLOBAL_TX_VERSION is signed and zero must not fall back to 2""" + psbt = PSBT.create_v2(tx_version=0) + inp = InputScope() + inp.txid = bytes(32) + inp.vout = 0 + psbt.add_input(inp) + out = OutputScope() + out.value = 1 + out.script_pubkey = Script(b"") + psbt.add_output(out) + assert psbt.tx.serialize()[:4] == b"\x00\x00\x00\x00" + + psbt.tx_version = -1 + assert psbt.tx.serialize()[:4] == b"\xff\xff\xff\xff" + + +class TestPSBTv2Compression: + def test_psbtv2_compress_non_witness_utxo_is_key_order_independent(self): + """PSBTv2 compress should not load the full prev tx when 0x00 precedes 0x0f""" + prev = Transaction( + vin=[TransactionInput(bytes([1]) * 32, 0)], + vout=[TransactionOutput(1234, Script(b"\x51"))], + ) + psbt = PSBT.create_v2() + inp = InputScope() + inp.txid = prev.txid() + inp.vout = 0 + # InputScope serializes non_witness_utxo before PSBTv2 prevout fields. + inp.non_witness_utxo = prev + psbt.add_input(inp) + out = OutputScope() + out.value = 1000 + out.script_pubkey = Script(b"\x51") + psbt.add_output(out) + + parsed = PSBT.parse(psbt.serialize(), compress=CompressMode.PARTIAL) + assert parsed.inputs[0].non_witness_utxo is None + assert parsed.inputs[0]._utxo.value == 1234 + assert parsed.verify() From 85a60670079d4e8f2d5b9ec06fd3d56ea87ee908 Mon Sep 17 00:00:00 2001 From: odudex Date: Thu, 14 May 2026 10:47:02 -0300 Subject: [PATCH 7/8] fix: restore old MicroPython-compatible PSBT errors Replace new PSBTv2/PSET f-strings with old-style formatting so the branch remains parseable on older MicroPython versions. --- src/embit/liquid/pset.py | 4 ++-- src/embit/psbt.py | 26 +++++++++++++++++--------- src/embit/psbtview.py | 5 +++-- 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/embit/liquid/pset.py b/src/embit/liquid/pset.py index b613ba95..dbac9e13 100644 --- a/src/embit/liquid/pset.py +++ b/src/embit/liquid/pset.py @@ -508,11 +508,11 @@ def _validate_v2_output(cls, out, i): """PSET allows value_commitment as an alternative to value (blinded outputs).""" if out.value is None and not getattr(out, "value_commitment", None): raise PSBTError( - f"PSBTv2 output {i} missing required PSBT_OUT_AMOUNT (0x03)" + "PSBTv2 output %d missing required PSBT_OUT_AMOUNT (0x03)" % i ) if out.script_pubkey is None: raise PSBTError( - f"PSBTv2 output {i} missing required PSBT_OUT_SCRIPT (0x04)" + "PSBTv2 output %d missing required PSBT_OUT_SCRIPT (0x04)" % i ) def unblind(self, blinding_key): diff --git a/src/embit/psbt.py b/src/embit/psbt.py index 7c4afa31..7306c283 100644 --- a/src/embit/psbt.py +++ b/src/embit/psbt.py @@ -403,7 +403,9 @@ def read_value(self, stream, k, version=None): raise PSBTError("PSBT_IN_REQUIRED_TIME_LOCKTIME must be 4 bytes") locktime = int.from_bytes(v, "little") if locktime < LOCKTIME_THRESHOLD: - raise PSBTError(f"Time-based locktime must be >= {LOCKTIME_THRESHOLD}") + raise PSBTError( + "Time-based locktime must be >= %d" % LOCKTIME_THRESHOLD + ) self.required_time_locktime = locktime # PSBT_IN_REQUIRED_HEIGHT_LOCKTIME @@ -419,7 +421,8 @@ def read_value(self, stream, k, version=None): locktime = int.from_bytes(v, "little") if locktime >= LOCKTIME_THRESHOLD or locktime == 0: raise PSBTError( - f"Height-based locktime must be > 0 and < {LOCKTIME_THRESHOLD}" + "Height-based locktime must be > 0 and < %d" + % LOCKTIME_THRESHOLD ) self.required_height_locktime = locktime @@ -796,11 +799,11 @@ def _validate_v2_output(cls, out, i): Subclasses (e.g. PSET) may override this to accept alternative fields.""" if out.value is None: raise PSBTError( - f"PSBTv2 output {i} missing required PSBT_OUT_AMOUNT (0x03)" + "PSBTv2 output %d missing required PSBT_OUT_AMOUNT (0x03)" % i ) if out.script_pubkey is None: raise PSBTError( - f"PSBTv2 output {i} missing required PSBT_OUT_SCRIPT (0x04)" + "PSBTv2 output %d missing required PSBT_OUT_SCRIPT (0x04)" % i ) def __init__(self, tx=None, unknown=None, version=None): @@ -1033,7 +1036,9 @@ def read_from(cls, stream, compress=CompressMode.KEEP_ALL): break value = read_string(stream) if key in global_kvs: - raise PSBTError(f"Duplicated global key: {hexlify(key).decode()}") + raise PSBTError( + "Duplicated global key: %s" % hexlify(key).decode() + ) global_kvs[key] = value # Determine PSBT version from PSBT_GLOBAL_VERSION (0xfb) @@ -1050,7 +1055,7 @@ def read_from(cls, stream, compress=CompressMode.KEEP_ALL): ) else: raise PSBTError( - f"Unsupported PSBT_GLOBAL_VERSION value: {parsed_version}" + "Unsupported PSBT_GLOBAL_VERSION value: %d" % parsed_version ) if version == 2: # PSBTv2 @@ -1081,7 +1086,8 @@ def read_from(cls, stream, compress=CompressMode.KEEP_ALL): for k_v2_only in v2_only_global_keys: if k_v2_only in global_kvs: raise PSBTError( - f"Global key {hexlify(k_v2_only).decode()} is not allowed in PSBTv0" + "Global key %s is not allowed in PSBTv0" + % hexlify(k_v2_only).decode() ) tx_bytes = global_kvs.pop(b"\x00") # Remove so it's not in unknown @@ -1107,11 +1113,13 @@ def read_from(cls, stream, compress=CompressMode.KEEP_ALL): for i, inp in enumerate(psbt.inputs): if inp.txid is None: raise PSBTError( - f"PSBTv2 input {i} missing required PSBT_IN_PREVIOUS_TXID (0x0e)" + "PSBTv2 input %d missing required " + "PSBT_IN_PREVIOUS_TXID (0x0e)" % i ) if inp.vout is None: raise PSBTError( - f"PSBTv2 input {i} missing required PSBT_IN_OUTPUT_INDEX (0x0f)" + "PSBTv2 input %d missing required " + "PSBT_IN_OUTPUT_INDEX (0x0f)" % i ) parsed_outputs = [] diff --git a/src/embit/psbtview.py b/src/embit/psbtview.py index 03b93bff..ccc9b865 100644 --- a/src/embit/psbtview.py +++ b/src/embit/psbtview.py @@ -461,7 +461,8 @@ def _determine_locktime_v2(self): height_locktime = int.from_bytes(v_height, "little") if height_locktime == 0 or height_locktime >= LOCKTIME_THRESHOLD: raise PSBTError( - f"Height-based locktime must be > 0 and < {LOCKTIME_THRESHOLD}" + "Height-based locktime must be > 0 and < %d" + % LOCKTIME_THRESHOLD ) height_locktimes.append(height_locktime) has_requirement = True @@ -471,7 +472,7 @@ def _determine_locktime_v2(self): time_locktime = int.from_bytes(v_time, "little") if time_locktime < LOCKTIME_THRESHOLD: raise PSBTError( - f"Time-based locktime must be >= {LOCKTIME_THRESHOLD}" + "Time-based locktime must be >= %d" % LOCKTIME_THRESHOLD ) time_locktimes.append(time_locktime) has_requirement = True From 4076252d584caaebf62586446182e43de74248d1 Mon Sep 17 00:00:00 2001 From: odudex Date: Thu, 14 May 2026 11:36:05 -0300 Subject: [PATCH 8/8] fix(psbt): avoid signed byte conversion kwargs Replace signed=True usage in BIP370 signed integer parsing and serialization with helper functions compatible with older MicroPython byte conversion APIs. This keeps PSBTv2 transaction versions and output amounts spec-compliant without changing regular keyword-argument call sites. --- src/embit/psbt.py | 17 ++++++++++++----- src/embit/psbtview.py | 12 +++++++----- src/embit/transaction.py | 29 +++++++++++++++++++++++------ 3 files changed, 42 insertions(+), 16 deletions(-) diff --git a/src/embit/psbt.py b/src/embit/psbt.py index 7306c283..71eff73c 100644 --- a/src/embit/psbt.py +++ b/src/embit/psbt.py @@ -1,5 +1,12 @@ from collections import OrderedDict -from .transaction import Transaction, TransactionOutput, TransactionInput, SIGHASH +from .transaction import ( + Transaction, + TransactionOutput, + TransactionInput, + SIGHASH, + _signed_from_bytes, + _signed_to_bytes, +) from . import compact from . import bip32 from . import ec @@ -693,7 +700,7 @@ def read_value(self, stream, k, version=None): raise PSBTError("PSBT_OUT_AMOUNT must be 8 bytes") if self.value is not None: raise PSBTError("Duplicated PSBT_OUT_AMOUNT") - self.value = int.from_bytes(v, "little", signed=True) + self.value = _signed_from_bytes(v) elif k == b"\x04": if version != 2: raise PSBTError("PSBT_OUT_SCRIPT not allowed in PSBTv0") @@ -738,7 +745,7 @@ def write_to(self, stream, skip_separator=False, version=None, **kwargs) -> int: if self.value is not None: r += ser_string(stream, b"\x03") # BIP370: PSBT_OUT_AMOUNT is a signed 64-bit integer - r += ser_string(stream, self.value.to_bytes(8, "little", signed=True)) + r += ser_string(stream, _signed_to_bytes(self.value, 8)) if self.script_pubkey is not None: r += ser_string(stream, b"\x04") r += self.script_pubkey.write_to(stream) @@ -971,7 +978,7 @@ def write_to(self, stream) -> int: ) r += ser_string(stream, b"\x02") # BIP370: PSBT_GLOBAL_TX_VERSION is a signed int32 - r += ser_string(stream, self.tx_version.to_bytes(4, "little", signed=True)) + r += ser_string(stream, _signed_to_bytes(self.tx_version, 4)) if self.locktime is not None: r += ser_string(stream, b"\x03") r += ser_string(stream, self.locktime.to_bytes(4, "little")) @@ -1185,7 +1192,7 @@ def parse_unknowns(self): if len(v) != 4: raise PSBTError("PSBT_GLOBAL_TX_VERSION must be 4 bytes") # BIP370: PSBT_GLOBAL_TX_VERSION is a signed int32 - self.tx_version = int.from_bytes(v, "little", signed=True) + self.tx_version = _signed_from_bytes(v) elif k == b"\x03": if self.version == 2: v = self.unknown.pop(k) diff --git a/src/embit/psbtview.py b/src/embit/psbtview.py index ccc9b865..967249ed 100644 --- a/src/embit/psbtview.py +++ b/src/embit/psbtview.py @@ -40,6 +40,8 @@ SIGHASH, hash_amounts, hash_script_pubkeys, + _signed_from_bytes, + _signed_to_bytes, ) @@ -411,7 +413,7 @@ def vout(self, i, compress=None): self.seek_to_scope(self.num_inputs + i) v = self.get_value(b"\x03", from_current=True) - value = int.from_bytes(v, "little") + value = _signed_from_bytes(v) self.seek_to_scope(self.num_inputs + i) v = self.get_value(b"\x04", from_current=True) @@ -508,7 +510,7 @@ def tx_version(self): if len(v) != 4: raise PSBTError("Invalid PSBT_GLOBAL_TX_VERSION length") # BIP370: PSBT_GLOBAL_TX_VERSION is a signed int32 - self._tx_version = int.from_bytes(v, "little", signed=True) + self._tx_version = _signed_from_bytes(v) return self._tx_version def seek_to_value(self, key_start, from_current=False): @@ -598,7 +600,7 @@ def sighash_taproot( sh, anyonecanpay = SIGHASH.check(sighash) h = hashes.tagged_hash_init("TapSighash", b"\x00") h.update(bytes([sighash])) - h.update(self.tx_version.to_bytes(4, "little", signed=True)) + h.update(_signed_to_bytes(self.tx_version, 4)) h.update(self.locktime.to_bytes(4, "little")) if not anyonecanpay: h.update(self.hash_prevouts()) @@ -646,7 +648,7 @@ def sighash_segwit(self, input_index, script_pubkey, value, sighash=SIGHASH.ALL) inp = self.vin(input_index) zero = b"\x00" * 32 # for sighashes h = hashlib.sha256() - h.update(self.tx_version.to_bytes(4, "little", signed=True)) + h.update(_signed_to_bytes(self.tx_version, 4)) if anyonecanpay: h.update(zero) else: @@ -686,7 +688,7 @@ def sighash_legacy(self, input_index, script_pubkey, sighash=SIGHASH.ALL): return b"\x00" * 31 + b"\x01" h = hashlib.sha256() - h.update(self.tx_version.to_bytes(4, "little", signed=True)) + h.update(_signed_to_bytes(self.tx_version, 4)) # ANYONECANPAY - only one input is serialized if anyonecanpay: h.update(compact.to_bytes(1)) diff --git a/src/embit/transaction.py b/src/embit/transaction.py index 083c7f5a..bab053c0 100644 --- a/src/embit/transaction.py +++ b/src/embit/transaction.py @@ -33,6 +33,23 @@ def check(cls, sighash: int): # util functions +def _signed_from_bytes(b): + res = int.from_bytes(b, "little") + bits = 8 * len(b) + if bits and res >= (1 << (bits - 1)): + res -= 1 << bits + return res + + +def _signed_to_bytes(i, length): + bits = 8 * length + if i < -(1 << (bits - 1)) or i >= (1 << (bits - 1)): + raise OverflowError("int too big to convert") + if i < 0: + i += 1 << bits + return i.to_bytes(length, "little") + + def hash_amounts(amounts): h = hashlib.sha256() for a in amounts: @@ -76,7 +93,7 @@ def is_segwit(self): def write_to(self, stream): """Returns the byte serialization of the transaction""" - res = stream.write(self.version.to_bytes(4, "little", signed=True)) + res = stream.write(_signed_to_bytes(self.version, 4)) if self.is_segwit: res += stream.write(b"\x00\x01") # segwit marker and flag res += stream.write(compact.to_bytes(len(self.vin))) @@ -93,7 +110,7 @@ def write_to(self, stream): def hash(self): h = hashlib.sha256() - h.update(self.version.to_bytes(4, "little", signed=True)) + h.update(_signed_to_bytes(self.version, 4)) h.update(compact.to_bytes(len(self.vin))) for inp in self.vin: h.update(inp.serialize()) @@ -144,7 +161,7 @@ def read_vout(cls, stream, idx): @classmethod def read_from(cls, stream): - ver = int.from_bytes(stream.read(4), "little", signed=True) + ver = _signed_from_bytes(stream.read(4)) num_vin = compact.read_from(stream) # if num_vin is zero it is a segwit transaction is_segwit = num_vin == 0 @@ -221,7 +238,7 @@ def sighash_taproot( sh, anyonecanpay = SIGHASH.check(sighash) h = hashes.tagged_hash_init("TapSighash", b"\x00") h.update(bytes([sighash])) - h.update(self.version.to_bytes(4, "little", signed=True)) + h.update(_signed_to_bytes(self.version, 4)) h.update(self.locktime.to_bytes(4, "little")) if not anyonecanpay: h.update(self.hash_prevouts()) @@ -268,7 +285,7 @@ def sighash_segwit(self, input_index, script_pubkey, value, sighash=SIGHASH.ALL) inp = self.vin[input_index] zero = b"\x00" * 32 # for sighashes h = hashlib.sha256() - h.update(self.version.to_bytes(4, "little", signed=True)) + h.update(_signed_to_bytes(self.version, 4)) if anyonecanpay: h.update(zero) else: @@ -307,7 +324,7 @@ def sighash_legacy(self, input_index, script_pubkey, sighash=SIGHASH.ALL): return b"\x00" * 31 + b"\x01" h = hashlib.sha256() - h.update(self.version.to_bytes(4, "little", signed=True)) + h.update(_signed_to_bytes(self.version, 4)) # ANYONECANPAY - only one input is serialized if anyonecanpay: h.update(compact.to_bytes(1))