Skip to content

jmwallet.commitment_history

jmwallet.commitment_history

Initialize taker commitment history for a data directory's first generated wallet.

Attributes

Functions:

generated_wallet_is_authorized(data_dir: Path, mnemonic: str) -> bool

Require durable affirmative generation evidence, never infer it from absence.

Source code in jmwallet/src/jmwallet/commitment_history.py
38
39
40
41
42
43
44
45
46
def generated_wallet_is_authorized(data_dir: Path, mnemonic: str) -> bool:
    """Require durable affirmative generation evidence, never infer it from absence."""
    try:
        path = _authorization_path(data_dir, mnemonic)
        if path.parent.is_symlink():
            return False
        return read_private_file(path) == _GENERATION_PROOF
    except OSError:
        return False

history_requires_generation_authorization(data_dir: Path, history: dict[str, object]) -> bool

Retain the restriction even if another client rewrites unknown JSON fields.

Source code in jmwallet/src/jmwallet/commitment_history.py
21
22
23
24
25
def history_requires_generation_authorization(data_dir: Path, history: dict[str, object]) -> bool:
    """Retain the restriction even if another client rewrites unknown JSON fields."""
    return history.get(GENERATED_WALLETS_ONLY) is True or os.path.lexists(
        data_dir / "cmtdata" / _GENERATED_WALLETS_DIR
    )

initialize_commitment_history_for_new_wallet(data_dir: Path, *, mnemonic: str, wallet_file: Path, first_wallet: bool) -> None

Authorize a generated mnemonic, initializing only a still-unused directory.

Existing automatic histories can admit another freshly generated mnemonic without rewriting commitments. Imports and recovery must never call this. Failure is nonfatal to saving the wallet; it grants no taker authorization.

Source code in jmwallet/src/jmwallet/commitment_history.py
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def initialize_commitment_history_for_new_wallet(
    data_dir: Path, *, mnemonic: str, wallet_file: Path, first_wallet: bool
) -> None:
    """Authorize a generated mnemonic, initializing only a still-unused directory.

    Existing automatic histories can admit another freshly generated mnemonic
    without rewriting commitments. Imports and recovery must never call this.
    Failure is nonfatal to saving the wallet; it grants no taker authorization.
    """
    try:
        if wallet_file.parent.resolve() != (data_dir / "wallets").resolve():
            return
        if not wallet_file.is_file():
            return
        history_path = data_dir / "cmtdata" / "commitments.json"
        try:
            with history_path.open(encoding="utf-8") as history:
                data = json.load(history)
        except FileNotFoundError:
            if not first_wallet or not is_first_wallet_in_data_dir(
                data_dir, wallet_file, saved_wallet=True
            ):
                return
            create_history = True
        else:
            # Never replace or rewrite an existing history, even to enroll a new
            # seed. Independent proof files avoid racing a taker's history save.
            if not isinstance(data, dict) or not history_requires_generation_authorization(
                data_dir, data
            ):
                return
            create_history = False

        authorization = _authorization_path(data_dir, mnemonic)
        try:
            create_private_file_exclusive(authorization, _GENERATION_PROOF)
        except FileExistsError:
            if not generated_wallet_is_authorized(data_dir, mnemonic):
                raise OSError("Existing generation authorization is invalid") from None
        if not create_history:
            return
        # Recheck after every awaited preparation and after recording our proof.
        # A newly appeared backup or another wallet is not permission to reset.
        if not is_first_wallet_in_data_dir(
            data_dir, wallet_file, saved_wallet=True, authorization=authorization
        ):
            return
        try:
            create_commitment_history(data_dir, generated_wallets_only=True)
        except FileExistsError:
            return
    except (OSError, ValueError, TypeError) as exc:
        logger.warning(
            "Commitment-history setup needs operator action before CoinJoin. "
            "Preserve existing state and follow the taker recovery guidance."
        )
        logger.bind(sensitive=True).warning(f"Commitment history initialization failed: {exc}")
        return
    logger.info("Initialized empty commitment history for the new wallet")

is_first_wallet_in_data_dir(data_dir: Path, wallet_file: Path, *, saved_wallet: bool = False, authorization: Path | None = None) -> bool

Return True if a new wallet file would start an unused data directory.

Call before saving and recheck before initialization, allowing only the exact saved wallet's own artifacts. Unknown files, including hidden wallets and backups, never prove that a directory is unused.

Source code in jmwallet/src/jmwallet/commitment_history.py
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
def is_first_wallet_in_data_dir(
    data_dir: Path,
    wallet_file: Path,
    *,
    saved_wallet: bool = False,
    authorization: Path | None = None,
) -> bool:
    """Return True if a new wallet file would start an unused data directory.

    Call before saving and recheck before initialization, allowing only the exact
    saved wallet's own artifacts. Unknown files, including hidden wallets and
    backups, never prove that a directory is unused.
    """
    try:
        wallets_dir = data_dir / "wallets"
        if wallet_file.parent.resolve(strict=False) != wallets_dir.resolve(strict=False):
            return False
        if any(
            os.path.lexists(data_dir / name) for name in (HISTORY_FILENAME, LEGACY_HISTORY_FILENAME)
        ):
            return False
        ignored = {".wallet-operation.lock"}
        if saved_wallet:
            # Ignore only artifacts of this exact generated wallet, not every
            # hidden file or similarly named backup belonging to an older wallet.
            ignored.update(
                {
                    wallet_file.name,
                    wallet_file.name + ".meta",
                    wallet_file.name + ".meta.lock",
                    wallet_file.name + ".meta.recovery.lock",
                }
            )
        if _has_entries(wallets_dir, ignore=frozenset(ignored)):
            return False
        if authorization is None:
            return not _has_entries(data_dir / "cmtdata")
        return not (
            _has_entries(data_dir / "cmtdata", ignore=frozenset({_GENERATED_WALLETS_DIR}))
            or _has_entries(authorization.parent, ignore=frozenset({authorization.name}))
        )
    except OSError:
        return False