Skip to content

jmwallet.wallet.psbt

jmwallet.wallet.psbt

Strict BIP174 PSBT v0 and BIP370 PSBT v2 parsing and record-preserving updates.

Attributes

LOCKTIME_THRESHOLD = 500000000 module-attribute

PSBT_GLOBAL_FALLBACK_LOCKTIME = 3 module-attribute

PSBT_GLOBAL_INPUT_COUNT = 4 module-attribute

PSBT_GLOBAL_OUTPUT_COUNT = 5 module-attribute

PSBT_GLOBAL_TX_MODIFIABLE = 6 module-attribute

PSBT_GLOBAL_TX_VERSION = 2 module-attribute

PSBT_GLOBAL_UNSIGNED_TX = 0 module-attribute

PSBT_GLOBAL_VERSION = 251 module-attribute

PSBT_GLOBAL_XPUB = 1 module-attribute

PSBT_IN_BIP32_DERIVATION = 6 module-attribute

PSBT_IN_FINAL_SCRIPTSIG = 7 module-attribute

PSBT_IN_FINAL_SCRIPTWITNESS = 8 module-attribute

PSBT_IN_NON_WITNESS_UTXO = 0 module-attribute

PSBT_IN_OUTPUT_INDEX = 15 module-attribute

PSBT_IN_PARTIAL_SIG = 2 module-attribute

PSBT_IN_PREVIOUS_TXID = 14 module-attribute

PSBT_IN_PROPRIETARY = 252 module-attribute

PSBT_IN_REDEEM_SCRIPT = 4 module-attribute

PSBT_IN_REQUIRED_HEIGHT_LOCKTIME = 18 module-attribute

PSBT_IN_REQUIRED_TIME_LOCKTIME = 17 module-attribute

PSBT_IN_SEQUENCE = 16 module-attribute

PSBT_IN_SIGHASH_TYPE = 3 module-attribute

PSBT_IN_WITNESS_SCRIPT = 5 module-attribute

PSBT_IN_WITNESS_UTXO = 1 module-attribute

PSBT_MAGIC = b'psbt\xff' module-attribute

PSBT_OUT_AMOUNT = 3 module-attribute

PSBT_OUT_BIP32_DERIVATION = 2 module-attribute

PSBT_OUT_PROPRIETARY = 252 module-attribute

PSBT_OUT_REDEEM_SCRIPT = 0 module-attribute

PSBT_OUT_SCRIPT = 4 module-attribute

PSBT_OUT_WITNESS_SCRIPT = 1 module-attribute

PSBT_VERSION_0 = 0 module-attribute

PSBT_VERSION_2 = 2 module-attribute

SEQUENCE_FINAL = 4294967295 module-attribute

TX_MODIFIABLE_HAS_SIGHASH_SINGLE = 4 module-attribute

TX_MODIFIABLE_INPUTS = 1 module-attribute

TX_MODIFIABLE_OUTPUTS = 2 module-attribute

Classes

BIP32KeyOrigin dataclass

A BIP32 public key and its master fingerprint and derivation path.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
137
138
139
140
141
142
143
@dataclass(frozen=True)
class BIP32KeyOrigin:
    """A BIP32 public key and its master fingerprint and derivation path."""

    pubkey: bytes
    fingerprint: bytes
    path: tuple[int, ...]
Attributes
fingerprint: bytes instance-attribute
path: tuple[int, ...] instance-attribute
pubkey: bytes instance-attribute

PSBTError

Bases: ValueError

Raised when a PSBT violates BIP174 serialization requirements.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
91
92
class PSBTError(ValueError):
    """Raised when a PSBT violates BIP174 serialization requirements."""

PSBTKeyValue dataclass

An ordered raw PSBT key/value record.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
 95
 96
 97
 98
 99
100
@dataclass(frozen=True)
class PSBTKeyValue:
    """An ordered raw PSBT key/value record."""

    key: bytes
    value: bytes
Attributes
key: bytes instance-attribute
value: bytes instance-attribute

PSBTMap dataclass

A PSBT map retaining record order and unknown records.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
@dataclass
class PSBTMap:
    """A PSBT map retaining record order and unknown records."""

    records: list[PSBTKeyValue] = field(default_factory=list)

    def append(self, key: bytes, value: bytes) -> None:
        """Append a unique, nonempty raw record to this map."""
        if not key:
            raise PSBTError("PSBT map keys must not be empty")
        if any(record.key == key for record in self.records):
            raise PSBTError(f"Duplicate PSBT key: {key.hex()}")
        self.records.append(PSBTKeyValue(key=key, value=value))

    def serialize(self) -> bytes:
        """Serialize this map with canonical CompactSize lengths."""
        result = bytearray()
        for record in self.records:
            result.extend(encode_varint(len(record.key)))
            result.extend(record.key)
            result.extend(encode_varint(len(record.value)))
            result.extend(record.value)
        result.append(0)
        return bytes(result)
Attributes
records: list[PSBTKeyValue] = field(default_factory=list) class-attribute instance-attribute
Methods:
append(key: bytes, value: bytes) -> None

Append a unique, nonempty raw record to this map.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
109
110
111
112
113
114
115
def append(self, key: bytes, value: bytes) -> None:
    """Append a unique, nonempty raw record to this map."""
    if not key:
        raise PSBTError("PSBT map keys must not be empty")
    if any(record.key == key for record in self.records):
        raise PSBTError(f"Duplicate PSBT key: {key.hex()}")
    self.records.append(PSBTKeyValue(key=key, value=value))
serialize() -> bytes

Serialize this map with canonical CompactSize lengths.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
117
118
119
120
121
122
123
124
125
126
def serialize(self) -> bytes:
    """Serialize this map with canonical CompactSize lengths."""
    result = bytearray()
    for record in self.records:
        result.extend(encode_varint(len(record.key)))
        result.extend(record.key)
        result.extend(encode_varint(len(record.value)))
        result.extend(record.value)
    result.append(0)
    return bytes(result)

ParsedPSBT dataclass

A parsed BIP174 PSBT v0 or BIP370 PSBT v2, retaining all raw map records.

transaction is the unsigned transaction described by the PSBT: parsed from PSBT_GLOBAL_UNSIGNED_TX for v0 and reconstructed from the BIP370 fields for v2, with the locktime derived as BIP370 specifies. unsigned_tx is its serialization; for v2 it is a reconstruction and is not part of the PSBT bytes.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
@dataclass
class ParsedPSBT:
    """A parsed BIP174 PSBT v0 or BIP370 PSBT v2, retaining all raw map records.

    ``transaction`` is the unsigned transaction described by the PSBT: parsed from
    ``PSBT_GLOBAL_UNSIGNED_TX`` for v0 and reconstructed from the BIP370 fields for
    v2, with the locktime derived as BIP370 specifies. ``unsigned_tx`` is its
    serialization; for v2 it is a reconstruction and is not part of the PSBT bytes.
    """

    unsigned_tx: bytes
    transaction: ParsedTransaction
    global_map: PSBTMap
    input_maps: list[PSBTMap]
    output_maps: list[PSBTMap]
    version: int = PSBT_VERSION_0

    def serialize(self) -> bytes:
        """Serialize the PSBT while preserving all map record order."""
        result = bytearray(PSBT_MAGIC)
        result.extend(self.global_map.serialize())
        for input_map in self.input_maps:
            result.extend(input_map.serialize())
        for output_map in self.output_maps:
            result.extend(output_map.serialize())
        return bytes(result)

    def append_input_key_value(self, input_index: int, key: bytes, value: bytes) -> None:
        """Append a valid unique record to an input map."""
        if input_index < 0:
            raise PSBTError(f"PSBT input index out of range: {input_index}")
        try:
            input_map = self.input_maps[input_index]
        except IndexError as error:
            raise PSBTError(f"PSBT input index out of range: {input_index}") from error
        _validate_key("input", key)
        _validate_map_records(
            "input", PSBTMap(records=[PSBTKeyValue(key=key, value=value)]), self.version
        )
        input_map.append(key, value)
Attributes
global_map: PSBTMap instance-attribute
input_maps: list[PSBTMap] instance-attribute
output_maps: list[PSBTMap] instance-attribute
transaction: ParsedTransaction instance-attribute
unsigned_tx: bytes instance-attribute
version: int = PSBT_VERSION_0 class-attribute instance-attribute
Methods:
append_input_key_value(input_index: int, key: bytes, value: bytes) -> None

Append a valid unique record to an input map.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
173
174
175
176
177
178
179
180
181
182
183
184
185
def append_input_key_value(self, input_index: int, key: bytes, value: bytes) -> None:
    """Append a valid unique record to an input map."""
    if input_index < 0:
        raise PSBTError(f"PSBT input index out of range: {input_index}")
    try:
        input_map = self.input_maps[input_index]
    except IndexError as error:
        raise PSBTError(f"PSBT input index out of range: {input_index}") from error
    _validate_key("input", key)
    _validate_map_records(
        "input", PSBTMap(records=[PSBTKeyValue(key=key, value=value)]), self.version
    )
    input_map.append(key, value)
serialize() -> bytes

Serialize the PSBT while preserving all map record order.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
163
164
165
166
167
168
169
170
171
def serialize(self) -> bytes:
    """Serialize the PSBT while preserving all map record order."""
    result = bytearray(PSBT_MAGIC)
    result.extend(self.global_map.serialize())
    for input_map in self.input_maps:
        result.extend(input_map.serialize())
    for output_map in self.output_maps:
        result.extend(output_map.serialize())
    return bytes(result)

WitnessUTXO dataclass

The amount and scriptPubKey contained in a PSBT witness UTXO record.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
129
130
131
132
133
134
@dataclass(frozen=True)
class WitnessUTXO:
    """The amount and scriptPubKey contained in a PSBT witness UTXO record."""

    value: int
    script_pubkey: bytes
Attributes
script_pubkey: bytes instance-attribute
value: int instance-attribute

Functions:

parse_bip32_derivation(key: bytes, value: bytes) -> BIP32KeyOrigin

Parse a BIP174 BIP32 derivation key/value pair.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
375
376
377
378
379
380
381
382
383
384
385
386
387
def parse_bip32_derivation(key: bytes, value: bytes) -> BIP32KeyOrigin:
    """Parse a BIP174 BIP32 derivation key/value pair."""
    if len(key) != 34:
        raise PSBTError("BIP32 derivation key must contain a type byte and 33-byte public key")
    pubkey = key[1:]
    if pubkey[0] not in (0x02, 0x03):
        raise PSBTError("BIP32 derivation key must contain a compressed public key")
    _validate_key_origin_value(value, "BIP32 derivation")
    path = tuple(
        int.from_bytes(value[offset : offset + 4], "little", signed=False)
        for offset in range(4, len(value), 4)
    )
    return BIP32KeyOrigin(pubkey=pubkey, fingerprint=value[:4], path=path)

parse_psbt(data: bytes) -> ParsedPSBT

Parse a strict, complete BIP174 PSBT v0 or BIP370 PSBT v2 binary payload.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
188
189
190
191
192
193
194
195
196
197
198
199
200
def parse_psbt(data: bytes) -> ParsedPSBT:
    """Parse a strict, complete BIP174 PSBT v0 or BIP370 PSBT v2 binary payload."""
    if not data.startswith(PSBT_MAGIC):
        raise PSBTError("Invalid PSBT magic bytes")

    offset = len(PSBT_MAGIC)
    global_map, offset = _read_map(data, offset, "global")
    version = _read_psbt_version(global_map)
    _validate_map_records("global", global_map, version)

    if version == PSBT_VERSION_2:
        return _parse_psbt_v2(data, offset, global_map)
    return _parse_psbt_v0(data, offset, global_map)

parse_witness_utxo(value: bytes) -> WitnessUTXO

Parse a BIP174 witness UTXO value with exact consumption.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def parse_witness_utxo(value: bytes) -> WitnessUTXO:
    """Parse a BIP174 witness UTXO value with exact consumption."""
    if len(value) < 8:
        raise PSBTError("Truncated witness UTXO value")
    amount = int.from_bytes(value[:8], "little", signed=False)
    if amount > MAX_MONEY:
        raise PSBTError("Witness UTXO amount exceeds Bitcoin MAX_MONEY")
    script_length, offset = _read_compact_size(value, 8, "witness UTXO script length")
    remaining = len(value) - offset
    if script_length > remaining:
        raise PSBTError("Truncated witness UTXO scriptPubKey")
    if script_length != remaining:
        raise PSBTError("Trailing data after witness UTXO scriptPubKey")
    return WitnessUTXO(value=amount, script_pubkey=value[offset:])