Skip to content

jmwallet.cli.bonds

jmwallet.cli.bonds

Fidelity bond commands: list-bonds, generate-bond-address, 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', help='Data directory (default: ~/.joinmarket-ng or $JOINMARKET_DATA_DIR)')] = 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
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
@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",
            help="Data directory (default: ~/.joinmarket-ng or $JOINMARKET_DATA_DIR)",
        ),
    ] = 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)

    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,
        load_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)

    coin_type = 0 if resolved_network == "mainnet" else 1

    # 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"m/84'/{coin_type}'/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:
        registry = load_registry(resolved_data_dir)
        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)
            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: {resolved_data_dir / 'fidelity_bonds.json'}")
    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', help='Data directory (default: ~/.joinmarket-ng or $JOINMARKET_DATA_DIR)')] = 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
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
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
@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",
            help="Data directory (default: ~/.joinmarket-ng or $JOINMARKET_DATA_DIR)",
        ),
    ] = 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)

    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,
        load_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)

    coin_type = 0 if resolved_network == "mainnet" else 1
    deriv_path = f"m/84'/{coin_type}'/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
    registry = load_registry(resolved_data_dir)
    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)

    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: {resolved_data_dir / 'fidelity_bonds.json'}")
    print()
    print(
        "Note: The bond UTXO will be detected on the next wallet sync.\n"
        "      Run 'jm-wallet balance' to trigger a sync."
    )
    print("=" * 80 + "\n")

list_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: scantxoutset | descriptor_wallet | neutrino')] = None, rpc_url: Annotated[str | None, typer.Option('--rpc-url', envvar='BITCOIN_RPC_URL')] = None, locktimes: Annotated[list[int] | None, typer.Option('--locktime', '-L', help='Locktime(s) to scan for')] = None, data_dir: Annotated[Path | None, typer.Option('--data-dir', help='Data directory (default: ~/.joinmarket-ng or $JOINMARKET_DATA_DIR)')] = None, funded_only: Annotated[bool, typer.Option('--funded-only', help='Show only funded bonds (offline mode)')] = False, active_only: Annotated[bool, typer.Option('--active-only', help='Show only active bonds (offline mode)')] = False, json_output: Annotated[bool, typer.Option('--json', '-j', help='Output as JSON (offline mode)')] = False, log_level: Annotated[str | None, typer.Option('--log-level', '-l', help='Log level')] = None) -> None

List all fidelity bonds in the wallet.

Without --mnemonic-file: shows bonds from the local registry (offline, fast). With --mnemonic-file: scans the blockchain for bonds and updates the registry.

Source code in jmwallet/src/jmwallet/cli/bonds.py
 24
 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
@app.command()
def list_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: scantxoutset | descriptor_wallet | neutrino"
        ),
    ] = None,
    rpc_url: Annotated[str | None, typer.Option("--rpc-url", envvar="BITCOIN_RPC_URL")] = None,
    locktimes: Annotated[
        list[int] | None, typer.Option("--locktime", "-L", help="Locktime(s) to scan for")
    ] = None,
    data_dir: Annotated[
        Path | None,
        typer.Option(
            "--data-dir",
            help="Data directory (default: ~/.joinmarket-ng or $JOINMARKET_DATA_DIR)",
        ),
    ] = None,
    funded_only: Annotated[
        bool,
        typer.Option("--funded-only", help="Show only funded bonds (offline mode)"),
    ] = False,
    active_only: Annotated[
        bool,
        typer.Option("--active-only", help="Show only active bonds (offline mode)"),
    ] = False,
    json_output: Annotated[
        bool,
        typer.Option("--json", "-j", help="Output as JSON (offline mode)"),
    ] = False,
    log_level: Annotated[
        str | None,
        typer.Option("--log-level", "-l", help="Log level"),
    ] = None,
) -> None:
    """
    List all fidelity bonds in the wallet.

    Without --mnemonic-file: shows bonds from the local registry (offline, fast).
    With --mnemonic-file: scans the blockchain for bonds and updates the registry.
    """
    settings = setup_cli(log_level)

    # If no mnemonic provided, show bonds from registry (offline mode)
    if mnemonic_file is None and not any(v is not None for v in [rpc_url, backend_type]):
        _list_bonds_offline(
            data_dir=data_dir or settings.get_data_dir(),
            funded_only=funded_only,
            active_only=active_only,
            json_output=json_output,
        )
        return

    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)

    # Resolve backend settings with CLI overrides taking priority
    backend = resolve_backend_settings(
        settings,
        network=network,
        backend_type=backend_type,
        rpc_url=rpc_url,
        data_dir=data_dir,
    )

    asyncio.run(
        _list_fidelity_bonds(
            resolved_mnemonic,
            backend,
            locktimes or [],
            resolved_bip39_passphrase,
            creation_height=resolved_creation_height,
        )
    )

recover_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: scantxoutset | 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', help='Data directory (default: ~/.joinmarket-ng or $JOINMARKET_DATA_DIR)')] = 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.

Source code in jmwallet/src/jmwallet/cli/bonds.py
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
@app.command("recover-bonds")
def recover_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: scantxoutset | 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",
            help="Data directory (default: ~/.joinmarket-ng or $JOINMARKET_DATA_DIR)",
        ),
    ] = 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.
    """
    settings = setup_cli(log_level)

    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)

    # 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,
        )
    )