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
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:
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.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 separates three concerns that XLN should also keep separate:
Sources are listed at the end.
XLN already has most of the raw material:
core/types/account.ts.abiProofBody, currentDisputeProofHanko, counterpartyDisputeProofHanko, disputeProofNoncesByHash, and disputeProofBodiesByHash.buildAccountProofBody() and createDisputeProofHash() in core/protocol/dispute/proof-builder.ts.RuntimeHistoryRecord materialized by
core/storage/history/history-view.ts from the authoritative Runtime WAL.stateHash, documented in docs/merkle.md.entity-crontab.ts already handles pending-frame resend, stale pending-frame detection, HTLC timeouts, rollback suggestions, and rebalance automation.Implemented in the current repo:
/api/tower/*;watchSeed is revealed by DisputeStarted;/api/watchtower/* removed;watchtowerCounterDispute(...) path that rejects early tower action,
wrong tower action, missing newer proof, and same-proof delegated finalize;Still missing or incomplete:
K = 3 per account, with overwriting slots.clearDB or local reset become an accidental funds-loss path.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.
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.
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:
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.
The Watchtower Vault stores compact recovery bundles. There are two modes.
Blind backup mode
Last-resort disputer mode
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.
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:
K = 3 for consumer accounts;K = 5 for merchant/hub/operator accounts;K = 2 minimum for free relay/tower plans;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.
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:
lastResortPayload.encryptedRemedy is unreadable until a J-layer
DisputeStarted event reveals the account watchSeed;K historical backup slots stay encrypted only to the
user, while the action payload is under its own blinded lookup key.Delayed last-resort mode:
On account open:
AccountOpenAnchorV1.On every committed frame:
AccountRecoveryBundleV1 from AccountReplica.frame.stateHash;proofBodyHash;disputeHash;height > previousUploadedHeight.slot = height mod K.TowerReceiptV1.StateReceiptHashV1 to recovery relays.On pending frame:
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:
recoveryPubkey.accountId equals canonical left/right/jurisdiction id.frame.stateHash recomputes.prevFrameHash chain is consistent when previous frames are available.proofBodyHash and disputeHash recompute.stateHash, enter conflict mode and ask relays/towers/peers for more evidence.AccountReplica with current frame, deltas, locks, proof metadata, J observations, settlement workspace, and pending frame if valid.verified, peer-restored, tower-restored, proof-only, or conflict.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:
AccountDisputeStarted(accountId, nonce, proofBodyHash, byEntity);AccountDisputeUpdated(accountId, nonce, proofBodyHash);AccountFinalized(accountId, nonce);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:
min(25% of dispute window, configured max) but never less than the chain-specific finality/fee-bump margin.When a tower sees a dispute:
triggerHint.lastResortStartTimestamp;lastResortStartTimestamp, decrypt the latest remedy and submit the counter-dispute if no better state is on-chain;feeBumpStartTimestamp, fee-bump or rebroadcast if the rescue tx is not confirmed;The tower action must be counter-dispute only:
finalNonce > activeDispute.initialNonce;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.
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:
block.timestamp + lastResortWindowSeconds >= account.disputeTimeout.finalNonce > stored account nonce and finalNonce > initialNonce.K recovery bundles are encrypted only to the user.appointmentSequence, session id, and receipt policy.Required contract/runtime assumption:
lastResortWindowSeconds on-chain.jurisdictions contracts need a guarded watchtowerCounterDispute or equivalent before last-resort towers can be considered collusion-resistant.Current repo note:
Depository.sol has a tower-specific watchtowerCounterDispute(...) path.The user should see:
Verified: local, peer, and/or tower agree on latest height.Peer restored: restored from hub/counterparty, tower not available.Tower restored: restored from tower, peer unavailable.Proof-only: funds can be defended, rich UI state is incomplete.Conflict: signed states disagree; account is frozen until resolved.The primary happy path is one screen:
Open Wallet -> BrainVault unlock -> Restoring accounts... -> Wallet ready
Advanced details belong in settings, not onboarding.
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.
Files/modules:
core/storage/recovery/bundle/types.ts;core/storage/recovery/bundle/index.ts;core/storage/recovery/verify.ts;core/storage/recovery/peer-sync.ts;core/api/server/index.ts, core/orchestrator/hub-node.ts, and relay server modules;entity-crontab.ts to schedule PSR pings.Exit tests:
Files/modules:
core/storage/recovery/tower-client.ts;core/storage/recovery/tower-server.ts or a standalone tower service;core/storage/recovery/encryption.ts;Exit tests:
K = 3 bundles and overwrite slots correctly;Current repo status:
core/watchtower/* service exists;Files/modules:
core/jurisdiction/adapter/watcher/index.ts event fanout for account/dispute events;core/storage/recovery/tower-action.ts;watchtowerCounterDispute, that rejects early tower action before the last-resort window;jurisdictions contracts if a newer proof cannot challenge an older dispute.Exit tests:
lastResortStartTimestamp;Current repo status:
watchtowerCounterDispute(...) exists in Depository.sol;core/watchtower/action.ts;/api/watchtower/* access;watchSeed, decrypt only
after DisputeStarted, and plaintext last-resort remedies are rejected by
tower HTTP and store insertion;Features:
Status key: done = implemented and covered in the current repo; open = still active backlog.
core/storage/recovery/bundle/types.ts.AccountReplica in core/storage/recovery/bundle/index.ts.core/storage/recovery/verify.ts.recovery_bundle_request and answers with encrypted runtime recovery
bundles through the same typed adapter resolver as /rpc.recovery_bundle_request /
recovery_bundle_response as live, non-queued messages and fails closed
when the target runtime is offline.RuntimeWsClient.requestRecoveryBundles() provides a correlated
request/response Promise API with timeout and offline-Account input rejection.RuntimeRecoveryPeerSource entries, rejects runtime
mismatches before socket open, and does not infer /ws from stored /rpc
imports.PeerStateRequestV1 / PeerStateResponseV1
materialization and restore selection remain broader PSR work.POST /api/recovery/discoverPOST /api/recovery/statePOST /api/recovery/complaintPUT /api/tower/appointmentPOST /api/tower/restoreGET /api/tower/receipt/:lookupKeylastResortWindowSeconds;safetyMarginSeconds as tower policy;MVP should include:
PeerStateRequestV1.AccountRecoveryBundleV1.Current 0.1.5 status:
MVP should not include yet:
jurisdictions account contract allow a newer signed proof to defeat an older dispute during the dispute window?K = 3 enough for all account types, or should high-value accounts default to K = 5?