Skip to content

jmwallet.cli.sign_psbt

jmwallet.cli.sign_psbt

PSBT review, signing, and confirmed broadcasting.

Attributes

MAX_PSBT_SIZE = 10 * 1024 * 1024 module-attribute

Classes

Functions:

sign_psbt(psbt_base64: Annotated[str | None, typer.Argument(help='Base64-encoded PSBT v0 or v2')] = None, input_file: Annotated[Path | None, typer.Option('--input', '-i', help='Read a binary or base64 PSBT from a file')] = None, output_file: Annotated[Path | None, typer.Option('--output', '-o', help='Write the signed base64 PSBT to a file')] = None, mnemonic_file: Annotated[Path | None, typer.Option('--mnemonic-file', '-f', envvar='MNEMONIC_FILE')] = None, prompt_bip39_passphrase: Annotated[bool, typer.Option('--prompt-bip39-passphrase', help='Prompt for BIP39 passphrase')] = False, network: Annotated[str | None, typer.Option('--network', '-n', help='Bitcoin network')] = None, scan_range: Annotated[int | None, typer.Option('--scan-range', min=0, max=1000000, help='Fallback addresses per branch to derive when PSBT key origins are absent')] = None, yes: Annotated[bool, typer.Option('--yes', '-y', help='Skip confirmations (broadcast still needs --broadcast)')] = False, broadcast: Annotated[bool, typer.Option('--broadcast', help='Submit the fully signed transaction (default: sign only)')] = False, no_broadcast: Annotated[bool, typer.Option('--no-broadcast', help='Disable submission and backend access, even with --broadcast')] = False, data_dir: Annotated[Path | None, typer.Option('--data-dir', envvar='JOINMARKET_DATA_DIR', help='Data directory (default: ~/.joinmarket-ng or $JOINMARKET_DATA_DIR)')] = None, config_file: Annotated[Path | None, typer.Option('--config-file', envvar='JOINMARKET_CONFIG_FILE', help='Config file path (default: <data-dir>/config.toml)')] = None, log_level: Annotated[str | None, typer.Option('--log-level', '-l', help='Log level')] = None) -> None

Review and sign a PSBT offline. Submit only with --broadcast.

Supports regular P2WPKH wallet inputs and canonical JoinMarket fidelity bond P2WSH inputs, while leaving unrelated P2WSH inputs unsigned. Every input must include witness_utxo and the full funding transaction (non_witness_utxo) so every amount and script can be authenticated offline. Accepts PSBT v0 and v2. Broadcasting requires every input to be wallet-owned and fully signed. Signing-only is the default, including with --yes. Submission requires --broadcast and a separate confirmation unless --yes is also supplied.

Source code in jmwallet/src/jmwallet/cli/sign_psbt.py
166
167
168
169
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
@app.command("sign-psbt")
def sign_psbt(
    psbt_base64: Annotated[str | None, typer.Argument(help="Base64-encoded PSBT v0 or v2")] = None,
    input_file: Annotated[
        Path | None,
        typer.Option("--input", "-i", help="Read a binary or base64 PSBT from a file"),
    ] = None,
    output_file: Annotated[
        Path | None,
        typer.Option("--output", "-o", help="Write the signed base64 PSBT to a file"),
    ] = None,
    mnemonic_file: Annotated[
        Path | None, typer.Option("--mnemonic-file", "-f", envvar="MNEMONIC_FILE")
    ] = None,
    prompt_bip39_passphrase: Annotated[
        bool, typer.Option("--prompt-bip39-passphrase", help="Prompt for BIP39 passphrase")
    ] = False,
    network: Annotated[str | None, typer.Option("--network", "-n", help="Bitcoin network")] = None,
    scan_range: Annotated[
        int | None,
        typer.Option(
            "--scan-range",
            min=0,
            max=1_000_000,
            help="Fallback addresses per branch to derive when PSBT key origins are absent",
        ),
    ] = None,
    yes: Annotated[
        bool,
        typer.Option("--yes", "-y", help="Skip confirmations (broadcast still needs --broadcast)"),
    ] = False,
    broadcast: Annotated[
        bool,
        typer.Option(
            "--broadcast",
            help="Submit the fully signed transaction (default: sign only)",
        ),
    ] = False,
    no_broadcast: Annotated[
        bool,
        typer.Option(
            "--no-broadcast", help="Disable submission and backend access, even with --broadcast"
        ),
    ] = False,
    data_dir: Annotated[
        Path | None,
        typer.Option(
            "--data-dir",
            envvar="JOINMARKET_DATA_DIR",
            help="Data directory (default: ~/.joinmarket-ng or $JOINMARKET_DATA_DIR)",
        ),
    ] = None,
    config_file: Annotated[
        Path | None,
        typer.Option(
            "--config-file",
            envvar="JOINMARKET_CONFIG_FILE",
            help="Config file path (default: <data-dir>/config.toml)",
        ),
    ] = None,
    log_level: Annotated[str | None, typer.Option("--log-level", "-l", help="Log level")] = None,
) -> None:
    """Review and sign a PSBT offline. Submit only with --broadcast.

    Supports regular P2WPKH wallet inputs and canonical JoinMarket fidelity bond
    P2WSH inputs, while leaving unrelated P2WSH inputs unsigned. Every input must
    include witness_utxo and the full funding transaction (non_witness_utxo) so
    every amount and script can be authenticated offline. Accepts PSBT
    v0 and v2. Broadcasting requires every input to be wallet-owned and fully signed.
    Signing-only is the default, including with --yes. Submission requires
    --broadcast and a separate confirmation unless --yes is also supplied.
    """
    settings = setup_cli(log_level, data_dir=data_dir, config_file=config_file)
    try:
        if psbt_base64 is None and input_file is None:
            psbt_base64 = typer.prompt("Paste base64 PSBT")
        raw_psbt = _load_psbt(psbt_base64, input_file)
        resolved = resolve_mnemonic(
            settings,
            mnemonic_file=mnemonic_file,
            prompt_bip39_passphrase=prompt_bip39_passphrase,
        )
        if resolved is None:
            raise ValueError("No mnemonic provided")

        configured_network = (
            settings.network_config.bitcoin_network or settings.network_config.network
        )
        resolved_network = NetworkType(network or configured_network.value).value
        resolved_scan_range = settings.wallet.scan_range if scan_range is None else scan_range
        wallet = WalletService(
            mnemonic=resolved.mnemonic,
            backend=OfflineBackend(),
            network=resolved_network,
            mixdepth_count=settings.wallet.mixdepth_count,
            scan_range=resolved_scan_range,
            passphrase=resolved.bip39_passphrase,
        )
        plan = wallet.prepare_psbt_signing(raw_psbt, resolved_scan_range)
        if plan.owned_count == 0:
            raise ValueError("The PSBT contains no inputs owned by this wallet")
        if plan.fee > 0:
            enforce_fee_rate_cap(
                plan.estimated_fee_rate,
                settings.wallet.max_fee_rate_sat_vb,
                source="PSBT upper bound" if plan.fee_rate_is_upper_bound else "PSBT estimated",
            )
        else:
            logger.warning("PSBT pays a zero fee and may not be relayable")

        _display_plan(plan, resolved_network)
        if plan.signable_count > 0 and not yes:
            if not typer.confirm("Sign the wallet-owned inputs shown above?", default=False):
                typer.echo("Signing cancelled")
                raise typer.Exit(1)

        result = wallet.sign_psbt(plan)
        _write_result(result.psbt, output_file)
        typer.echo(
            f"Signed {len(result.signed_indices)} input(s); "
            f"{len(result.already_signed_indices)} already had valid wallet signatures."
        )
        if not broadcast or no_broadcast:
            return
        tx_bytes = wallet.finalize_psbt(
            result.psbt,
            expected_unsigned_tx=plan.psbt.unsigned_tx,
            scan_range=resolved_scan_range,
        )
        vsize = calculate_tx_vsize(tx_bytes)
        fee_rate = plan.fee / vsize
        enforce_fee_rate_cap(fee_rate, settings.wallet.max_fee_rate_sat_vb, source="PSBT final")
        tx_hex = tx_bytes.hex()
        txid = get_txid(tx_hex)
        typer.echo(f"\nBitcoin network: {resolved_network}")
        typer.echo(f"Fee: {plan.fee:,} sats ({fee_rate:.2f} sat/vB, {vsize} vB)")
        typer.echo(f"Transaction ID: {txid}")
        if not yes and not typer.confirm("Broadcast this transaction?", default=False):
            typer.echo("Not broadcast. The signed PSBT is available above or in the output file.")
            return
        backend_settings = resolve_backend_settings(settings, network=resolved_network)
        if backend_settings.bitcoin_network != resolved_network:
            raise ValueError("Configured Bitcoin network does not match the reviewed network")
        wallet_name = generate_descriptor_wallet_name(
            resolved.mnemonic, resolved_network, resolved.bip39_passphrase
        )
        asyncio.run(_broadcast_transaction(tx_hex, backend_settings, wallet_name))
    except (
        ExcessiveFeeRateError,
        FileNotFoundError,
        PSBTError,
        TransactionSigningError,
        ValueError,
        OSError,
    ) as exc:
        logger.error(str(exc))
        raise typer.Exit(1) from exc