Skip to content

jmwallet.wallet.spend

jmwallet.wallet.spend

Reusable direct-send (non-CoinJoin) transaction building, signing, and broadcasting.

This module contains the core spending logic extracted from the CLI so that both the CLI and the jmwalletd HTTP daemon can share it without duplication.

Attributes

DEFAULT_MAX_FEE_RATE_SAT_VB: float = 1000.0 module-attribute

DUST_THRESHOLD = 546 module-attribute

Classes

DirectSendResult dataclass

Result returned by :func:direct_send.

Source code in jmwallet/src/jmwallet/wallet/spend.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
@dataclass
class DirectSendResult:
    """Result returned by :func:`direct_send`."""

    txid: str
    tx_hex: str
    fee: int
    fee_rate: float
    send_amount: int
    change_amount: int
    num_inputs: int
    num_outputs: int
    inputs: list[dict[str, object]] = field(default_factory=list)
    outputs: list[dict[str, object]] = field(default_factory=list)
Attributes
change_amount: int instance-attribute
fee: int instance-attribute
fee_rate: float instance-attribute
inputs: list[dict[str, object]] = field(default_factory=list) class-attribute instance-attribute
num_inputs: int instance-attribute
num_outputs: int instance-attribute
outputs: list[dict[str, object]] = field(default_factory=list) class-attribute instance-attribute
send_amount: int instance-attribute
tx_hex: str instance-attribute
txid: str instance-attribute

ExcessiveFeeRateError

Bases: ValueError

Raised when a resolved fee rate exceeds the configured safety cap.

Subclasses :class:ValueError so existing except ValueError handlers in the CLI and HTTP layers continue to behave correctly (refuse the transaction with a user-visible error) without needing to know about the new exception type.

Source code in jmwallet/src/jmwallet/wallet/spend.py
51
52
53
54
55
56
57
58
class ExcessiveFeeRateError(ValueError):
    """Raised when a resolved fee rate exceeds the configured safety cap.

    Subclasses :class:`ValueError` so existing ``except ValueError`` handlers
    in the CLI and HTTP layers continue to behave correctly (refuse the
    transaction with a user-visible error) without needing to know about the
    new exception type.
    """

SignedDirectTx dataclass

Intermediate result from :func:prepare_direct_send.

Source code in jmwallet/src/jmwallet/wallet/spend.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
@dataclass
class SignedDirectTx:
    """Intermediate result from :func:`prepare_direct_send`."""

    txid: str
    tx_hex: str
    fee: int
    fee_rate: float
    send_amount: int
    change_amount: int
    num_inputs: int
    num_outputs: int
    destination: str
    change_address: str = ""
    selected_utxos: list[tuple[str, int]] = field(default_factory=list)
    source_addresses: list[str] = field(default_factory=list)
    inputs: list[dict[str, object]] = field(default_factory=list)
    outputs: list[dict[str, object]] = field(default_factory=list)
Attributes
change_address: str = '' class-attribute instance-attribute
change_amount: int instance-attribute
destination: str instance-attribute
fee: int instance-attribute
fee_rate: float instance-attribute
inputs: list[dict[str, object]] = field(default_factory=list) class-attribute instance-attribute
num_inputs: int instance-attribute
num_outputs: int instance-attribute
outputs: list[dict[str, object]] = field(default_factory=list) class-attribute instance-attribute
selected_utxos: list[tuple[str, int]] = field(default_factory=list) class-attribute instance-attribute
send_amount: int instance-attribute
source_addresses: list[str] = field(default_factory=list) class-attribute instance-attribute
tx_hex: str instance-attribute
txid: str instance-attribute

Functions:

direct_send(*, wallet: WalletService, backend: BlockchainBackend, mixdepth: int, amount_sats: int, destination: str, fee_rate: float | None = None, fee_target_blocks: int = 6, tx_fee_factor: float = 0.0, max_fee_rate_sat_vb: float = DEFAULT_MAX_FEE_RATE_SAT_VB) -> DirectSendResult async

Build, sign, and broadcast a direct (non-CoinJoin) transaction.

Parameters:

Name Type Description Default
wallet WalletService

An initialised and synced :class:WalletService.

required
backend BlockchainBackend

The blockchain backend for fee estimation and broadcasting.

required
mixdepth int

The mixdepth (account) to spend from.

required
amount_sats int

Amount in satoshis to send. 0 means sweep the entire mixdepth.

required
destination str

Destination Bitcoin address (bech32 only).

required
fee_rate float | None

Explicit fee rate in sat/vB. When None, the rate is estimated from the backend using fee_target_blocks.

None
fee_target_blocks int

Number of blocks for fee estimation (ignored when fee_rate is set).

6
tx_fee_factor float

Privacy randomization factor. The final rate is selected between the resolved rate and that rate multiplied by 1 + tx_fee_factor, with the upper end limited by max_fee_rate_sat_vb.

0.0
max_fee_rate_sat_vb float

Safety cap on the fee rate (sat/vB). The resolved rate (manual or from backend estimation) is rejected with :class:ExcessiveFeeRateError when it exceeds this value. Defaults to :data:DEFAULT_MAX_FEE_RATE_SAT_VB; daemon and CLI callers wire this from settings.wallet.max_fee_rate_sat_vb.

DEFAULT_MAX_FEE_RATE_SAT_VB

Returns:

Type Description
DirectSendResult
Source code in jmwallet/src/jmwallet/wallet/spend.py
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
async def direct_send(
    *,
    wallet: WalletService,
    backend: BlockchainBackend,
    mixdepth: int,
    amount_sats: int,
    destination: str,
    fee_rate: float | None = None,
    fee_target_blocks: int = 6,
    tx_fee_factor: float = 0.0,
    max_fee_rate_sat_vb: float = DEFAULT_MAX_FEE_RATE_SAT_VB,
) -> DirectSendResult:
    """Build, sign, and broadcast a direct (non-CoinJoin) transaction.

    Parameters
    ----------
    wallet:
        An initialised and synced :class:`WalletService`.
    backend:
        The blockchain backend for fee estimation and broadcasting.
    mixdepth:
        The mixdepth (account) to spend from.
    amount_sats:
        Amount in satoshis to send.  ``0`` means sweep the entire mixdepth.
    destination:
        Destination Bitcoin address (bech32 only).
    fee_rate:
        Explicit fee rate in sat/vB.  When *None*, the rate is estimated
        from the backend using *fee_target_blocks*.
    fee_target_blocks:
        Number of blocks for fee estimation (ignored when *fee_rate* is set).
    tx_fee_factor:
        Privacy randomization factor. The final rate is selected between the
        resolved rate and that rate multiplied by ``1 + tx_fee_factor``, with
        the upper end limited by *max_fee_rate_sat_vb*.
    max_fee_rate_sat_vb:
        Safety cap on the fee rate (sat/vB).  The resolved rate (manual or
        from backend estimation) is rejected with
        :class:`ExcessiveFeeRateError` when it exceeds this value.  Defaults
        to :data:`DEFAULT_MAX_FEE_RATE_SAT_VB`; daemon and CLI callers wire
        this from ``settings.wallet.max_fee_rate_sat_vb``.

    Returns
    -------
    DirectSendResult
    """
    prepared = await prepare_direct_send(
        wallet=wallet,
        backend=backend,
        mixdepth=mixdepth,
        amount_sats=amount_sats,
        destination=destination,
        fee_rate=fee_rate,
        fee_target_blocks=fee_target_blocks,
        tx_fee_factor=tx_fee_factor,
        max_fee_rate_sat_vb=max_fee_rate_sat_vb,
    )

    tx_bytes_len = len(bytes.fromhex(prepared.tx_hex))
    logger.info("Broadcasting direct-send transaction ({} bytes)", tx_bytes_len)
    broadcast_txid = await backend.broadcast_transaction(prepared.tx_hex)
    txid = broadcast_txid or prepared.txid

    logger.info("Broadcast OK: {}", txid)
    return DirectSendResult(
        txid=txid,
        tx_hex=prepared.tx_hex,
        fee=prepared.fee,
        fee_rate=prepared.fee_rate,
        send_amount=prepared.send_amount,
        change_amount=prepared.change_amount,
        num_inputs=prepared.num_inputs,
        num_outputs=prepared.num_outputs,
        inputs=prepared.inputs,
        outputs=prepared.outputs,
    )

enforce_fee_rate_cap(fee_rate: float, max_fee_rate_sat_vb: float, *, source: str) -> None

Reject fee_rate if it exceeds the configured cap.

Parameters:

Name Type Description Default
fee_rate float

The candidate fee rate in sat/vB.

required
max_fee_rate_sat_vb float

The safety cap. Must be positive.

required
source str

Human-readable description of where the rate came from ("manual", "backend estimate", ...). Included verbatim in the error message to make misconfiguration easy to debug.

required

Raises:

Type Description
ExcessiveFeeRateError

If fee_rate exceeds max_fee_rate_sat_vb.

Source code in jmwallet/src/jmwallet/wallet/spend.py
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
def enforce_fee_rate_cap(fee_rate: float, max_fee_rate_sat_vb: float, *, source: str) -> None:
    """Reject *fee_rate* if it exceeds the configured cap.

    Parameters
    ----------
    fee_rate:
        The candidate fee rate in sat/vB.
    max_fee_rate_sat_vb:
        The safety cap.  Must be positive.
    source:
        Human-readable description of where the rate came from
        (``"manual"``, ``"backend estimate"``, ...).  Included verbatim in
        the error message to make misconfiguration easy to debug.

    Raises
    ------
    ExcessiveFeeRateError
        If ``fee_rate`` exceeds ``max_fee_rate_sat_vb``.
    """
    if not math.isfinite(fee_rate) or fee_rate <= 0:
        msg = f"{source} fee rate must be a finite positive number, got {fee_rate!r}"
        raise ExcessiveFeeRateError(msg)
    if fee_rate > max_fee_rate_sat_vb:
        msg = (
            f"{source} fee rate {fee_rate:.2f} sat/vB exceeds safety cap "
            f"{max_fee_rate_sat_vb:.2f} sat/vB. "
            "Raise the cap explicitly (settings.wallet.max_fee_rate_sat_vb) "
            "only if you really intend to pay this much."
        )
        raise ExcessiveFeeRateError(msg)

estimate_fee(utxos: list[UTXOInfo], destination: str, fee_rate: float, *, has_change: bool) -> tuple[int, int]

Estimate the transaction fee and vsize.

P2WSH inputs (expired fidelity bonds being swept) are larger than P2WPKH inputs (their witness carries the timelock script), so size them as such or the resulting fee rate falls below the requested one (and potentially below the relay floor).

Returns (fee, vsize).

Source code in jmwallet/src/jmwallet/wallet/spend.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def estimate_fee(
    utxos: list[UTXOInfo],
    destination: str,
    fee_rate: float,
    *,
    has_change: bool,
) -> tuple[int, int]:
    """Estimate the transaction fee and vsize.

    P2WSH inputs (expired fidelity bonds being swept) are larger than P2WPKH
    inputs (their witness carries the timelock script), so size them as such
    or the resulting fee rate falls below the requested one (and potentially
    below the relay floor).

    Returns ``(fee, vsize)``.
    """
    input_types = ["p2wsh" if u.is_p2wsh else "p2wpkh" for u in utxos]
    try:
        dest_type = get_address_type(destination)
    except ValueError:
        dest_type = "p2wpkh"

    output_types = [dest_type]
    if has_change:
        output_types.append("p2wpkh")

    vsize = estimate_vsize(input_types, output_types)
    return math.ceil(vsize * fee_rate), vsize

prepare_direct_send(*, wallet: WalletService, backend: BlockchainBackend, mixdepth: int, amount_sats: int, destination: str, fee_rate: float | None = None, fee_target_blocks: int = 6, tx_fee_factor: float = 0.0, max_fee_rate_sat_vb: float = DEFAULT_MAX_FEE_RATE_SAT_VB) -> SignedDirectTx async

Build and sign a direct-send transaction WITHOUT broadcasting.

Returns a :class:SignedDirectTx containing the signed hex and all metadata needed to broadcast and record a history entry. Callers that want the full build+sign+broadcast flow should use :func:direct_send instead.

Source code in jmwallet/src/jmwallet/wallet/spend.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
async def prepare_direct_send(
    *,
    wallet: WalletService,
    backend: BlockchainBackend,
    mixdepth: int,
    amount_sats: int,
    destination: str,
    fee_rate: float | None = None,
    fee_target_blocks: int = 6,
    tx_fee_factor: float = 0.0,
    max_fee_rate_sat_vb: float = DEFAULT_MAX_FEE_RATE_SAT_VB,
) -> SignedDirectTx:
    """Build and sign a direct-send transaction WITHOUT broadcasting.

    Returns a :class:`SignedDirectTx` containing the signed hex and all
    metadata needed to broadcast and record a history entry. Callers that want
    the full build+sign+broadcast flow should use :func:`direct_send` instead.
    """
    if not destination.startswith(("bc1", "tb1", "bcrt1")):
        msg = "Only bech32 addresses are currently supported"
        raise ValueError(msg)

    # Validate the destination address up front (checksum + HRP + network).
    # We compute the scriptPubKey now so a malformed address fails fast,
    # before any fee estimation or UTXO selection side effects.
    network = getattr(wallet, "network", None)
    dest_script = _decode_bech32_scriptpubkey(destination, network=network)

    # --- Fee rate resolution ---
    fee_source = "manual"
    if fee_rate is None:
        fee_rate = await backend.estimate_fee(target_blocks=fee_target_blocks)
        logger.debug("Estimated fee rate: {:.2f} sat/vB ({} blocks)", fee_rate, fee_target_blocks)
        fee_source = "backend estimate"

    enforce_fee_rate_cap(fee_rate, max_fee_rate_sat_vb, source=fee_source)
    if not math.isfinite(tx_fee_factor) or tx_fee_factor < 0:
        msg = f"tx_fee_factor must be a finite non-negative number, got {tx_fee_factor!r}"
        raise ValueError(msg)
    if tx_fee_factor > 0:
        upper_rate = min(fee_rate * (1 + tx_fee_factor), max_fee_rate_sat_vb)
        fee_rate = secure_random.uniform(fee_rate, upper_rate)
        logger.debug("Randomized direct-send fee rate: {:.2f} sat/vB", fee_rate)
    enforce_fee_rate_cap(fee_rate, max_fee_rate_sat_vb, source="final")

    # --- UTXO selection ---
    utxos: list[UTXOInfo]
    locktime_cutoff: int | None = None
    if amount_sats == 0:
        # Sweep regular coins by default. If there are none, admit expired
        # hot-wallet bonds. This supports explicit bond-redemption flows that
        # freeze every other coin without making bonds part of normal
        # auto-selection or linking them to unrelated funds.
        raw_utxos = await wallet.get_utxos(mixdepth)
        utxos = select_spendable_utxos(raw_utxos)
        if not utxos and any(u.is_fidelity_bond and not u.frozen for u in raw_utxos):
            locktime_cutoff = await backend.get_median_time_past()
            bond_candidates = select_spendable_utxos(
                raw_utxos,
                include_fidelity_bonds=True,
                locktime_cutoff=locktime_cutoff,
            )
            utxos = [u for u in bond_candidates if _is_signable_fidelity_bond(wallet, u)]
    else:
        # Non-sweep: use greedy coin selection to pick the minimum UTXOs needed.
        # This avoids building oversized transactions when the wallet has many UTXOs.
        # Add a generous fee buffer (5× estimated fee) to ensure enough inputs.
        fee_buffer = max(10_000, int(amount_sats * 0.05))
        try:
            utxos = wallet.select_utxos(mixdepth, amount_sats + fee_buffer)
        except ValueError:
            # Fallback: use all spendable UTXOs if coin selection fails
            # (e.g. many dust UTXOs where the sum exceeds target but individually small).
            raw_utxos = await wallet.get_utxos(mixdepth)
            utxos = select_spendable_utxos(raw_utxos)

    if not utxos:
        msg = f"No spendable UTXOs in mixdepth {mixdepth}"
        raise ValueError(msg)

    total_input = sum(u.value for u in utxos)
    is_sweep = amount_sats == 0

    # --- Fee estimation ---
    has_change = not is_sweep
    fee, _vsize = estimate_fee(utxos, destination, fee_rate, has_change=has_change)

    if is_sweep:
        send_amount = total_input - fee
        if send_amount <= 0:
            msg = "Insufficient funds after fee deduction for sweep"
            raise ValueError(msg)
        change_amount = 0
    else:
        send_amount = amount_sats
        change_amount = total_input - send_amount - fee
        if change_amount < 0:
            msg = f"Insufficient funds: need {send_amount + fee}, have {total_input}"
            raise ValueError(msg)
        if change_amount < DUST_THRESHOLD:
            # With no change output, every satoshi not sent is the actual fee.
            # Keep the reported fee consistent with the serialized transaction.
            fee = total_input - send_amount
            change_amount = 0

    # --- Destination scriptPubKey ---
    # (already validated and computed at the top of this function)

    # --- Change output ---
    change_script: bytes | None = None
    change_addr: str = ""
    if change_amount > 0:
        change_index = wallet.get_next_address_index(mixdepth, 1)
        change_addr = wallet.get_change_address(mixdepth, change_index)
        change_key = wallet.get_key_for_address(change_addr)
        if change_key is None:
            msg = f"Cannot derive key for change address {change_addr}"
            raise ValueError(msg)
        change_script = pubkey_to_p2wpkh_script(
            change_key.get_public_key_bytes(compressed=True).hex()
        )

    # --- Build unsigned tx ---
    unsigned_tx, version, inputs_data, outputs_data, num_outputs = _build_unsigned_tx(
        utxos,
        dest_script,
        send_amount,
        change_script,
        change_amount,
        locktime_cutoff=locktime_cutoff,
    )

    # --- Sign ---
    witnesses = _sign_inputs(unsigned_tx, utxos, wallet)

    # --- Assemble signed tx ---
    locktime_bytes = unsigned_tx[-4:]
    signed_tx = _assemble_signed_tx(
        version, inputs_data, num_outputs, outputs_data, locktime_bytes, witnesses, len(utxos)
    )
    tx_hex = signed_tx.hex()

    outputs_list: list[dict[str, object]] = [
        {"value_sats": send_amount, "scriptPubKey": dest_script.hex(), "address": destination},
    ]
    if change_amount > 0 and change_script is not None:
        outputs_list.append(
            {
                "value_sats": change_amount,
                "scriptPubKey": change_script.hex(),
                "address": change_addr,
            }
        )

    return SignedDirectTx(
        txid=get_txid(tx_hex),
        tx_hex=tx_hex,
        fee=fee,
        fee_rate=fee_rate,
        send_amount=send_amount,
        change_amount=change_amount,
        num_inputs=len(utxos),
        num_outputs=num_outputs,
        destination=destination,
        change_address=change_addr if change_amount > 0 else "",
        selected_utxos=[(u.txid, u.vout) for u in utxos],
        source_addresses=[u.address for u in utxos],
        inputs=[
            {
                "outpoint": f"{u.txid}:{u.vout}",
                "scriptSig": "",
                "nSequence": 0xFFFFFFFE
                if any(ut.is_timelocked and ut.locktime is not None for ut in utxos)
                else 0xFFFFFFFF,
                "witness": "",
            }
            for u in utxos
        ],
        outputs=outputs_list,
    )

select_spendable_utxos(utxos: list[UTXOInfo], *, include_frozen: bool = False, include_fidelity_bonds: bool = False, locktime_cutoff: int | None = None) -> list[UTXOInfo]

Filter UTXOs to only those safe for auto-spending.

Frozen UTXOs and all fidelity bonds are excluded by default. Setting include_fidelity_bonds admits only bonds whose locktime is strictly below locktime_cutoff. The cutoff should be chain median-time-past for transaction construction; it defaults to the host time for display-only callers.

Source code in jmwallet/src/jmwallet/wallet/spend.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def select_spendable_utxos(
    utxos: list[UTXOInfo],
    *,
    include_frozen: bool = False,
    include_fidelity_bonds: bool = False,
    locktime_cutoff: int | None = None,
) -> list[UTXOInfo]:
    """Filter UTXOs to only those safe for auto-spending.

    Frozen UTXOs and all fidelity bonds are excluded by default. Setting
    ``include_fidelity_bonds`` admits only bonds whose locktime is strictly
    below ``locktime_cutoff``. The cutoff should be chain median-time-past for
    transaction construction; it defaults to the host time for display-only
    callers.
    """
    cutoff = int(time.time()) if locktime_cutoff is None else locktime_cutoff
    result = []
    for u in utxos:
        if not include_frozen and u.frozen:
            continue
        if u.is_fidelity_bond:
            if not include_fidelity_bonds:
                continue
            if u.locktime is None or u.locktime >= cutoff:
                continue
        result.append(u)
    return result