Skip to content

jmwallet.cli.bonds

jmwallet.cli.bonds

Fidelity bond commands: list-bonds, generate-bond-address, sync-bonds, recover-bonds.

Attributes

Classes

Functions:

generate_bond_address(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, locktime: Annotated[int, typer.Option('--locktime', '-L', help='Locktime as Unix timestamp')] = 0, locktime_date: Annotated[str | None, typer.Option('--locktime-date', '-d', help='Locktime as YYYY-MM (must be 1st of month)')] = None, network: Annotated[str | None, typer.Option('--network', '-n')] = None, 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 (decoupled from data dir). Defaults to <data-dir>/config.toml')] = None, no_save: Annotated[bool, typer.Option('--no-save', help='Do not save the bond to the registry')] = False, log_level: Annotated[str | None, typer.Option('--log-level', '-l', help='Log level')] = None) -> None

Generate a fidelity bond (timelocked P2WSH) address.

Source code in jmwallet/src/jmwallet/cli/bonds.py
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
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
@app.command("generate-bond-address")
def generate_bond_address(
    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,
    locktime: Annotated[
        int, typer.Option("--locktime", "-L", help="Locktime as Unix timestamp")
    ] = 0,
    locktime_date: Annotated[
        str | None,
        typer.Option("--locktime-date", "-d", help="Locktime as YYYY-MM (must be 1st of month)"),
    ] = None,
    network: Annotated[str | None, typer.Option("--network", "-n")] = None,
    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 (decoupled from data dir). Defaults to <data-dir>/config.toml",
        ),
    ] = None,
    no_save: Annotated[
        bool,
        typer.Option("--no-save", help="Do not save the bond to the registry"),
    ] = False,
    log_level: Annotated[
        str | None,
        typer.Option("--log-level", "-l", help="Log level"),
    ] = None,
) -> None:
    """Generate a fidelity bond (timelocked P2WSH) address."""
    settings = setup_cli(log_level, data_dir=data_dir, config_file=config_file)

    try:
        resolved = resolve_mnemonic(
            settings,
            mnemonic_file=mnemonic_file,
            prompt_bip39_passphrase=prompt_bip39_passphrase,
        )
        if not resolved:
            raise ValueError("No mnemonic provided")
        resolved_mnemonic = resolved.mnemonic
        resolved_bip39_passphrase = resolved.bip39_passphrase
    except (FileNotFoundError, ValueError) as e:
        logger.error(str(e))
        raise typer.Exit(1)

    # Resolve network from config if not provided
    resolved_network = network if network is not None else settings.network_config.network.value

    # Resolve data directory from config if not provided
    resolved_data_dir = data_dir if data_dir is not None else settings.get_data_dir()

    # Parse and validate locktime
    from jmcore.timenumber import is_valid_locktime, parse_locktime_date

    if locktime_date:
        try:
            # Use timenumber module for proper parsing and validation
            locktime = parse_locktime_date(locktime_date)
        except ValueError as e:
            logger.error(f"Invalid locktime date: {e}")
            logger.info("Use format: YYYY-MM or YYYY-MM-DD (must be 1st of month)")
            logger.info("Valid range: 2020-01 to 2099-12")
            raise typer.Exit(1)

    if locktime <= 0:
        logger.error("Locktime is required. Use --locktime or --locktime-date")
        raise typer.Exit(1)

    # Validate locktime is a valid timenumber (1st of month, midnight UTC)
    if not is_valid_locktime(locktime):
        from jmcore.timenumber import get_nearest_valid_locktime

        suggested = get_nearest_valid_locktime(locktime, round_up=True)
        suggested_dt = datetime.fromtimestamp(suggested)
        logger.warning(
            f"Locktime {locktime} is not a valid fidelity bond locktime "
            f"(must be 1st of month at midnight UTC)"
        )
        logger.info(f"Suggested locktime: {suggested} ({suggested_dt.strftime('%Y-%m-%d')})")
        logger.info("Use --locktime-date YYYY-MM for correct format")
        raise typer.Exit(1)

    # Validate locktime is in the future
    if locktime <= datetime.now().timestamp():
        logger.warning("Locktime is in the past - the bond will be immediately spendable")

    from jmcore.btc_script import disassemble_script, mk_freeze_script

    from jmwallet.wallet.address import script_to_p2wsh_address
    from jmwallet.wallet.bip32 import HDKey, mnemonic_to_seed
    from jmwallet.wallet.bond_registry import (
        create_bond_info,
        get_registry_path,
        load_registry,
        make_wallet_ownership_predicate,
        migrate_legacy_registry,
        save_registry,
    )
    from jmwallet.wallet.service import FIDELITY_BOND_BRANCH

    seed = mnemonic_to_seed(resolved_mnemonic, resolved_bip39_passphrase)
    master_key = HDKey.from_seed(seed)
    wallet_fingerprint = master_key.derive("m/0").fingerprint.hex()

    coin_type = 0 if resolved_network == "mainnet" else 1
    root_path = f"m/84'/{coin_type}'"

    # Compute the timenumber from the locktime (this is the BIP32 child index)
    from jmcore.timenumber import timestamp_to_timenumber

    timenumber = timestamp_to_timenumber(locktime)
    path = f"{root_path}/0'/{FIDELITY_BOND_BRANCH}/{timenumber}"

    key = master_key.derive(path)
    pubkey_hex = key.get_public_key_bytes(compressed=True).hex()

    witness_script = mk_freeze_script(pubkey_hex, locktime)
    address = script_to_p2wsh_address(witness_script, resolved_network)

    locktime_dt = datetime.fromtimestamp(locktime)
    disassembled = disassemble_script(witness_script)

    # Save to registry unless --no-save
    saved = False
    existing = False
    if not no_save:
        # This command does not open a WalletService, so run the one-shot
        # legacy migration here to claim this wallet's own bonds out of the
        # shared registry. Then load with the legacy fallback disabled so
        # foreign bonds are never copied into this wallet's file (#492).
        migrate_legacy_registry(
            resolved_data_dir,
            wallet_fingerprint,
            make_wallet_ownership_predicate(master_key, root_path),
        )
        registry = load_registry(resolved_data_dir, wallet_fingerprint, allow_legacy_fallback=False)
        existing_bond = registry.get_bond_by_address(address)
        if existing_bond:
            existing = True
            logger.info(f"Bond already exists in registry (created: {existing_bond.created_at})")
        else:
            bond_info = create_bond_info(
                address=address,
                locktime=locktime,
                index=timenumber,
                path=path,
                pubkey_hex=pubkey_hex,
                witness_script=witness_script,
                network=resolved_network,
            )
            registry.add_bond(bond_info)
            save_registry(registry, resolved_data_dir, wallet_fingerprint)
            saved = True

    print("\n" + "=" * 80)
    print("FIDELITY BOND ADDRESS")
    print("=" * 80)
    print(f"\nAddress:      {address}")
    print(f"Locktime:     {locktime} ({locktime_dt.strftime('%Y-%m-%d %H:%M:%S')})")
    print(f"Timenumber:   {timenumber}")
    print(f"Network:      {resolved_network}")
    print(f"Path:         {path}")
    print()
    print("-" * 80)
    print("WITNESS SCRIPT (redeemScript)")
    print("-" * 80)
    print(f"Hex:          {witness_script.hex()}")
    print(f"Disassembled: {disassembled}")
    print("-" * 80)
    if saved:
        print(f"\nSaved to registry: {get_registry_path(resolved_data_dir, wallet_fingerprint)}")
    elif existing:
        print("\nBond already in registry (not updated)")
    elif no_save:
        print("\nNot saved to registry (--no-save)")
    print("\n" + "=" * 80)
    print("IMPORTANT: Funds sent to this address are LOCKED until the locktime!")
    print("           Make sure you have backed up your mnemonic.")
    print()
    print("WARNING: You should send coins to this address only once.")
    print("         Only the single biggest value UTXO will be announced")
    print("         as a fidelity bond. Sending coins multiple times will")
    print("         NOT increase fidelity bond value.")
    print("=" * 80 + "\n")

import_bond(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, locktime: Annotated[int, typer.Option('--locktime', '-L', help='Locktime as Unix timestamp')] = 0, locktime_date: Annotated[str | None, typer.Option('--locktime-date', '-d', help='Locktime as YYYY-MM (must be 1st of month)')] = None, timenumber: Annotated[int | None, typer.Option('--timenumber', '-t', help='Timenumber (0-959). Auto-derived if omitted.')] = None, path_spec: Annotated[str | None, typer.Option('--path', '-p', help="Full derivation path with locktime, e.g. m/84'/0'/0'/2/73:1740787200")] = None, network: Annotated[str | None, typer.Option('--network', '-n')] = None, 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 (decoupled from data dir). Defaults to <data-dir>/config.toml')] = None, log_level: Annotated[str | None, typer.Option('--log-level', '-l', help='Log level')] = None) -> None

Manually import a fidelity bond into the registry.

Use this when you know the exact derivation path and locktime of a bond that was not discovered automatically. The bond address and keys are derived from your mnemonic.

Examples: jm-wallet import-bond --locktime-date 2026-02 jm-wallet import-bond --path "m/84'/0'/0'/2/73:1740787200" jm-wallet import-bond --timenumber 73

Source code in jmwallet/src/jmwallet/cli/bonds.py
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
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
@app.command("import-bond")
def import_bond(
    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,
    locktime: Annotated[
        int, typer.Option("--locktime", "-L", help="Locktime as Unix timestamp")
    ] = 0,
    locktime_date: Annotated[
        str | None,
        typer.Option("--locktime-date", "-d", help="Locktime as YYYY-MM (must be 1st of month)"),
    ] = None,
    timenumber: Annotated[
        int | None,
        typer.Option("--timenumber", "-t", help="Timenumber (0-959). Auto-derived if omitted."),
    ] = None,
    path_spec: Annotated[
        str | None,
        typer.Option(
            "--path",
            "-p",
            help="Full derivation path with locktime, e.g. m/84'/0'/0'/2/73:1740787200",
        ),
    ] = None,
    network: Annotated[str | None, typer.Option("--network", "-n")] = None,
    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 (decoupled from data dir). Defaults to <data-dir>/config.toml",
        ),
    ] = None,
    log_level: Annotated[
        str | None,
        typer.Option("--log-level", "-l", help="Log level"),
    ] = None,
) -> None:
    """
    Manually import a fidelity bond into the registry.

    Use this when you know the exact derivation path and locktime of a bond
    that was not discovered automatically. The bond address and keys are
    derived from your mnemonic.

    Examples:
        jm-wallet import-bond --locktime-date 2026-02
        jm-wallet import-bond --path "m/84'/0'/0'/2/73:1740787200"
        jm-wallet import-bond --timenumber 73
    """
    settings = setup_cli(log_level, data_dir=data_dir, config_file=config_file)

    try:
        resolved = resolve_mnemonic(
            settings,
            mnemonic_file=mnemonic_file,
            prompt_bip39_passphrase=prompt_bip39_passphrase,
        )
        if not resolved:
            raise ValueError("No mnemonic provided")
        resolved_mnemonic = resolved.mnemonic
        resolved_bip39_passphrase = resolved.bip39_passphrase
    except (FileNotFoundError, ValueError) as e:
        logger.error(str(e))
        raise typer.Exit(1)

    resolved_network = network if network is not None else settings.network_config.network.value
    resolved_data_dir = data_dir if data_dir is not None else settings.get_data_dir()

    from jmcore.timenumber import (
        is_valid_locktime,
        parse_locktime_date,
        timenumber_to_timestamp,
        timestamp_to_timenumber,
    )

    # Parse --path if provided: m/84'/0'/0'/2/73:1740787200
    if path_spec:
        parts = path_spec.rstrip("/").split("/")
        last = parts[-1]
        if ":" in last:
            parsed_timenumber = int(last.split(":")[0])
            parsed_locktime = int(last.split(":")[1])
        else:
            parsed_timenumber = int(last)
            parsed_locktime = timenumber_to_timestamp(parsed_timenumber)

        if timenumber is None:
            timenumber = parsed_timenumber
        if locktime == 0:
            locktime = parsed_locktime

    # Parse --locktime-date
    if locktime_date:
        try:
            locktime = parse_locktime_date(locktime_date)
        except ValueError as e:
            logger.error(f"Invalid locktime date: {e}")
            raise typer.Exit(1)

    # Derive timenumber from locktime or vice versa
    if locktime > 0 and timenumber is None:
        timenumber = timestamp_to_timenumber(locktime)
    elif timenumber is not None and locktime == 0:
        locktime = timenumber_to_timestamp(timenumber)

    if locktime <= 0 or timenumber is None:
        logger.error("Must specify one of: --locktime, --locktime-date, --timenumber, or --path")
        raise typer.Exit(1)

    if not is_valid_locktime(locktime):
        logger.error(f"Locktime {locktime} is not a valid fidelity bond locktime")
        raise typer.Exit(1)

    # Verify consistency
    expected_timenumber = timestamp_to_timenumber(locktime)
    if timenumber != expected_timenumber:
        logger.error(
            f"Timenumber {timenumber} does not match locktime {locktime} "
            f"(expected timenumber {expected_timenumber})"
        )
        raise typer.Exit(1)

    from jmcore.btc_script import mk_freeze_script

    from jmwallet.wallet.address import script_to_p2wsh_address
    from jmwallet.wallet.bip32 import HDKey, mnemonic_to_seed
    from jmwallet.wallet.bond_registry import (
        create_bond_info,
        get_registry_path,
        load_registry,
        make_wallet_ownership_predicate,
        migrate_legacy_registry,
        save_registry,
    )
    from jmwallet.wallet.service import FIDELITY_BOND_BRANCH

    seed = mnemonic_to_seed(resolved_mnemonic, resolved_bip39_passphrase)
    master_key = HDKey.from_seed(seed)
    wallet_fingerprint = master_key.derive("m/0").fingerprint.hex()

    coin_type = 0 if resolved_network == "mainnet" else 1
    root_path = f"m/84'/{coin_type}'"
    deriv_path = f"{root_path}/0'/{FIDELITY_BOND_BRANCH}/{timenumber}"

    key = master_key.derive(deriv_path)
    pubkey_hex = key.get_public_key_bytes(compressed=True).hex()
    witness_script = mk_freeze_script(pubkey_hex, locktime)
    address = script_to_p2wsh_address(witness_script, resolved_network)

    # Save to registry. This command does not open a WalletService, so run
    # the one-shot legacy migration here and load with the legacy fallback
    # disabled to avoid copying foreign bonds into this wallet's file (#492).
    migrate_legacy_registry(
        resolved_data_dir,
        wallet_fingerprint,
        make_wallet_ownership_predicate(master_key, root_path),
    )
    registry = load_registry(resolved_data_dir, wallet_fingerprint, allow_legacy_fallback=False)
    existing = registry.get_bond_by_address(address)
    if existing:
        print(f"\nBond already in registry (created: {existing.created_at})")
        print(f"Address: {address}")
        raise typer.Exit(0)

    bond_info = create_bond_info(
        address=address,
        locktime=locktime,
        index=timenumber,
        path=deriv_path,
        pubkey_hex=pubkey_hex,
        witness_script=witness_script,
        network=resolved_network,
    )
    registry.add_bond(bond_info)
    save_registry(registry, resolved_data_dir, wallet_fingerprint)

    from jmcore.timenumber import format_locktime_date

    locktime_str = format_locktime_date(locktime)
    print("\n" + "=" * 80)
    print("FIDELITY BOND IMPORTED")
    print("=" * 80)
    print(f"\nAddress:      {address}")
    print(f"Locktime:     {locktime} ({locktime_str})")
    print(f"Timenumber:   {timenumber}")
    print(f"Path:         {deriv_path}")
    print(f"Network:      {resolved_network}")
    print(f"\nSaved to: {get_registry_path(resolved_data_dir, wallet_fingerprint)}")
    print()
    print(
        "Next steps:\n"
        "  - If the bond was funded recently, run 'jm-wallet sync-bonds' to\n"
        "    refresh its on-chain value.\n"
        "  - If it was funded in an older block the wallet has not scanned yet,\n"
        "    run 'jm-wallet rescan' first so Bitcoin Core scans historical\n"
        "    blocks for this address; a plain sync only tracks new activity."
    )
    print("=" * 80 + "\n")

list_bonds(mnemonic_file: Annotated[Path | None, typer.Option('--mnemonic-file', '-f', envvar='MNEMONIC_FILE', help="Select the per-wallet bond registry by deriving its fingerprint from this mnemonic file. This does NOT scan the blockchain; use 'jm-wallet recover-bonds' to discover bonds on-chain.")] = None, prompt_bip39_passphrase: Annotated[bool, typer.Option('--prompt-bip39-passphrase', help='Prompt for BIP39 passphrase')] = False, wallet_fingerprint: Annotated[str | None, typer.Option('--wallet-fingerprint', help="Select the per-wallet bond registry by its 8-char hex BIP32 master fingerprint. Use this instead of --mnemonic-file when you already know the fingerprint (e.g. from 'jm-wallet info'). When neither --mnemonic-file nor this flag is provided and exactly one wallet has a registry in the data directory, that wallet is selected automatically.")] = None, 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 (decoupled from data dir). Defaults to <data-dir>/config.toml')] = None, funded_only: Annotated[bool, typer.Option('--funded-only', help='Show only funded bonds')] = False, active_only: Annotated[bool, typer.Option('--active-only', help='Show only active bonds')] = False, json_output: Annotated[bool, typer.Option('--json', '-j', help='Output as JSON')] = False, log_level: Annotated[str | None, typer.Option('--log-level', '-l', help='Log level')] = None) -> None

List fidelity bonds from the local registry (offline, no blockchain access).

This command only reads the per-wallet registry; it never scans the blockchain. Registered-but-unfunded bonds (created with generate-bond-address or import-bond but not yet funded) are shown with an UNFUNDED status. Funded status and values reflect the last on-chain sync.

To refresh funded status from the blockchain, use 'jm-wallet sync-bonds' (fast, known bonds) or 'jm-wallet recover-bonds' (full discovery scan). The per-wallet registry is selected by the fingerprint derived from --mnemonic-file, taken from --wallet-fingerprint, the configured wallet, or auto-detected when only one wallet's registry exists in the data dir.

Source code in jmwallet/src/jmwallet/cli/bonds.py
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 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
 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
122
123
124
125
126
127
128
129
130
131
132
133
@app.command()
def list_bonds(
    mnemonic_file: Annotated[
        Path | None,
        typer.Option(
            "--mnemonic-file",
            "-f",
            envvar="MNEMONIC_FILE",
            help=(
                "Select the per-wallet bond registry by deriving its "
                "fingerprint from this mnemonic file. This does NOT scan the "
                "blockchain; use 'jm-wallet recover-bonds' to discover bonds "
                "on-chain."
            ),
        ),
    ] = None,
    prompt_bip39_passphrase: Annotated[
        bool, typer.Option("--prompt-bip39-passphrase", help="Prompt for BIP39 passphrase")
    ] = False,
    wallet_fingerprint: Annotated[
        str | None,
        typer.Option(
            "--wallet-fingerprint",
            help=(
                "Select the per-wallet bond registry by its 8-char hex BIP32 "
                "master fingerprint. Use this instead of --mnemonic-file when "
                "you already know the fingerprint (e.g. from 'jm-wallet info'). "
                "When neither --mnemonic-file nor this flag is provided and "
                "exactly one wallet has a registry in the data directory, that "
                "wallet is selected automatically."
            ),
        ),
    ] = None,
    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 (decoupled from data dir). Defaults to <data-dir>/config.toml",
        ),
    ] = None,
    funded_only: Annotated[
        bool,
        typer.Option("--funded-only", help="Show only funded bonds"),
    ] = False,
    active_only: Annotated[
        bool,
        typer.Option("--active-only", help="Show only active bonds"),
    ] = False,
    json_output: Annotated[
        bool,
        typer.Option("--json", "-j", help="Output as JSON"),
    ] = False,
    log_level: Annotated[
        str | None,
        typer.Option("--log-level", "-l", help="Log level"),
    ] = None,
) -> None:
    """
    List fidelity bonds from the local registry (offline, no blockchain access).

    This command only reads the per-wallet registry; it never scans the
    blockchain. Registered-but-unfunded bonds (created with
    generate-bond-address or import-bond but not yet funded) are shown with an
    UNFUNDED status. Funded status and values reflect the last on-chain sync.

    To refresh funded status from the blockchain, use 'jm-wallet sync-bonds'
    (fast, known bonds) or 'jm-wallet recover-bonds' (full discovery scan). The
    per-wallet registry is selected by the fingerprint derived from
    --mnemonic-file, taken from --wallet-fingerprint, the configured wallet, or
    auto-detected when only one wallet's registry exists in the data dir.
    """
    settings = setup_cli(log_level, data_dir=data_dir, config_file=config_file)
    resolved_data_dir = data_dir if data_dir else settings.get_data_dir()

    from jmwallet.cli._wallet_selection import resolve_wallet_fingerprint
    from jmwallet.wallet.bond_registry import list_registry_fingerprints

    fingerprint = resolve_wallet_fingerprint(
        settings,
        mnemonic_file=mnemonic_file,
        wallet_fingerprint=wallet_fingerprint,
        prompt_bip39_passphrase=prompt_bip39_passphrase,
        list_known_fingerprints=lambda: list_registry_fingerprints(resolved_data_dir),
        command_label="jm-wallet list-bonds",
        fall_back_to_configured_mnemonic=True,
    )
    if fingerprint is None:
        logger.error(
            "No bond registry found in this data directory and no wallet "
            "identity was provided. Pass --mnemonic-file (with "
            "--prompt-bip39-passphrase if needed) or --wallet-fingerprint."
        )
        raise typer.Exit(1)
    _list_bonds_offline(
        data_dir=resolved_data_dir,
        fingerprint=fingerprint,
        funded_only=funded_only,
        active_only=active_only,
        json_output=json_output,
    )

recover_bonds(mark_scanned: Annotated[bool, typer.Option('--mark-scanned', help='Confirm prior full bond recovery and record completion without scanning (offline).')] = False, 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, backend_type: Annotated[str | None, typer.Option('--backend', '-b', help='Backend: descriptor_wallet | neutrino')] = None, rpc_url: Annotated[str | None, typer.Option('--rpc-url', envvar='BITCOIN_RPC_URL')] = None, neutrino_url: Annotated[str | None, typer.Option('--neutrino-url', envvar='NEUTRINO_URL')] = None, 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 (decoupled from data dir). Defaults to <data-dir>/config.toml')] = None, log_level: Annotated[str | None, typer.Option('--log-level', '-l', help='Log level')] = None) -> None

Recover fidelity bonds by scanning all 960 possible timelocks.

This command scans the blockchain for fidelity bonds at all valid timenumber locktimes (Jan 2020 through Dec 2099). Use this when recovering a wallet from mnemonic and you don't know which locktimes were used for fidelity bonds.

Each timenumber (0-959) maps to exactly one address, matching the reference JoinMarket implementation.

With --mark-scanned, only record your confirmation that full bond recovery already completed. This does not scan or verify coverage. A regular wallet history scan alone is not sufficient. Requires a mnemonic file and prompts for confirmation; use the same BIP39 passphrase as the recovered wallet.

Source code in jmwallet/src/jmwallet/cli/bonds.py
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
@app.command("recover-bonds")
def recover_bonds(
    mark_scanned: Annotated[
        bool,
        typer.Option(
            "--mark-scanned",
            help=(
                "Confirm prior full bond recovery and record completion without scanning (offline)."
            ),
        ),
    ] = False,
    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,
    backend_type: Annotated[
        str | None,
        typer.Option("--backend", "-b", help="Backend: descriptor_wallet | neutrino"),
    ] = None,
    rpc_url: Annotated[str | None, typer.Option("--rpc-url", envvar="BITCOIN_RPC_URL")] = None,
    neutrino_url: Annotated[
        str | None, typer.Option("--neutrino-url", envvar="NEUTRINO_URL")
    ] = None,
    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 (decoupled from data dir). Defaults to <data-dir>/config.toml",
        ),
    ] = None,
    log_level: Annotated[
        str | None,
        typer.Option("--log-level", "-l", help="Log level"),
    ] = None,
) -> None:
    """
    Recover fidelity bonds by scanning all 960 possible timelocks.

    This command scans the blockchain for fidelity bonds at all valid
    timenumber locktimes (Jan 2020 through Dec 2099). Use this when
    recovering a wallet from mnemonic and you don't know which locktimes
    were used for fidelity bonds.

    Each timenumber (0-959) maps to exactly one address, matching the
    reference JoinMarket implementation.

    With --mark-scanned, only record your confirmation that full bond recovery
    already completed. This does not scan or verify coverage. A regular wallet
    history scan alone is not sufficient. Requires a mnemonic file and prompts
    for confirmation; use the same BIP39 passphrase as the recovered wallet.
    """
    settings = setup_cli(log_level, data_dir=data_dir, config_file=config_file)

    try:
        resolved = resolve_mnemonic(
            settings,
            mnemonic_file=mnemonic_file,
            prompt_bip39_passphrase=prompt_bip39_passphrase,
        )
        if not resolved:
            raise ValueError("No mnemonic provided")
        resolved_mnemonic = resolved.mnemonic
        resolved_bip39_passphrase = resolved.bip39_passphrase
        resolved_creation_height = resolved.creation_height
    except (FileNotFoundError, ValueError) as e:
        logger.error(str(e))
        raise typer.Exit(1)

    if mark_scanned:
        from jmwallet.backends.descriptor_wallet import get_mnemonic_fingerprint
        from jmwallet.cli.mnemonic import (
            FidelityBondRecoveryInProgressError,
            acknowledge_fidelity_bond_recovery_scanned,
        )

        if resolved.mnemonic_file is None:
            logger.error("--mark-scanned requires a mnemonic file; select it with --mnemonic-file")
            raise typer.Exit(1)
        fingerprint = get_mnemonic_fingerprint(resolved_mnemonic, resolved_bip39_passphrase)
        print(f"Mnemonic file: {resolved.mnemonic_file}")
        print(f"Wallet fingerprint: {fingerprint}")
        print(
            "This only records your confirmation; it does not scan, discover bonds, or verify "
            "coverage. A regular wallet history scan (including the default one-year scan) "
            "does not prove all 960 bond addresses were scanned. "
            "Do not confirm while a recovery scan is still running."
        )
        typer.confirm(
            "Has full fidelity bond recovery already completed for this wallet?",
            default=False,
            abort=True,
        )
        try:
            acknowledge_fidelity_bond_recovery_scanned(resolved.mnemonic_file, fingerprint)
        except (OSError, FidelityBondRecoveryInProgressError) as e:
            logger.error(str(e))
            raise typer.Exit(1)
        print("Recorded user-confirmed fidelity bond recovery completion. No scan was performed.")
        return

    # Resolve backend settings
    backend_settings = resolve_backend_settings(
        settings,
        network=network,
        backend_type=backend_type,
        rpc_url=rpc_url,
        neutrino_url=neutrino_url,
        data_dir=data_dir,
    )

    asyncio.run(
        _recover_bonds_async(
            resolved_mnemonic,
            backend_settings,
            resolved_bip39_passphrase,
            creation_height=resolved_creation_height,
            mnemonic_file=resolved.mnemonic_file,
            mixdepth_count=settings.wallet.mixdepth_count,
            max_sats_freeze_reuse=settings.wallet.max_sats_freeze_reuse,
            reconstruct_history=settings.wallet.reconstruct_history,
        )
    )

sync_bonds(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, backend_type: Annotated[str | None, typer.Option('--backend', '-b', help='Backend: descriptor_wallet | neutrino')] = None, rpc_url: Annotated[str | None, typer.Option('--rpc-url', envvar='BITCOIN_RPC_URL')] = None, neutrino_url: Annotated[str | None, typer.Option('--neutrino-url', envvar='NEUTRINO_URL')] = None, 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 (decoupled from data dir). Defaults to <data-dir>/config.toml')] = None, log_level: Annotated[str | None, typer.Option('--log-level', '-l', help='Log level')] = None) -> None

Refresh funded status of bonds already in the registry (fast).

Syncs only the bond addresses already recorded in the per-wallet registry and updates their on-chain UTXO info (value, confirmations). Unlike recover-bonds, this does NOT scan all 960 possible timelocks, so it is the quick way to reflect a funding transaction after creating a bond with generate-bond-address. Use recover-bonds instead when you need to discover bonds whose addresses are not yet in the registry.

Source code in jmwallet/src/jmwallet/cli/bonds.py
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
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
@app.command("sync-bonds")
def sync_bonds(
    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,
    backend_type: Annotated[
        str | None,
        typer.Option("--backend", "-b", help="Backend: descriptor_wallet | neutrino"),
    ] = None,
    rpc_url: Annotated[str | None, typer.Option("--rpc-url", envvar="BITCOIN_RPC_URL")] = None,
    neutrino_url: Annotated[
        str | None, typer.Option("--neutrino-url", envvar="NEUTRINO_URL")
    ] = None,
    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 (decoupled from data dir). Defaults to <data-dir>/config.toml",
        ),
    ] = None,
    log_level: Annotated[
        str | None,
        typer.Option("--log-level", "-l", help="Log level"),
    ] = None,
) -> None:
    """
    Refresh funded status of bonds already in the registry (fast).

    Syncs only the bond addresses already recorded in the per-wallet registry
    and updates their on-chain UTXO info (value, confirmations). Unlike
    recover-bonds, this does NOT scan all 960 possible timelocks, so it is the
    quick way to reflect a funding transaction after creating a bond with
    generate-bond-address. Use recover-bonds instead when you need to discover
    bonds whose addresses are not yet in the registry.
    """
    settings = setup_cli(log_level, data_dir=data_dir, config_file=config_file)

    try:
        resolved = resolve_mnemonic(
            settings,
            mnemonic_file=mnemonic_file,
            prompt_bip39_passphrase=prompt_bip39_passphrase,
        )
        if not resolved:
            raise ValueError("No mnemonic provided")
        resolved_mnemonic = resolved.mnemonic
        resolved_bip39_passphrase = resolved.bip39_passphrase
        resolved_creation_height = resolved.creation_height
    except (FileNotFoundError, ValueError) as e:
        logger.error(str(e))
        raise typer.Exit(1)

    backend_settings = resolve_backend_settings(
        settings,
        network=network,
        backend_type=backend_type,
        rpc_url=rpc_url,
        neutrino_url=neutrino_url,
        data_dir=data_dir,
    )

    asyncio.run(
        _sync_bonds_async(
            resolved_mnemonic,
            backend_settings,
            resolved_bip39_passphrase,
            creation_height=resolved_creation_height,
            mnemonic_file=resolved.mnemonic_file,
            mixdepth_count=settings.wallet.mixdepth_count,
            max_sats_freeze_reuse=settings.wallet.max_sats_freeze_reuse,
            reconstruct_history=settings.wallet.reconstruct_history,
        )
    )