Skip to content

jmwalletd.routers.wallet

jmwalletd.routers.wallet

Wallet lifecycle and info endpoints.

Covers: getinfo, session, wallet/all, wallet/create, wallet/recover, wallet/{name}/unlock, wallet/{name}/lock, token refresh.

Attributes

router = APIRouter() module-attribute

Classes

Functions:

get_info() -> GetInfoResponse async

Return backend information.

Source code in jmwalletd/src/jmwalletd/routers/wallet.py
145
146
147
148
149
150
@router.get("/getinfo", operation_id="version")
async def get_info() -> GetInfoResponse:
    """Return backend information."""
    from jmcore.version import __version__

    return GetInfoResponse(version=__version__, backend="joinmarket-ng")

get_session(request: Request, state: DaemonState = Depends(get_daemon_state)) -> SessionResponse async

Heartbeat / status endpoint.

If an Authorization header is present, it is validated. An invalid token returns 401. A missing token is fine (unauthenticated access).

Source code in jmwalletd/src/jmwalletd/routers/wallet.py
156
157
158
159
160
161
162
163
164
165
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
@router.get("/session", operation_id="session")
async def get_session(
    request: Request,
    state: DaemonState = Depends(get_daemon_state),
) -> SessionResponse:
    """Heartbeat / status endpoint.

    If an Authorization header is present, it is validated. An invalid
    token returns 401. A missing token is fine (unauthenticated access).
    """
    token = get_optional_token(request)
    token_valid = False

    if token is not None:
        try:
            state.token_authority.verify_access(token)
            token_valid = True
        except pyjwt.InvalidTokenError as exc:
            raise InvalidToken(str(exc)) from exc

    # Bitcoin Core is the source of truth for rescan state: the in-memory
    # flag can go stale while Core keeps scanning server-side (issue #551).
    rescanning, _progress = await state.live_rescan_status()

    resp = SessionResponse(
        session=state.wallet_loaded,
        maker_running=state.maker_running,
        coinjoin_in_process=state.taker_running,
        wallet_name=state.wallet_name if state.wallet_loaded else "",
        rescanning=rescanning,
    )

    # Populate extra fields only when authenticated.
    if state.wallet_loaded and token_valid:
        resp.schedule = _get_running_tumble_schedule(state)
        resp.nickname = state.nickname

        # Read offer_list directly from the running maker bot so that the
        # frontend receives it as soon as offers are created (the old path
        # through state.offer_list was unreachable because maker.start()
        # blocks until shutdown).
        offer_list = _get_offer_list_from_maker(state)
        resp.offer_list = offer_list if offer_list else state.offer_list

        try:
            backend = state.wallet_service.backend
            resp.block_height = await backend.get_block_height()
        except Exception:
            resp.block_height = None

        # Expose the underlying bitcoind descriptor wallet name for clients
        # (e.g. test setup / debugging tools) that need to query Bitcoin Core
        # directly. Only present when the active backend is a descriptor
        # wallet — other backends (Neutrino) leave this unset.
        try:
            backend = state.wallet_service.backend
            wallet_name_attr = getattr(backend, "wallet_name", None)
            if isinstance(wallet_name_attr, str) and wallet_name_attr:
                resp.descriptor_wallet_name = wallet_name_attr
        except Exception:
            resp.descriptor_wallet_name = None

    return resp

list_wallets(state: DaemonState = Depends(get_daemon_state)) -> ListWalletsResponse async

List available wallet files.

Source code in jmwalletd/src/jmwalletd/routers/wallet.py
224
225
226
227
228
229
@router.get("/wallet/all", operation_id="listwallets")
async def list_wallets(
    state: DaemonState = Depends(get_daemon_state),
) -> ListWalletsResponse:
    """List available wallet files."""
    return ListWalletsResponse(wallets=state.list_wallets())

token_refresh(body: TokenRequest, _auth: dict[str, Any] = Depends(require_auth_allow_expired), state: DaemonState = Depends(get_daemon_state)) -> TokenResponse async

Refresh the access/refresh token pair.

Source code in jmwalletd/src/jmwalletd/routers/wallet.py
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
@router.post("/token", operation_id="token")
async def token_refresh(
    body: TokenRequest,
    _auth: dict[str, Any] = Depends(require_auth_allow_expired),
    state: DaemonState = Depends(get_daemon_state),
) -> TokenResponse:
    """Refresh the access/refresh token pair."""
    if body.grant_type != "refresh_token":
        raise InvalidRequestFormat("Unsupported grant_type. Must be 'refresh_token'.")

    try:
        state.token_authority.verify_refresh(body.refresh_token)
    except pyjwt.InvalidTokenError as exc:
        logger.debug("Refresh token verification failed: {}", exc)
        raise InvalidToken(f"Invalid refresh token: {exc}") from exc

    tokens = state.token_authority.issue(state.wallet_name)

    return TokenResponse(
        walletname=state.wallet_name,
        token=tokens.token,
        token_type=tokens.token_type,
        expires_in=tokens.expires_in,
        scope=tokens.scope,
        refresh_token=tokens.refresh_token,
    )

wallet_create(body: CreateWalletRequest, state: DaemonState = Depends(get_daemon_state)) -> CreateWalletResponse async

Create a new wallet.

Source code in jmwalletd/src/jmwalletd/routers/wallet.py
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
@router.post("/wallet/create", status_code=201, operation_id="createwallet")
async def wallet_create(
    body: CreateWalletRequest,
    state: DaemonState = Depends(get_daemon_state),
) -> CreateWalletResponse:
    """Create a new wallet."""
    if state.wallet_loaded:
        raise WalletAlreadyUnlocked()

    wallet_path = state.wallets_dir / body.walletname
    if wallet_path.exists():
        raise WalletAlreadyExists()

    try:
        wallet_service, seedphrase = await create_wallet(
            wallet_path=wallet_path,
            password=body.password,
            wallet_type=body.wallettype,
            data_dir=state.data_dir,
        )
    except FileExistsError as exc:
        raise WalletAlreadyExists() from exc
    except OSError as exc:
        raise LockExists(str(exc)) from exc
    except ValueError as exc:
        raise InvalidRequestFormat(str(exc)) from exc

    state.wallet_service = wallet_service
    state.wallet_mnemonic = seedphrase
    state.wallet_name = body.walletname
    state.wallet_password = body.password

    # A generated wallet has no pre-existing history to suppress, so monitoring
    # can become live without risking a readiness error after seed generation.
    state.start_tx_monitor(baseline_existing=False)
    await _require_tx_monitor_ready(state)

    tokens = state.token_authority.issue(body.walletname)

    return CreateWalletResponse(
        walletname=body.walletname,
        seedphrase=seedphrase,
        token=tokens.token,
        token_type=tokens.token_type,
        expires_in=tokens.expires_in,
        scope=tokens.scope,
        refresh_token=tokens.refresh_token,
    )

wallet_lock(walletname: str, _auth: dict[str, Any] = Depends(require_auth), _wallet: None = Depends(require_wallet_match), state: DaemonState = Depends(get_daemon_state)) -> LockWalletResponse async

Lock the current wallet and stop all services.

Source code in jmwalletd/src/jmwalletd/routers/wallet.py
420
421
422
423
424
425
426
427
428
429
@router.get("/wallet/{walletname}/lock", operation_id="lockwallet")
async def wallet_lock(
    walletname: str,
    _auth: dict[str, Any] = Depends(require_auth),
    _wallet: None = Depends(require_wallet_match),
    state: DaemonState = Depends(get_daemon_state),
) -> LockWalletResponse:
    """Lock the current wallet and stop all services."""
    already_locked = await state.lock_wallet()
    return LockWalletResponse(walletname=walletname, already_locked=already_locked)

wallet_recover(body: RecoverWalletRequest, state: DaemonState = Depends(get_daemon_state)) -> CreateWalletResponse async

Recover a wallet from a seed phrase.

Source code in jmwalletd/src/jmwalletd/routers/wallet.py
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
@router.post("/wallet/recover", status_code=201, operation_id="recoverwallet")
async def wallet_recover(
    body: RecoverWalletRequest,
    state: DaemonState = Depends(get_daemon_state),
) -> CreateWalletResponse:
    """Recover a wallet from a seed phrase."""
    if state.wallet_loaded:
        raise WalletAlreadyUnlocked()

    wallet_path = state.wallets_dir / body.walletname
    if wallet_path.exists():
        raise WalletAlreadyExists()

    try:
        wallet_service = await recover_wallet(
            wallet_path=wallet_path,
            password=body.password,
            wallet_type=body.wallettype,
            seedphrase=body.seedphrase,
            data_dir=state.data_dir,
        )
    except FileExistsError as exc:
        raise WalletAlreadyExists() from exc
    except OSError as exc:
        raise LockExists(str(exc)) from exc
    except ValueError as exc:
        raise InvalidRequestFormat(str(exc)) from exc

    state.wallet_service = wallet_service
    state.wallet_mnemonic = body.seedphrase
    state.wallet_name = body.walletname
    state.wallet_password = body.password

    state.start_tx_monitor()
    try:
        await _require_tx_monitor_ready(state, lock_on_failure=True)
    except BackendNotReady:
        # Recovery is a create operation. Remove the encrypted file so the
        # caller can retry the same request after a transient backend outage.
        try:
            wallet_path.unlink(missing_ok=True)
        except OSError:
            logger.exception("Failed to roll back wallet recovery for {}", body.walletname)
        raise

    tokens = state.token_authority.issue(body.walletname)

    return CreateWalletResponse(
        walletname=body.walletname,
        seedphrase=body.seedphrase,
        token=tokens.token,
        token_type=tokens.token_type,
        expires_in=tokens.expires_in,
        scope=tokens.scope,
        refresh_token=tokens.refresh_token,
    )

wallet_unlock(walletname: str, body: UnlockWalletRequest, state: DaemonState = Depends(get_daemon_state)) -> UnlockWalletResponse async

Unlock (decrypt) a wallet.

Source code in jmwalletd/src/jmwalletd/routers/wallet.py
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
@router.post("/wallet/{walletname}/unlock", operation_id="unlockwallet")
async def wallet_unlock(
    walletname: str,
    body: UnlockWalletRequest,
    state: DaemonState = Depends(get_daemon_state),
) -> UnlockWalletResponse:
    """Unlock (decrypt) a wallet."""
    wallet_path = state.wallets_dir / walletname
    if not wallet_path.exists():
        raise WalletNotFound()

    # If the same wallet is already unlocked, just verify password and re-issue tokens.
    if state.wallet_loaded and state.wallet_name == walletname:
        if body.password != state.wallet_password:
            raise InvalidCredentials()
        await _require_tx_monitor_ready(state, lock_on_failure=True)
        tokens = state.token_authority.issue(walletname)
        return UnlockWalletResponse(
            walletname=walletname,
            token=tokens.token,
            token_type=tokens.token_type,
            expires_in=tokens.expires_in,
            scope=tokens.scope,
            refresh_token=tokens.refresh_token,
        )

    # If a different wallet is loaded, lock it first.
    if state.wallet_loaded:
        await state.lock_wallet()

    try:
        wallet_service, seedphrase = await open_wallet_with_mnemonic(
            wallet_path=wallet_path,
            password=body.password,
            data_dir=state.data_dir,
            sync_on_open=False,
        )
    except OSError as exc:
        raise LockExists(str(exc)) from exc
    except ValueError as exc:
        raise InvalidCredentials(str(exc)) from exc

    state.wallet_service = wallet_service
    state.wallet_mnemonic = seedphrase
    state.wallet_name = walletname
    state.wallet_password = body.password

    # Kick off sync asynchronously so unlock returns immediately.
    if state._wallet_sync_task is not None and not state._wallet_sync_task.done():
        state._wallet_sync_task.cancel()
    state._wallet_sync_task = asyncio.create_task(_background_wallet_sync(state, walletname))

    # Start pushing WebSocket notifications for wallet transactions (issue #560).
    state.start_tx_monitor()
    await _require_tx_monitor_ready(state, lock_on_failure=True)

    tokens = state.token_authority.issue(walletname)

    return UnlockWalletResponse(
        walletname=walletname,
        token=tokens.token,
        token_type=tokens.token_type,
        expires_in=tokens.expires_in,
        scope=tokens.scope,
        refresh_token=tokens.refresh_token,
    )