xln

XLN Recovery and Watchtower Protocol

Status: protocol spec and implementation tracker, updated for 0.1.5 Scope: account-state recovery, peer refresh, watchtower storage, and offline dispute protection Audience: runtime, wallet, hub, relay, and protocol implementers

Executive Summary

BrainVault can restore the user’s keys on a new computer, but it cannot restore bilateral account state by itself. XLN needs a recovery layer that makes a fresh install converge back to the user’s latest safe state with no manual backup ceremony.

The recovery order has three layers:

  1. Local encrypted backup: restore the latest user-controlled Runtime bundle before contacting any service.
  2. Watchtower Vault: independent services store the last K compact encrypted recovery bundles per account, keyed by deterministic blinded slots. Advanced towers also monitor J-layer disputes and publish the user’s latest valid proof when the user is offline.
  3. Optional peer assistance: Peer State Refresh (PSR) or a recovery relay may supply independently verifiable signed evidence when local and tower copies are unavailable. Launch safety must not depend on a hub answering.

The user flow must be: install wallet, enter the same BrainVault inputs, derive the same runtime identity, try local backup then independent towers, verify every bundle locally, and restore account machines. Peer assistance is optional; if recovery evidence remains unavailable, the wallet offers an explicit on-chain dispute/exit rather than silently creating fresh state.

Lightning Lessons

Lightning separates three concerns that XLN should also keep separate:

Sources are listed at the end.

Current XLN Fit

XLN already has most of the raw material:

Implemented in the current repo:

Still missing or incomplete:

Goals

Non-goals

Protocol Layers

Layer 0: BrainVault Identity

BrainVault restores deterministic wallet material from the same name, passphrase, and shard settings. That gives the wallet the same signer addresses and entity ids.

BrainVault does not restore:

So after BrainVault unlock, the wallet enters Recovery Discovery rather than assuming a fresh empty runtime is safe.

Layer 1: Account Discovery

At account opening, both sides create an AccountOpenAnchorV1 and publish it to selected relays/towers:

type AccountOpenAnchorV1 = {
  version: 1;
  jurisdictionId: string;
  accountId: string;              // canonical H(leftEntity, rightEntity, jurisdiction)
  leftEntityId: string;
  rightEntityId: string;
  openedAtRuntimeHeight: number;
  openedAtJHeight: number;
  recoveryEndpoints: string[];    // relay, hub, tower, or direct endpoint URLs
  ownerRecoveryPubkey: string;    // derived from BrainVault recovery branch
  counterpartyRecoveryPubkey?: string;
  anchorHash: string;
  leftHanko?: string;
  rightHanko?: string;
};

The relay may store a public form or a blinded form:

public lookup:  entityId -> account anchors
blinded lookup: H("xln/recovery/discovery/v1" || recoveryPubkey || entityId)

For consumer UX, hubs should publish anchors automatically. Privacy-sensitive users can use blinded discovery plus local contact lists.

Optional Layer 3: Peer State Refresh

Peer State Refresh is the simple mechanism from the prompt: periodically ping existing accounts and ask for the latest state.

Request:

type PeerStateRequestV1 = {
  type: "peer_state_request";
  version: 1;
  requesterEntityId: string;
  accountId: string;
  knownHeight?: number;
  knownStateHash?: string;
  challenge: string;              // random 32 bytes
  requested: "latest" | "range" | "proof_only";
  requesterHanko: string;         // signs accountId + challenge + knownHeight
};

Response:

type PeerStateResponseV1 = {
  type: "peer_state_response";
  version: 1;
  responderEntityId: string;
  accountId: string;
  challenge: string;
  latestHeight: number;
  latestStateHash: string;
  bundle: AccountRecoveryBundleV1;
  responderHanko: string;         // signs response header + bundleHash
};

Rules:

Default cadence:

Layer 3: Recovery Relay

The relay is not a judge and does not custody state. It stores verifiable evidence:

type StateComplaintV1 = {
  type: "state_complaint";
  version: 1;
  complainantEntityId: string;
  accountId: string;
  challenge: string;
  accusedEntityId: string;
  accusedResponse?: PeerStateResponseV1;
  complainantBestBundle?: AccountRecoveryBundleV1;
  reason:
    | "invalid_signature"
    | "invalid_state_hash"
    | "stale_height"
    | "missing_dispute_proof"
    | "refused_latest"
    | "timeout";
  complaintHanko: string;
};

Relay outputs:

The relay should not decide balances. It verifies cryptographic facts only: signatures, hashes, account id, and relative heights.

Layer 4: Watchtower Vault

The Watchtower Vault stores compact recovery bundles. There are two modes.

Blind backup mode

Last-resort disputer mode

Account Recovery Bundle

The recovery bundle is the core object. It must be compact, self-verifying, and sufficient to restore or defend one account.

type AccountRecoveryBundleV1 = {
  version: 1;

  account: {
    accountId: string;
    jurisdictionId: string;
    leftEntityId: string;
    rightEntityId: string;
    ownerEntityId: string;
    counterpartyEntityId: string;
  };

  latestCommitted: {
    height: number;
    frame: AccountFrame;
    frameHash: string;            // equals frame.stateHash
    ownerFrameHanko: string;
    counterpartyFrameHanko: string;
    committedAtRuntimeHeight?: number;
    committedAtJHeight?: number;
  };

  dispute: {
    proofBodyHash: string;
    encodedProofBody?: string;    // needed for active tower or full restore
    proofBodyStruct?: unknown;    // matches runtime disputeProofBodiesByHash
    disputeHash: string;
    nonce: number;
    ownerDisputeHanko: string;
    counterpartyDisputeHanko: string;
    depositoryAddress: string;
    disputeConfig: {
      leftResponseSeconds: number;
      rightResponseSeconds: number;
    };
  };

  stateMaterial: {
    deltas: Array<[number, Delta]>;
    locks?: Array<[string, HtlcLock]>;
    swapOffers?: Array<[string, SwapOffer]>;
    pulls?: Array<[string, PullCommitment]>;
    settlementWorkspace?: SettlementWorkspace;
    lastOutboundFrameAck?: AccountReplica["lastOutboundFrameAck"];
  };

  pending?: {
    pendingFrame?: AccountFrame;
    pendingAccountInput?: AccountInput;
    createdAt: number;
    reason: "awaiting_ack" | "htlc_deadline" | "settlement" | "dispute";
  };

  anchors: {
    storageStateHash?: string;
    storageMerkleRoot?: string;
    lastHistoryRuntimeHeight?: number;
    lastJBlockHash?: string;
  };

  bundleHash: string;
  createdAt: number;
};

Minimum v0 bundle can omit locks, swapOffers, pulls, and settlementWorkspace only if the client restores that account in proof-only safe mode. Full UX restoration requires state material.

Tower Storage Keys

The user wanted keyed overwrite, not rewriting full old values. Use a small per-account ring.

accountRecoveryKey = H("xln/recovery/account-key/v1" || recoveryPubkey || accountId)
slotKey(K, i)     = H("xln/recovery/slot/v1" || accountRecoveryKey || i)
slot              = latestCommitted.height mod K

Default:

Tower upload envelope:

type TowerAppointmentV1 = {
  type: "tower_appointment";
  version: 1;
  towerMode: "blind_backup" | "delayed_last_resort";
  lookupKey: string;              // blinded accountRecoveryKey or slotKey
  slot: number;
  height: number;
  bundleHash: string;
  encryptedBundle: string;        // encrypted to BrainVault recovery key
  lastResortPayload?: {
    triggerHint: string;          // truncated accountId/proofBodyHash/J event hint
    encryptedRemedy: string;      // encrypted to account watchSeed
    actionKind: "counter_dispute_only";
    appointmentSequence: number;  // monotonically increasing per account+tower session
    proofNonce: number;           // exact proof nonce the remedy may submit
    proofBodyHash: string;
    responseMode: "last_resort";
    lastResortWindowSeconds: number;
    safetyMarginSeconds: number;
    maxFeeToken?: string;
    feeBudget?: string;
  };
  ownerEntityId: string;
  ownerHanko: string;             // signs towerMode + lookupKey + slot + height + bundleHash
};

Tower receipt:

type TowerReceiptV1 = {
  type: "tower_receipt";
  version: 1;
  towerId: string;
  lookupKey: string;
  slot: number;
  height: number;
  bundleHash: string;
  storedAt: number;
  expiresAt: number;
  towerSignature: string;
};

The wallet stores receipts locally and optionally gossips receipt hashes to recovery relays.

Encryption Model

Derive a recovery branch from BrainVault output:

recoverySecret = HKDF(masterKey, "xln/recovery/v1")
recoveryPubkey = secp256k1(recoverySecret).pubkey
bundleKey      = ECDH(recoverySecret, towerStoragePubkey) or local AEAD key
backupLookup   = H("xln/recovery/lookup/v1" || runtimeId || recoverySecret)
actionLookup   = H("xln/recovery/action-lookup/v1" || runtimeId || entityId || counterentity || recoverySecret)

Blind backup:

Last-resort disputer:

Delayed last-resort mode:

Normal Operation

On account open:

  1. Create AccountOpenAnchorV1.
  2. Publish anchor to selected relays and towers.
  3. Upload genesis or height-0 recovery bundle.
  4. Store tower receipts in local runtime state.

On every committed frame:

  1. Build AccountRecoveryBundleV1 from AccountReplica.
  2. Verify locally before upload:
    • recompute frame.stateHash;
    • verify owner and counterparty frame hankos;
    • rebuild proofBodyHash;
    • rebuild disputeHash;
    • verify owner and counterparty dispute hankos;
    • ensure height > previousUploadedHeight.
  3. Compress and encrypt.
  4. Upload to slot = height mod K.
  5. Store TowerReceiptV1.
  6. Optionally publish a StateReceiptHashV1 to recovery relays.

On pending frame:

New Computer Recovery Flow

sequenceDiagram
  participant U as User
  participant W as New Wallet
  participant B as BrainVault
  participant R as Recovery Relays
  participant H as Hubs/Peers
  participant T as Watchtowers
  participant J as J-layer

  U->>W: Enter same BrainVault inputs
  W->>B: Derive signer, entity ids, recovery key
  W->>R: Query account anchors and receipt hashes
  W->>T: Query blinded tower slots
  W->>H: Send PeerStateRequestV1 per discovered account
  H-->>W: PeerStateResponseV1 with latest bundle
  T-->>W: Encrypted bundles + tower receipts
  W->>W: Verify frame hashes, hankos, proof bodies, nonces
  W->>J: Check account/dispute anchors and latest J state
  W->>W: Select highest valid safe bundle per account
  W->>W: Materialize AccountReplica
  W->>R: Submit complaint if peer lied/refused
  W->>T: Refresh tower appointments
  W-->>U: Wallet opens at restored state

Detailed steps:

  1. Derive identity
    • BrainVault derives the same mnemonic/private keys.
    • Wallet derives signer addresses, entity ids, and recoveryPubkey.
  2. Discover accounts
    • Query known relays by public or blinded lookup.
    • Query default hubs from onboarding/Hub Matrix.
    • Query watchtowers by deterministic slot keys.
    • Query J-layer account/dispute events for known entity ids.
  3. Collect candidate bundles
    • Peer responses.
    • Tower bundles.
    • Local browser/device DB if any.
    • Optional emergency export file or QR, if user has one.
  4. Verify candidates
    • accountId equals canonical left/right/jurisdiction id.
    • frame.stateHash recomputes.
    • prevFrameHash chain is consistent when previous frames are available.
    • owner and counterparty frame hankos verify.
    • proofBodyHash and disputeHash recompute.
    • owner and counterparty dispute hankos verify.
    • nonce is not lower than an already-settled on-chain nonce.
    • active J-layer dispute state does not contradict the bundle.
  5. Choose state
    • Prefer highest valid committed height.
    • If equal height but different stateHash, enter conflict mode and ask relays/towers/peers for more evidence.
    • If only proof material is available, restore account in proof-only safe mode.
    • If no valid state exists, show account as discovered but unrecovered.
  6. Materialize runtime
    • Rebuild AccountReplica with current frame, deltas, locks, proof metadata, J observations, settlement workspace, and pending frame if valid.
    • Append the Runtime WAL, then materialize history views.
    • Restart PSR cadence and tower uploads.
    • Mark account status as verified, peer-restored, tower-restored, proof-only, or conflict.
  7. Resume
    • Ask every counterparty for a fresh PSR after local materialization.
    • Refresh tower appointments.
    • If an active dispute is detected, submit or delegate the latest valid proof before deadline.

Delayed Last-resort Watchtower Flow

The last-resort tower should be a last-resort responder, not an immediate dispute bot. This reduces the risk that a hub and a tower collude to force a premature on-chain close or choose a stale-but-valid proof while the user is merely offline for a short time.

The tower monitors J-layer events:

For every dispute, define:

disputeStartTimestamp       = on-chain account.disputeStartTimestamp (unix seconds)
disputeTimeout              = on-chain account.disputeTimeout (unix seconds)
lastResortWindowSeconds     = 2 hours by default
safetyMarginSeconds         = 10-20 minutes by default
lastResortStartTimestamp    = disputeTimeout - lastResortWindowSeconds
feeBumpStartTimestamp       = disputeTimeout - safetyMarginSeconds

Block height is observation/finality metadata only. It must never be converted into a protocol deadline: Account and Runtime share exact unix-second clocks, and Runtime casts seconds to milliseconds only at its scheduling boundary.

Default policy:

When a tower sees a dispute:

  1. Match event to triggerHint.
  2. Compare event nonce/proof hash with latest stored appointment.
  3. If the on-chain dispute already uses the latest known proof:
    • do nothing except record observation.
  4. If the on-chain dispute is stale:
    • immediately notify the user, user’s other devices, relays, and optional backup towers;
    • do not submit a transaction before lastResortStartTimestamp;
    • continue checking whether the user or another honest party already countered the dispute;
    • at lastResortStartTimestamp, decrypt the latest remedy and submit the counter-dispute if no better state is on-chain;
    • at feeBumpStartTimestamp, fee-bump or rebroadcast if the rescue tx is not confirmed;
    • publish a tower action receipt.

The tower action must be counter-dispute only:

This still gives the user the first chance to respond. The tower only acts when the alternative is that the hub’s stale dispute may become final.

Collusion Controls

Delayed response is useful, but by itself it is only policy. If a tower receives a pre-signed remedy that is valid immediately, a colluding tower can ignore the policy. Real collusion resistance needs the delay inside the signed payload and contract verification.

Required controls:

  1. On-chain not-before predicate
    • The watchtower rescue path checks block.timestamp + lastResortWindowSeconds >= account.disputeTimeout.
    • The pre-signed tower payload is invalid before that point.
    • This prevents “hub starts dispute, tower instantly finalizes/counters” collusion.
  2. Counter-dispute-only capability
    • The delegated action must require finalNonce > stored account nonce and finalNonce > initialNonce.
    • The tower cannot submit the same-proof finalize path.
    • If the hub started a dispute with the true latest proof, the tower does nothing; the latest state can finalize normally.
  3. Latest last-resort remedy only
    • Historical K recovery bundles are encrypted only to the user.
    • The tower-action payload is a single latest slot, overwritten on every new committed frame.
    • Old action payloads should expire by appointmentSequence, session id, and receipt policy.
  4. Public signed receipts
    • Every last-resort appointment has a signed tower receipt: account, height, proof nonce, proofBodyHash, sequence, and expiry.
    • If a tower submits a lower nonce than a newer receipt it signed, the user can prove misbehavior to relays, Hub Matrix, and any staking/slashing layer.
  5. Independent towers
    • Default consumer policy should use at least two non-hub towers for high-value accounts.
    • A hub may subsidize tower fees, but the hub’s own tower must not be the only last-resort responder.
  6. User-first notification ladder
    • On dispute start: push notification, desktop notification, relay message.
    • During user-exclusive window: tower only watches and simulates.
    • Last-resort window: tower may act.
    • After action: tower publishes receipt and wallet shows exactly what happened.
  7. No blind trust in “latest”
    • No contract can know the latest off-chain state unless the protocol publishes a latest commitment on-chain or adds Lightning-style revocation.
    • Therefore old last-resort remedies are a real risk if a malicious tower retained them.
    • Mitigation for v1 is separation of backup/action payloads, receipts, reputation/slashing, delayed validity, and multiple towers.
    • A future stronger design can add revocation secrets or an on-chain latest-appointment registry, but that increases complexity and/or on-chain writes.

Required contract/runtime assumption:

Current repo note:

UX Contract

The user should see:

The primary happy path is one screen:

Open Wallet -> BrainVault unlock -> Restoring accounts... -> Wallet ready

Advanced details belong in settings, not onboarding.

Market and PMF Impact

This solves the biggest consumer objection to self-custodial credit-channel wallets: “What happens if I lose my phone or laptop?”

High PMF segments:

Compared with adding only payments/swaps/cross-chain swaps, recovery/watchtowers increase trust in every feature. Payments without recovery feel demo-grade. Recovery makes the core wallet believable.

Implementation Plan

Phase A: Peer State Refresh

Files/modules:

Exit tests:

Phase B: Blind Watchtower Vault

Files/modules:

Exit tests:

Current repo status:

Phase C: Delayed Last-resort Watchtower

Files/modules:

Exit tests:

Current repo status:

Phase D: Multi-tower and Incentives

Features:

Code Changes Checklist

Status key: done = implemented and covered in the current repo; open = still active backlog.

  1. done: define recovery protocol types in core/storage/recovery/bundle/types.ts.
  2. done: build bundle creation from AccountReplica in core/storage/recovery/bundle/index.ts.
  3. done: build deterministic verification in core/storage/recovery/verify.ts.
  4. partial: add PSR wire handling to direct core/hub/relay transports.
    • done: authenticated direct runtime websocket accepts recovery_bundle_request and answers with encrypted runtime recovery bundles through the same typed adapter resolver as /rpc.
    • done: relay routes recovery_bundle_request / recovery_bundle_response as live, non-queued messages and fails closed when the target runtime is offline.
    • done: RuntimeWsClient.requestRecoveryBundles() provides a correlated request/response Promise API with timeout and offline-Account input rejection.
    • done: recovery discovery can wrap explicit runtime websocket peer endpoints as RuntimeRecoveryPeerSource entries, rejects runtime mismatches before socket open, and does not infer /ws from stored /rpc imports.
    • open: account-level PeerStateRequestV1 / PeerStateResponseV1 materialization and restore selection remain broader PSR work.
  5. partial: add recovery discovery endpoint:
    • POST /api/recovery/discover
    • POST /api/recovery/state
    • POST /api/recovery/complaint
  6. done: add tower API:
    • PUT /api/tower/appointment
    • POST /api/tower/restore
    • GET /api/tower/receipt/:lookupKey
  7. partial: persist tower receipts and last-uploaded heights.
  8. partial: extend scheduled recovery work; tower upload exists, PSR cadence is still open.
  9. partial: extend wallet initialization after BrainVault unlock:
    • try local DB;
    • if missing or strict restore fails, enter recovery discovery instead of creating empty state silently;
    • only create a fresh env after explicit user confirmation when no recoverable accounts exist.
  10. partial: add UI state for recovery coverage and account recovery status; runtime coverage grid exists, account-level PSR status remains open.
  11. done: add contract support for dispute update/challenge if missing.
  12. done: add contract-enforced delayed tower action:
    • lastResortWindowSeconds;
    • safetyMarginSeconds as tower policy;
    • counter-dispute-only payload;
    • no same-proof finalize capability.
  13. partial: add recovery E2E for wiped local browser state and tower restore; broader BrainVault + hub + PSR recovery soak remains open.

Minimum Viable Product

MVP should include:

Current 0.1.5 status:

MVP should not include yet:

Open Questions

  1. Does the current jurisdictions account contract allow a newer signed proof to defeat an older dispute during the dispute window?
  2. Should account anchors be public by default for consumer simplicity, or blinded by default for privacy?
  3. Is K = 3 enough for all account types, or should high-value accounts default to K = 5?
  4. Should hubs be required to provide PSR as part of the hub protocol, or should it remain a reputation feature?
  5. What exact compression should v0 use: msgpack + gzip via Bun, or a new zstd dependency?
  6. What should the default last-resort window be per jurisdiction: 2h, 4h, or a percentage of the dispute window?
  7. Do we want a future stronger revocation mechanism for old active tower remedies, or is delayed action plus receipts/multi-tower enough for v1?

Source References