Skip to content

jmwallet.wallet.signing

jmwallet.wallet.signing

Bitcoin transaction signing utilities for P2WPKH and P2WSH inputs.

Uses the unified transaction models from jmcore.bitcoin. The signing functions access byte-oriented properties (txid_le, sequence_bytes, version_bytes, locktime_bytes) to construct the exact BIP-143 sighash preimage.

Attributes

Transaction = ParsedTransaction module-attribute

__all__ = ['ParsedTransaction', 'Transaction', 'TransactionSigningError', 'TxInput', 'TxOutput', 'compute_sighash_segwit', 'create_p2wpkh_script_code', 'create_p2wsh_witness_stack', 'create_witness_stack', 'deserialize_transaction', 'encode_varint', 'hash256', 'read_varint', 'sign_p2wpkh_input', 'sign_p2wsh_input', 'verify_p2wpkh_signature'] module-attribute

read_varint = decode_varint module-attribute

Classes

ParsedTransaction

Parsed Bitcoin transaction with typed inputs and outputs.

Provides dual accessors for int and bytes representations of version and locktime (needed by BIP-143 sighash construction).

Source code in jmcore/src/jmcore/bitcoin.py
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
@dataclass
class ParsedTransaction:
    """Parsed Bitcoin transaction with typed inputs and outputs.

    Provides dual accessors for int and bytes representations of version
    and locktime (needed by BIP-143 sighash construction).
    """

    version: int
    inputs: list[TxInput]
    outputs: list[TxOutput]
    witnesses: list[list[bytes]]
    locktime: int
    has_witness: bool

    # --- bytes accessors (for BIP-143 sighash) ------------------------------

    @property
    def version_bytes(self) -> bytes:
        """Version as 4-byte little-endian bytes."""
        return struct.pack("<I", self.version)

    @property
    def locktime_bytes(self) -> bytes:
        """Locktime as 4-byte little-endian bytes."""
        return struct.pack("<I", self.locktime)
Attributes
has_witness: bool instance-attribute
inputs: list[TxInput] instance-attribute
locktime: int instance-attribute
locktime_bytes: bytes property

Locktime as 4-byte little-endian bytes.

outputs: list[TxOutput] instance-attribute
version: int instance-attribute
version_bytes: bytes property

Version as 4-byte little-endian bytes.

witnesses: list[list[bytes]] instance-attribute

TransactionSigningError

Bases: Exception

Source code in jmwallet/src/jmwallet/wallet/signing.py
31
32
class TransactionSigningError(Exception):
    pass

TxInput

Unified transaction input model.

Stores data in canonical byte form internally. Provides dual accessors for the two dominant usage patterns in the codebase:

  • String pattern (RPC / human-readable): txid (big-endian hex), scriptsig_hex, scriptpubkey_hex, sequence (int).
  • Bytes pattern (BIP-143 signing): txid_le (little-endian bytes), scriptsig (bytes), sequence_bytes (4-byte LE bytes).
Construction helpers
  • TxInput.from_hex(txid_hex, vout, ...) — build from big-endian hex txid (the format returned by Bitcoin Core RPC).
  • Direct TxInput(txid_le=..., vout=..., ...) — build from raw LE bytes (the format found inside serialised transactions).
Source code in jmcore/src/jmcore/bitcoin.py
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
@dataclass
class TxInput:
    """Unified transaction input model.

    Stores data in canonical byte form internally.  Provides dual accessors for
    the two dominant usage patterns in the codebase:

    * **String pattern** (RPC / human-readable): ``txid`` (big-endian hex),
      ``scriptsig_hex``, ``scriptpubkey_hex``, ``sequence`` (int).
    * **Bytes pattern** (BIP-143 signing): ``txid_le`` (little-endian bytes),
      ``scriptsig`` (bytes), ``sequence_bytes`` (4-byte LE bytes).

    Construction helpers
    --------------------
    * ``TxInput.from_hex(txid_hex, vout, ...)`` — build from big-endian hex
      txid (the format returned by Bitcoin Core RPC).
    * Direct ``TxInput(txid_le=..., vout=..., ...)`` — build from raw LE bytes
      (the format found inside serialised transactions).
    """

    # --- canonical fields (stored as-is) ------------------------------------
    txid_le: bytes  # 32-byte txid in little-endian (wire / internal format)
    vout: int
    scriptsig: bytes = b""
    sequence: int = 0xFFFFFFFF
    value: int = 0  # Optional: UTXO value (needed by tx builder / sighash)
    scriptpubkey: bytes = b""  # Optional: prevout scriptPubKey

    # --- string accessors (big-endian hex) ----------------------------------

    @property
    def txid(self) -> str:
        """Transaction ID as big-endian hex (RPC / display format)."""
        return self.txid_le[::-1].hex()

    @property
    def scriptsig_hex(self) -> str:
        """ScriptSig as hex string."""
        return self.scriptsig.hex()

    @property
    def scriptpubkey_hex(self) -> str:
        """ScriptPubKey of the prevout as hex string."""
        return self.scriptpubkey.hex()

    # --- bytes accessors (for BIP-143 sighash) ------------------------------

    @property
    def sequence_bytes(self) -> bytes:
        """Sequence as 4-byte little-endian bytes (for BIP-143 preimage)."""
        return struct.pack("<I", self.sequence)

    # --- dict-like access (backward compat during migration) ----------------

    def __getitem__(self, key: str) -> Any:
        """Allow ``inp["txid"]`` style access for backward compatibility."""
        if key == "txid":
            return self.txid
        if key == "vout":
            return self.vout
        if key == "scriptsig":
            return self.scriptsig_hex
        if key == "sequence":
            return self.sequence
        if key == "value":
            return self.value
        if key == "scriptpubkey":
            return self.scriptpubkey_hex
        raise KeyError(key)

    def get(self, key: str, default: Any = None) -> Any:
        """Allow ``inp.get("key", default)`` for backward compatibility."""
        try:
            return self[key]
        except KeyError:
            return default

    # --- factories ----------------------------------------------------------

    @classmethod
    def from_hex(
        cls,
        txid: str,
        vout: int,
        *,
        scriptsig: str = "",
        sequence: int = 0xFFFFFFFF,
        value: int = 0,
        scriptpubkey: str = "",
    ) -> TxInput:
        """Create from big-endian hex txid (the RPC / display format).

        Args:
            txid: 64-char hex string (big-endian, as returned by RPC)
            vout: Output index
            scriptsig: ScriptSig hex (default empty)
            sequence: Sequence number (default 0xFFFFFFFF)
            value: UTXO value in satoshis (optional, for tx builder)
            scriptpubkey: Prevout scriptPubKey hex (optional)
        """
        return cls(
            txid_le=bytes.fromhex(txid)[::-1],
            vout=vout,
            scriptsig=bytes.fromhex(scriptsig) if scriptsig else b"",
            sequence=sequence,
            value=value,
            scriptpubkey=bytes.fromhex(scriptpubkey) if scriptpubkey else b"",
        )
Attributes
scriptpubkey: bytes = b'' class-attribute instance-attribute
scriptpubkey_hex: str property

ScriptPubKey of the prevout as hex string.

scriptsig: bytes = b'' class-attribute instance-attribute
scriptsig_hex: str property

ScriptSig as hex string.

sequence: int = 4294967295 class-attribute instance-attribute
sequence_bytes: bytes property

Sequence as 4-byte little-endian bytes (for BIP-143 preimage).

txid: str property

Transaction ID as big-endian hex (RPC / display format).

txid_le: bytes instance-attribute
value: int = 0 class-attribute instance-attribute
vout: int instance-attribute
Functions
__getitem__(key: str) -> Any

Allow inp["txid"] style access for backward compatibility.

Source code in jmcore/src/jmcore/bitcoin.py
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
def __getitem__(self, key: str) -> Any:
    """Allow ``inp["txid"]`` style access for backward compatibility."""
    if key == "txid":
        return self.txid
    if key == "vout":
        return self.vout
    if key == "scriptsig":
        return self.scriptsig_hex
    if key == "sequence":
        return self.sequence
    if key == "value":
        return self.value
    if key == "scriptpubkey":
        return self.scriptpubkey_hex
    raise KeyError(key)
from_hex(txid: str, vout: int, *, scriptsig: str = '', sequence: int = 4294967295, value: int = 0, scriptpubkey: str = '') -> TxInput classmethod

Create from big-endian hex txid (the RPC / display format).

Args: txid: 64-char hex string (big-endian, as returned by RPC) vout: Output index scriptsig: ScriptSig hex (default empty) sequence: Sequence number (default 0xFFFFFFFF) value: UTXO value in satoshis (optional, for tx builder) scriptpubkey: Prevout scriptPubKey hex (optional)

Source code in jmcore/src/jmcore/bitcoin.py
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
@classmethod
def from_hex(
    cls,
    txid: str,
    vout: int,
    *,
    scriptsig: str = "",
    sequence: int = 0xFFFFFFFF,
    value: int = 0,
    scriptpubkey: str = "",
) -> TxInput:
    """Create from big-endian hex txid (the RPC / display format).

    Args:
        txid: 64-char hex string (big-endian, as returned by RPC)
        vout: Output index
        scriptsig: ScriptSig hex (default empty)
        sequence: Sequence number (default 0xFFFFFFFF)
        value: UTXO value in satoshis (optional, for tx builder)
        scriptpubkey: Prevout scriptPubKey hex (optional)
    """
    return cls(
        txid_le=bytes.fromhex(txid)[::-1],
        vout=vout,
        scriptsig=bytes.fromhex(scriptsig) if scriptsig else b"",
        sequence=sequence,
        value=value,
        scriptpubkey=bytes.fromhex(scriptpubkey) if scriptpubkey else b"",
    )
get(key: str, default: Any = None) -> Any

Allow inp.get("key", default) for backward compatibility.

Source code in jmcore/src/jmcore/bitcoin.py
615
616
617
618
619
620
def get(self, key: str, default: Any = None) -> Any:
    """Allow ``inp.get("key", default)`` for backward compatibility."""
    try:
        return self[key]
    except KeyError:
        return default

TxOutput

Unified transaction output model.

Stores value and script (scriptPubKey) in canonical byte form. Provides convenience accessors for hex and address representations.

Source code in jmcore/src/jmcore/bitcoin.py
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
@dataclass
class TxOutput:
    """Unified transaction output model.

    Stores ``value`` and ``script`` (scriptPubKey) in canonical byte form.
    Provides convenience accessors for hex and address representations.
    """

    value: int
    script: bytes  # scriptPubKey bytes

    # --- string accessors ---------------------------------------------------

    @property
    def scriptpubkey(self) -> str:
        """ScriptPubKey as hex string (backward compat alias)."""
        return self.script.hex()

    def address(self, network: str | NetworkType = "mainnet") -> str:
        """Derive address from scriptPubKey.

        Args:
            network: Network type for bech32/base58 encoding.

        Returns:
            Address string.

        Raises:
            ValueError: If scriptPubKey is an unsupported type.
        """
        return scriptpubkey_to_address(self.script, network)

    # --- dict-like access (backward compat during migration) ----------------

    def __getitem__(self, key: str) -> Any:
        """Allow ``out["value"]`` style access for backward compatibility."""
        if key == "value":
            return self.value
        if key == "scriptpubkey":
            return self.scriptpubkey
        raise KeyError(key)

    def get(self, key: str, default: Any = None) -> Any:
        """Allow ``out.get("key", default)`` for backward compatibility."""
        try:
            return self[key]
        except KeyError:
            return default

    # --- factories ----------------------------------------------------------

    @classmethod
    def from_address(
        cls,
        address: str,
        value: int,
    ) -> TxOutput:
        """Create from address string (resolves to scriptPubKey).

        Args:
            address: Bitcoin address (any supported format)
            value: Output value in satoshis
        """
        return cls(value=value, script=address_to_scriptpubkey(address))

    @classmethod
    def from_hex(cls, scriptpubkey: str, value: int) -> TxOutput:
        """Create from hex scriptPubKey.

        Args:
            scriptpubkey: ScriptPubKey as hex string
            value: Output value in satoshis
        """
        return cls(value=value, script=bytes.fromhex(scriptpubkey))
Attributes
script: bytes instance-attribute
scriptpubkey: str property

ScriptPubKey as hex string (backward compat alias).

value: int instance-attribute
Functions
__getitem__(key: str) -> Any

Allow out["value"] style access for backward compatibility.

Source code in jmcore/src/jmcore/bitcoin.py
689
690
691
692
693
694
695
def __getitem__(self, key: str) -> Any:
    """Allow ``out["value"]`` style access for backward compatibility."""
    if key == "value":
        return self.value
    if key == "scriptpubkey":
        return self.scriptpubkey
    raise KeyError(key)
address(network: str | NetworkType = 'mainnet') -> str

Derive address from scriptPubKey.

Args: network: Network type for bech32/base58 encoding.

Returns: Address string.

Raises: ValueError: If scriptPubKey is an unsupported type.

Source code in jmcore/src/jmcore/bitcoin.py
673
674
675
676
677
678
679
680
681
682
683
684
685
def address(self, network: str | NetworkType = "mainnet") -> str:
    """Derive address from scriptPubKey.

    Args:
        network: Network type for bech32/base58 encoding.

    Returns:
        Address string.

    Raises:
        ValueError: If scriptPubKey is an unsupported type.
    """
    return scriptpubkey_to_address(self.script, network)
from_address(address: str, value: int) -> TxOutput classmethod

Create from address string (resolves to scriptPubKey).

Args: address: Bitcoin address (any supported format) value: Output value in satoshis

Source code in jmcore/src/jmcore/bitcoin.py
706
707
708
709
710
711
712
713
714
715
716
717
718
@classmethod
def from_address(
    cls,
    address: str,
    value: int,
) -> TxOutput:
    """Create from address string (resolves to scriptPubKey).

    Args:
        address: Bitcoin address (any supported format)
        value: Output value in satoshis
    """
    return cls(value=value, script=address_to_scriptpubkey(address))
from_hex(scriptpubkey: str, value: int) -> TxOutput classmethod

Create from hex scriptPubKey.

Args: scriptpubkey: ScriptPubKey as hex string value: Output value in satoshis

Source code in jmcore/src/jmcore/bitcoin.py
720
721
722
723
724
725
726
727
728
@classmethod
def from_hex(cls, scriptpubkey: str, value: int) -> TxOutput:
    """Create from hex scriptPubKey.

    Args:
        scriptpubkey: ScriptPubKey as hex string
        value: Output value in satoshis
    """
    return cls(value=value, script=bytes.fromhex(scriptpubkey))
get(key: str, default: Any = None) -> Any

Allow out.get("key", default) for backward compatibility.

Source code in jmcore/src/jmcore/bitcoin.py
697
698
699
700
701
702
def get(self, key: str, default: Any = None) -> Any:
    """Allow ``out.get("key", default)`` for backward compatibility."""
    try:
        return self[key]
    except KeyError:
        return default

Functions

compute_sighash_segwit(tx: ParsedTransaction, input_index: int, script_code: bytes, value: int, sighash_type: int) -> bytes

Source code in jmwallet/src/jmwallet/wallet/signing.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def compute_sighash_segwit(
    tx: ParsedTransaction,
    input_index: int,
    script_code: bytes,
    value: int,
    sighash_type: int,
) -> bytes:
    try:
        if input_index >= len(tx.inputs):
            raise TransactionSigningError("Input index out of range")

        hash_prevouts = hash256(
            b"".join(inp.txid_le + inp.vout.to_bytes(4, "little") for inp in tx.inputs)
        )
        hash_sequence = hash256(b"".join(inp.sequence_bytes for inp in tx.inputs))
        hash_outputs = hash256(
            b"".join(
                out.value.to_bytes(8, "little") + encode_varint(len(out.script)) + out.script
                for out in tx.outputs
            )
        )

        target_input = tx.inputs[input_index]

        preimage = (
            tx.version_bytes
            + hash_prevouts
            + hash_sequence
            + target_input.txid_le
            + target_input.vout.to_bytes(4, "little")
            + encode_varint(len(script_code))
            + script_code
            + value.to_bytes(8, "little")
            + target_input.sequence_bytes
            + hash_outputs
            + tx.locktime_bytes
            + sighash_type.to_bytes(4, "little")
        )

        return hash256(preimage)

    except Exception as e:
        raise TransactionSigningError(f"Failed to compute sighash: {e}") from e

create_p2wpkh_script_code(pubkey: bytes | str) -> bytes

Create scriptCode for P2WPKH signing (BIP143).

For P2WPKH, the scriptCode is the P2PKH script: OP_DUP OP_HASH160 <20-byte-pubkeyhash> OP_EQUALVERIFY OP_CHECKSIG

Args: pubkey: Public key bytes or hex

Returns: 25-byte scriptCode

Source code in jmcore/src/jmcore/bitcoin.py
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
def create_p2wpkh_script_code(pubkey: bytes | str) -> bytes:
    """
    Create scriptCode for P2WPKH signing (BIP143).

    For P2WPKH, the scriptCode is the P2PKH script:
    OP_DUP OP_HASH160 <20-byte-pubkeyhash> OP_EQUALVERIFY OP_CHECKSIG

    Args:
        pubkey: Public key bytes or hex

    Returns:
        25-byte scriptCode
    """
    if isinstance(pubkey, str):
        pubkey = bytes.fromhex(pubkey)

    pubkey_hash = hash160(pubkey)
    # OP_DUP OP_HASH160 PUSH20 <pkh> OP_EQUALVERIFY OP_CHECKSIG
    return b"\x76\xa9\x14" + pubkey_hash + b"\x88\xac"

create_p2wsh_witness_stack(signature: bytes, witness_script: bytes) -> list[bytes]

Create witness stack for P2WSH input.

For timelocked scripts (CLTV), the witness is: [signature, witness_script]

Args: signature: DER signature with sighash byte witness_script: The witness script (e.g., freeze script)

Returns: Witness stack: [signature, witness_script]

Source code in jmwallet/src/jmwallet/wallet/signing.py
202
203
204
205
206
207
208
209
210
211
212
213
214
def create_p2wsh_witness_stack(signature: bytes, witness_script: bytes) -> list[bytes]:
    """Create witness stack for P2WSH input.

    For timelocked scripts (CLTV), the witness is: [signature, witness_script]

    Args:
        signature: DER signature with sighash byte
        witness_script: The witness script (e.g., freeze script)

    Returns:
        Witness stack: [signature, witness_script]
    """
    return [signature, witness_script]

create_witness_stack(signature: bytes, pubkey_bytes: bytes) -> list[bytes]

Source code in jmwallet/src/jmwallet/wallet/signing.py
166
167
def create_witness_stack(signature: bytes, pubkey_bytes: bytes) -> list[bytes]:
    return [signature, pubkey_bytes]

deserialize_transaction(tx_bytes: bytes) -> ParsedTransaction

Deserialize a raw transaction for signing.

Delegates to :func:jmcore.bitcoin.parse_transaction_bytes which now returns typed TxInput / TxOutput objects with the dual-accessor API required by the signing code.

Raises: TransactionSigningError: If the transaction bytes cannot be parsed.

Source code in jmwallet/src/jmwallet/wallet/signing.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def deserialize_transaction(tx_bytes: bytes) -> ParsedTransaction:
    """Deserialize a raw transaction for signing.

    Delegates to :func:`jmcore.bitcoin.parse_transaction_bytes` which now
    returns typed ``TxInput`` / ``TxOutput`` objects with the dual-accessor
    API required by the signing code.

    Raises:
        TransactionSigningError: If the transaction bytes cannot be parsed.
    """
    try:
        return parse_transaction_bytes(tx_bytes)
    except Exception as e:
        raise TransactionSigningError(f"Failed to parse transaction: {e}") from e

encode_varint(n: int) -> bytes

Encode integer as Bitcoin varint.

Args: n: Integer to encode

Returns: Encoded bytes

Source code in jmcore/src/jmcore/bitcoin.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def encode_varint(n: int) -> bytes:
    """
    Encode integer as Bitcoin varint.

    Args:
        n: Integer to encode

    Returns:
        Encoded bytes
    """
    if n < 0xFD:
        return bytes([n])
    elif n <= 0xFFFF:
        return bytes([0xFD]) + struct.pack("<H", n)
    elif n <= 0xFFFFFFFF:
        return bytes([0xFE]) + struct.pack("<I", n)
    else:
        return bytes([0xFF]) + struct.pack("<Q", n)

hash256(data: bytes) -> bytes

SHA256(SHA256(data)) - Used for Bitcoin txids and block hashes.

Args: data: Input data to hash

Returns: 32-byte hash

Source code in jmcore/src/jmcore/bitcoin.py
246
247
248
249
250
251
252
253
254
255
256
def hash256(data: bytes) -> bytes:
    """
    SHA256(SHA256(data)) - Used for Bitcoin txids and block hashes.

    Args:
        data: Input data to hash

    Returns:
        32-byte hash
    """
    return hashlib.sha256(hashlib.sha256(data).digest()).digest()

sign_p2wpkh_input(tx: ParsedTransaction, input_index: int, script_code: bytes, value: int, private_key: PrivateKey, sighash_type: int = 1) -> bytes

Sign a P2WPKH input using coincurve.

Args: tx: The transaction to sign input_index: Index of the input to sign script_code: The scriptCode for signing (P2PKH script for P2WPKH) value: The value of the input being spent (in satoshis) private_key: coincurve PrivateKey instance sighash_type: Sighash type (default SIGHASH_ALL = 1)

Returns: DER-encoded signature with sighash type byte appended

Source code in jmwallet/src/jmwallet/wallet/signing.py
 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
122
123
def sign_p2wpkh_input(
    tx: ParsedTransaction,
    input_index: int,
    script_code: bytes,
    value: int,
    private_key: PrivateKey,
    sighash_type: int = 1,
) -> bytes:
    """Sign a P2WPKH input using coincurve.

    Args:
        tx: The transaction to sign
        input_index: Index of the input to sign
        script_code: The scriptCode for signing (P2PKH script for P2WPKH)
        value: The value of the input being spent (in satoshis)
        private_key: coincurve PrivateKey instance
        sighash_type: Sighash type (default SIGHASH_ALL = 1)

    Returns:
        DER-encoded signature with sighash type byte appended
    """
    sighash = compute_sighash_segwit(tx, input_index, script_code, value, sighash_type)

    # Sign the pre-hashed sighash (it's already SHA256d)
    # coincurve's sign() with hasher=None skips hashing
    signature = private_key.sign(sighash, hasher=None)

    return signature + bytes([sighash_type])

sign_p2wsh_input(tx: ParsedTransaction, input_index: int, witness_script: bytes, value: int, private_key: PrivateKey, sighash_type: int = 1) -> bytes

Sign a P2WSH input using coincurve.

For P2WSH, the scriptCode in BIP143 signing is the witness script itself.

Args: tx: The transaction to sign input_index: Index of the input to sign witness_script: The witness script (e.g., timelocked freeze script) value: The value of the input being spent (in satoshis) private_key: coincurve PrivateKey instance sighash_type: Sighash type (default SIGHASH_ALL = 1)

Returns: DER-encoded signature with sighash type byte appended

Source code in jmwallet/src/jmwallet/wallet/signing.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def sign_p2wsh_input(
    tx: ParsedTransaction,
    input_index: int,
    witness_script: bytes,
    value: int,
    private_key: PrivateKey,
    sighash_type: int = 1,
) -> bytes:
    """Sign a P2WSH input using coincurve.

    For P2WSH, the scriptCode in BIP143 signing is the witness script itself.

    Args:
        tx: The transaction to sign
        input_index: Index of the input to sign
        witness_script: The witness script (e.g., timelocked freeze script)
        value: The value of the input being spent (in satoshis)
        private_key: coincurve PrivateKey instance
        sighash_type: Sighash type (default SIGHASH_ALL = 1)

    Returns:
        DER-encoded signature with sighash type byte appended
    """
    # For P2WSH, the scriptCode is the witness script itself
    sighash = compute_sighash_segwit(tx, input_index, witness_script, value, sighash_type)

    # Sign the pre-hashed sighash (it's already SHA256d)
    signature = private_key.sign(sighash, hasher=None)

    return signature + bytes([sighash_type])

verify_p2wpkh_signature(tx: ParsedTransaction, input_index: int, script_code: bytes, value: int, signature: bytes, pubkey: bytes) -> bool

Verify a P2WPKH signature using coincurve.

Args: tx: The transaction containing the input input_index: Index of the input to verify script_code: The scriptCode (P2PKH script for P2WPKH) value: The value of the input being spent (in satoshis) signature: DER-encoded signature with sighash type byte appended pubkey: Public key bytes (compressed or uncompressed)

Returns: True if signature is valid, False otherwise

Source code in jmwallet/src/jmwallet/wallet/signing.py
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
160
161
162
163
def verify_p2wpkh_signature(
    tx: ParsedTransaction,
    input_index: int,
    script_code: bytes,
    value: int,
    signature: bytes,
    pubkey: bytes,
) -> bool:
    """Verify a P2WPKH signature using coincurve.

    Args:
        tx: The transaction containing the input
        input_index: Index of the input to verify
        script_code: The scriptCode (P2PKH script for P2WPKH)
        value: The value of the input being spent (in satoshis)
        signature: DER-encoded signature with sighash type byte appended
        pubkey: Public key bytes (compressed or uncompressed)

    Returns:
        True if signature is valid, False otherwise
    """
    from coincurve import PublicKey

    try:
        # Extract sighash type from last byte of signature
        if not signature:
            return False
        sighash_type = signature[-1]
        der_signature = signature[:-1]

        sighash = compute_sighash_segwit(tx, input_index, script_code, value, sighash_type)

        # Verify signature against sighash
        # coincurve verify(signature, message, hasher=None)
        public_key = PublicKey(pubkey)
        return public_key.verify(der_signature, sighash, hasher=None)
    except Exception:
        return False