Skip to content

jmwallet.wallet.psbt

jmwallet.wallet.psbt

Strict BIP174 PSBT v0 parsing and record-preserving updates.

Attributes

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_PARTIAL_SIG = 2 module-attribute

PSBT_IN_PROPRIETARY = 252 module-attribute

PSBT_IN_REDEEM_SCRIPT = 4 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_BIP32_DERIVATION = 2 module-attribute

PSBT_OUT_PROPRIETARY = 252 module-attribute

PSBT_OUT_REDEEM_SCRIPT = 0 module-attribute

PSBT_OUT_WITNESS_SCRIPT = 1 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
82
83
84
85
86
87
88
@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
36
37
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
40
41
42
43
44
45
@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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@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
54
55
56
57
58
59
60
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
62
63
64
65
66
67
68
69
70
71
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, retaining all raw map records.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
@dataclass
class ParsedPSBT:
    """A parsed BIP174 PSBT v0, retaining all raw map records."""

    unsigned_tx: bytes
    transaction: ParsedTransaction
    global_map: PSBTMap
    input_maps: list[PSBTMap]
    output_maps: list[PSBTMap]

    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)]))
        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
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
111
112
113
114
115
116
117
118
119
120
121
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)]))
    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
101
102
103
104
105
106
107
108
109
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
74
75
76
77
78
79
@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
178
179
180
181
182
183
184
185
186
187
188
189
190
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 binary payload.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def parse_psbt(data: bytes) -> ParsedPSBT:
    """Parse a strict, complete BIP174 PSBT v0 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")
    _validate_map_records("global", global_map)
    unsigned_tx = _get_unsigned_transaction(global_map)
    _validate_version(global_map)

    try:
        transaction = parse_transaction_bytes(unsigned_tx)
    except Exception as error:
        raise PSBTError(f"Invalid PSBT unsigned transaction: {error}") from error
    if transaction.has_witness:
        raise PSBTError("PSBT unsigned transaction must not contain witness data")
    if any(tx_input.scriptsig for tx_input in transaction.inputs):
        raise PSBTError("PSBT unsigned transaction must have empty scriptSigs")

    input_maps, offset = _read_expected_maps(data, offset, len(transaction.inputs), "input")
    output_maps, offset = _read_expected_maps(data, offset, len(transaction.outputs), "output")
    for input_map in input_maps:
        _validate_map_records("input", input_map)
    for output_map in output_maps:
        _validate_map_records("output", output_map)
    if offset != len(data):
        raise PSBTError("Trailing data after PSBT maps")

    return ParsedPSBT(
        unsigned_tx=unsigned_tx,
        transaction=transaction,
        global_map=global_map,
        input_maps=input_maps,
        output_maps=output_maps,
    )

parse_witness_utxo(value: bytes) -> WitnessUTXO

Parse a BIP174 witness UTXO value with exact consumption.

Source code in jmwallet/src/jmwallet/wallet/psbt.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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:])