Testnet Mode — switch back to Production in the menuheader when you're done.
VarnirRecovery extends Event
/** Voting round: dispatch(false) - validate only; a thrown string is the refusal. */
public vote(): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
try {
await this.dispatch(false);
resolve(true);
} catch (e) {
reject(typeof e === "string" ? e : (e as Error).message);
}
});
}/** Commit round: dispatch(true) - validate again, then write. */
public commit(): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
try {
await this.dispatch(true);
resolve(true);
} catch (e) {
reject(typeof e === "string" ? e : (e as Error).message);
}
});
} private refuseRecoveredIdentity(state: any, outgoing: boolean): string | null {
if (state && state.recoveredTo) {
// A dead identity may still RECEIVE: the credit lands and is swept to recoveredTo.
return outgoing
? `Identity recovered - new identity is ${state.recoveredTo}; your keys are still valid`
: null;
}
if (outgoing && state && state.recovery && state.recovery.frozen) {
return "Identity frozen - a social recovery is in its 48h waiting period";
}
return null;
} private refuseRecoveredStreams(incomingOnly: string[] | "all-outputs"): string | null {
// Never getActivityStreams(ref): an unloaded ref CREATES a stream. The
// no-argument form returns only the streams this transaction loaded.
const ctx: any = this as any;
const loaded: any = ctx.getActivityStreams() || {};
const outputs: any = (ctx.transactions && ctx.transactions.$o) || {};
const toId = (label: string, ref: any): string | null => {
const raw = ref && typeof ref === "object" ? ref.$stream : typeof ref === "string" ? ref : /^[0-9a-f]{64}$/i.test(label) ? label : null;
return typeof raw === "string" ? raw.split(":")[0].slice(-64) : null;
};
const outputIds: string[] = [];
const incomingIds: string[] = [];
for (const label of Object.keys(outputs)) {
const id = toId(label, outputs[label]);
if (!id) continue;
outputIds.push(id);
if (incomingOnly === "all-outputs" || incomingOnly.indexOf(label) !== -1) incomingIds.push(id);
}
for (const id of Object.keys(loaded)) {
const activity = loaded[id];
if (!activity || typeof activity.getState !== "function") continue;
const signed = typeof activity.hasSignature === "function" && activity.hasSignature();
const incoming = !signed && outputIds.indexOf(id) !== -1 && incomingIds.indexOf(id) !== -1;
const refusal = this.refuseRecoveredIdentity(activity.getState(), !incoming);
if (refusal) return refusal;
}
return null;
}/** Runs the entry named by `$entry`; an unknown entry is refused. */
private async dispatch(apply: boolean): Promise<void> {
switch (this.transactions.$entry) {
case "configure": return this.runConfigure(apply);
case "setup": return this.runSetup(apply);
case "update": return this.runUpdate(apply);
case "disable": return this.runDisable(apply);
case "start": return this.runStart(apply);
case "claim": return this.runClaim(apply);
case "sent": return this.runSent(apply);
case "notified": return this.runNotified(apply);
case "resend": return this.runResend(apply);
case "submit": return this.runSubmit(apply);
case "cancel": return this.runCancel(apply);
case "expire": return this.runExpire(apply);
case "finalize": return this.runFinalize(apply);
case "sweep": return this.runSweep(apply);
default:
throw `Unknown entry ${this.transactions.$entry}`;
}
}/** The contract's only clock: this.cDate in milliseconds. */
private now(): number {
return new Date(this.cDate).getTime();
}/** A millisecond instant as ISO-8601. */
private iso(ms: number): string {
return new Date(ms).toISOString();
}/** sha256 hex of `value` (ActiveCrypto). */
private sha256(value: string): string {
return this.ActiveCrypto.Hash.getHash(value, "sha256");
}/**
* The engine's getContractData() returns the storage wrapper {_id, data},
* not the data itself (@activeledger/activecontracts stream.js) - matches
* Varnir.Deposit.ts's getContractDataHelper(). Named …Helper, not
* contractData, because the base Event class already declares a private
* `contractData` field - reusing the name breaks TS2415 (incompatible
* private-property declarations across the inheritance chain).
*/ private getContractDataHelper(): any {
const wrapper: any = this.getContractData();
return (wrapper && wrapper.data) || {};
}/** A stream the transaction names under $i/$o. Safe: it is loaded, so no lookup creates one. */
private named(where: "$i" | "$o", label: string): any {
const ref = (this.transactions as any)[where] && (this.transactions as any)[where][label];
if (!ref) throw `Recovery - missing ${where}.${label}`;
return this.getActivityStreams(ref);
}/** Refuses unless `activity` was signed by one of its own stake-100 authorities. */
private requireStake100(activity: any): void {
const signed = (this as any).sigs && (this as any).sigs[activity.getId()];
const hashes = signed ? Object.keys(signed) : [];
const ok =
hashes.length > 0 &&
(activity.getAuthorities() || []).some(
(a: any) => a.stake === 100 && hashes.indexOf(a.hash) !== -1
);
if (!ok) throw "Recovery - requires the identity's stake-100 owner key";
}/** Refuses unless `activity` signed and its volatile carries `admin` or `minigate`. */
private async requireAdmin(activity: any): Promise<void> {
if (!activity.hasSignature()) throw "Recovery - admin must sign";
const volatile: any = await activity.getVolatile();
// Same trust anchor as Varnir.UserMod: an operator stream carries `admin`
// or `minigate` in its volatile, and only an operator can write there - no
// contract exposes a write to it. Varnir's gateways carry `minigate`, and
// they are exactly what `configure` lists as origins; a gateway can
// already claim any guardian's code through the fallback path, so naming
// the origin list grants it nothing it did not already have.
if (!volatile || (!volatile.admin && !volatile.minigate)) {
throw "Recovery - signer is not an admin or minigate stream";
}
}/** * Validates a guardian set: 1 to MAX_GUARDIANS guardians, each with an id * and a valid email, no duplicate ids or emails (case-insensitive), a * whole-number threshold from 1 to the guardian count, and an optional * valid `ownerEmail`. Returns the cleaned config. */
private validateConfig(input: any): { guardians: any[]; threshold: number; ownerEmail?: string }/** * Applies a due pending change (spec §3.2) unless a recovery is active, in * which case the pending change stays frozen. Returns the effective state and * volatile recovery blocks; writes nothing itself. */
private effective(state: any, volatile: any): { recovery: any; vrecovery: any; changed: boolean }/** * `configure`: an admin or minigate stream (`$i.admin`, requireAdmin) * sets `origins` - the gateway identities guardian codes are assigned to, * round-robin - in contract data. Must be a non-empty list of distinct * stream ids. */
private async runConfigure(apply: boolean): Promise<void> {
const admin = this.named("$i", "admin");
await this.requireAdmin(admin);
const origins = (this.transactions.$i as any).admin.origins;
if (
!Array.isArray(origins) ||
origins.length === 0 ||
origins.some((o: any) => typeof o !== "string" || !ID_PATTERN.test(o)) ||
new Set(origins).size !== origins.length
) {
throw "Recovery - origins must be a non-empty list of distinct stream ids";
}
if (!apply) return;
this.setContractData({ ...this.getContractDataHelper(), origins: origins.slice() });
}/** * `$i.owner`, signed by its stake-100 key and not recovered or frozen, * with its recovery config as it stands now (any due pending change * applied, see effective()). */
private async loadOwnerConfig(): Promise<{
owner: any;
state: any;
recovery: any;
vrecovery: any;
eff: { recovery: any; vrecovery: any; changed: boolean };
}/** * `setup` (owner key): turns recovery on with a guardian set and * threshold, taking effect at once. Guardian emails go to the identity's * volatile; the state keeps only the threshold, count and version. Refused * once set up. Emits `recovery-configured`. */
private async runSetup(apply: boolean): Promise<void> {
const { owner, recovery, eff } = await this.loadOwnerConfig();
if (apply) this.persistEffective(owner, eff);
if (recovery && recovery.enabled) throw "Recovery setup - already set up; use update";
const config = this.validateConfig((this.transactions.$i as any).owner);
if (!apply) return;
const next: any = {
enabled: true,
threshold: config.threshold,
guardianCount: config.guardians.length,
version: ((recovery && recovery.version) || 0) + 1,
};
if (recovery && recovery.lastClosedAt) next.lastClosedAt = recovery.lastClosedAt;
owner.setState({ recovery: next });
const vnext: any = { scheme: "plain", guardians: config.guardians };
if (config.ownerEmail !== undefined) vnext.ownerEmail = config.ownerEmail;
owner.setVolatile({ recovery: vnext });
this.event.emit("recovery-configured", { identity: owner.getId(), version: next.version });
}/** * `update` (owner key): stages a new guardian set and threshold as * `pending`, effective after CONFIG_DELAY_MS (48 h); with `revert: true` * drops a staged change instead. Refused when not set up or while a * recovery is active. Emits `recovery-config-change`. */
private async runUpdate(apply: boolean): Promise<void> {
const { owner, recovery, vrecovery, eff } = await this.loadOwnerConfig();
if (apply) this.persistEffective(owner, eff);
if (!recovery || !recovery.enabled) throw "Recovery update - recovery is not set up";
if (recovery.active) throw "Recovery update - refused while a recovery is active";
const input = (this.transactions.$i as any).owner;
if (input.revert) {
if (!recovery.pending) throw "Recovery update - nothing pending to revert";
if (!apply) return;
const nextState = { ...recovery };
delete nextState.pending;
const nextVol = { ...(vrecovery || {}) };
delete nextVol.pending;
owner.setState({ recovery: nextState });
owner.setVolatile({ recovery: nextVol });
this.event.emit("recovery-config-change", { identity: owner.getId(), kind: "revert" });
return;
}
const config = this.validateConfig(input);
if (!apply) return;
const effectiveAt = this.iso(this.now() + CONFIG_DELAY_MS);
owner.setState({
recovery: { ...recovery, pending: { threshold: config.threshold, guardianCount: config.guardians.length, effectiveAt } },
});
const vpending: any = { guardians: config.guardians };
if (config.ownerEmail !== undefined) vpending.ownerEmail = config.ownerEmail;
owner.setVolatile({ recovery: { ...(vrecovery || {}), pending: vpending } });
this.event.emit("recovery-config-change", { identity: owner.getId(), kind: "update", effectiveAt });
}/** * `disable` (owner key): stages turning recovery off, effective after * CONFIG_DELAY_MS. Refused when not set up or while a recovery is active. * Emits `recovery-config-change`. */
private async runDisable(apply: boolean): Promise<void> {
const { owner, recovery, eff } = await this.loadOwnerConfig();
if (apply) this.persistEffective(owner, eff);
if (!recovery || !recovery.enabled) throw "Recovery disable - recovery is not set up";
if (recovery.active) throw "Recovery disable - refused while a recovery is active";
if (!apply) return;
const effectiveAt = this.iso(this.now() + CONFIG_DELAY_MS);
owner.setState({ recovery: { ...recovery, pending: { disable: true, effectiveAt } } });
this.event.emit("recovery-config-change", { identity: owner.getId(), kind: "disable", effectiveAt });
}/** Refuses a closed record, and an awaiting record past its 7-day session. */
private requireOpen(record: any): void {
if (OPEN_STATUSES.indexOf(record.status) === -1) throw "Recovery - record is not open";
if (record.status === "awaiting-codes" && this.now() >= new Date(record.expiresAt).getTime()) {
throw "Recovery - session expired; submit an expire transaction";
}
}/** `i` when it is a valid index into the record's guardian assignments; refuses otherwise. */
private guardianIndex(record: any, i: any): number {
if (!Number.isInteger(i) || i < 0 || i >= record.assignments.length) throw "Recovery - bad guardian index";
return i;
}/** Structural shape check for a $o.record before trusting its fields. */
private looksLikeRecord(record: any): boolean {
return !!record && typeof record.target === "string" && Array.isArray(record.assignments) && ALL_STATUSES.indexOf(record.status) !== -1;
}/** Whether a real document exists for `id` (a notFound answer or a read error is "no"). */
private async streamExists(id: string): Promise<boolean> {
// A missing stream does NOT reject on the live engine: the store answers
// {"notFound":true,"code":"LEVEL_NOT_FOUND"} and getAnyStreamReadOnly
// resolves with that object. Truthiness alone therefore reported every
// fresh key as "already has an identity" and refused every start. A
// stream exists only when a real document comes back.
try {
const doc: any = await this.getAnyStreamReadOnly(id);
return !!doc && !doc.notFound && typeof doc._id === "string";
} catch (e) {
return false;
}
}/** Proves the $selfsign signer is a minigate authority (the Varnir.CryptoTransfer presigned gate). Returns its identity. */
private async requireMinigate(): Promise<string> {
const ref = (this.transactions as any).$r && (this.transactions as any).$r.minigate;
if (!ref) throw "Recovery - missing minigate reference";
const volatile: any = await this.getAnyStreamReadOnly(`${ref}:volatile`).catch(() => null);
if (!volatile || !volatile.minigate) throw "Recovery - reference is not a minigate";
const key = (this.transactions as any).$i && (this.transactions as any).$i.admin && (this.transactions as any).$i.admin.publicKey;
const meta: any = await this.getAnyStreamReadOnly(`${ref}:stream`).catch(() => null);
const ok = !!key && meta && Array.isArray(meta.authorities) && meta.authorities.some((a: any) => a.public === key);
if (!ok) throw "Recovery - signing key is not a minigate authority";
return ref;
}/**
* `start`: opens a recovery for `$o.target` under a NEW key
* (`$i.otk = {publicKey, type, target, carryKeys?}`); the transaction is
* signed by that new key, not by the target. Refuses a recovered or
* frozen target, one without recovery set up, one with a recovery already
* active, one inside the 24 h cooldown after the last closed, no
* configured origins, `carryKeys` naming anything but the target's
* non-owner authorities, and a new key that already has an identity.
* Writes a `recovery` record stream owned by the new key (status
* `awaiting-codes`, a 7-day session, one assignment per guardian), marks
* the target `recovery.active`, emits `recovery-started`.
*/ private async runStart(apply: boolean): Promise<void> {
const input: any = (this.transactions.$i as any).otk;
if (!input || typeof input.publicKey !== "string" || typeof input.type !== "string") {
throw "Recovery start - publicKey and type required";
}
const target = this.named("$o", "target");
if (target.getId() !== input.target) throw "Recovery start - $o.target does not match the requested target";
const state = target.getState();
const tombstone = this.refuseRecoveredIdentity(state, true);
if (tombstone) throw tombstone;
const eff = this.effective(state, await target.getVolatile());
const recovery = eff.recovery;
if (!recovery || !recovery.enabled) throw "Recovery start - recovery is not set up for this identity";
if (recovery.active) throw "Recovery start - a recovery is already active on this identity";
if (recovery.lastClosedAt && this.now() - new Date(recovery.lastClosedAt).getTime() < COOLDOWN_MS) {
throw "Recovery start - cooldown: wait 24h after the last recovery closed";
}
const data: any = this.getContractDataHelper();
const origins: string[] = Array.isArray(data.origins) ? data.origins : [];
if (!origins.length) throw "Recovery start - recovery is not configured (no origins)";
const carryKeys = input.carryKeys === undefined ? [] : input.carryKeys;
const authorities = target.getAuthorities() || [];
if (
!Array.isArray(carryKeys) ||
carryKeys.some(
(h: any) => !authorities.some((a: any) => a.hash === h && a.stake !== 100)
)
) {
throw "Recovery start - carryKeys may only name non-owner authorities of the target";
}
// >>> owner-gate
// A carried key keeps its stake and label on the new identity. Only the stakes Varnir.Keys gives a non-owner key
// (0, or 80 for a co-sign key) may be carried; anything else (a legacy stake-9000 key) is refused here and left
// behind at finalize. Two carried stake-80 keys still add up past 100, which is harmless: every owner-only gate
// requires exactly one stake-100 key (docs/tenancy/legacy-read-key-audit.md).
if (carryKeys.some((h: any) => authorities.some((a: any) => a.hash === h && a.stake !== 0 && a.stake !== 80))) {
throw "Recovery start - carryKeys may only name stake-0 or stake-80 keys";
}
// <<< owner-gate
const newIdentity = this.sha256(input.publicKey + "identity");
if (await this.streamExists(newIdentity)) {
throw "Recovery start - that key already has an identity; generate a fresh key";
}
if (!apply) return;
const record = this.newActivityStream("recovery", input.publicKey);
record.setAuthorities([{ public: input.publicKey, type: input.type, stake: 100 }]);
const startedAt = this.now();
record.setState({
target: target.getId(),
newKey: { public: input.publicKey, type: input.type },
newIdentity,
carryKeys: carryKeys.slice(),
status: "awaiting-codes",
startedAt: this.iso(startedAt),
expiresAt: this.iso(startedAt + SESSION_MS),
threshold: recovery.threshold,
guardianCount: recovery.guardianCount,
configVersion: recovery.version,
assignments: Array.from({ length: recovery.guardianCount }, (_v, i) => ({
origin: origins[i % origins.length],
resends: 0,
retiredHashes: [],
})),
accepted: [],
failedAttempts: 0,
overridden: false,
ownerNotified: {},
});
target.setState({ recovery: { ...recovery, active: record.getId() } });
if (eff.changed) target.setVolatile({ recovery: eff.vrecovery });
this.event.emit("recovery-started", {
record: record.getId(),
target: target.getId(),
newIdentity,
guardianCount: recovery.guardianCount,
startedAt: this.iso(startedAt),
});
}/** * `claim` (gateway, requireMinigate): claims guardian `i`'s code on the * open record `$o.record` and records its sha256 `codeHash`. Refused for * an accepted guardian, a code already sent, a live claim (under * CLAIM_TIMEOUT_MS), or a gateway other than the assigned origin before * CLAIM_TIMEOUT_MS has passed since the assignment opened (after that any * gateway may claim, marked `fallback`). */
private async runClaim(apply: boolean): Promise<void> {
const gateway = await this.requireMinigate();
const input: any = (this.transactions.$i as any).admin;
const recordStream = this.named("$o", "record");
const record = recordStream.getState();
this.requireOpen(record);
const i = this.guardianIndex(record, input.i);
if (typeof input.codeHash !== "string" || !ID_PATTERN.test(input.codeHash)) throw "Recovery claim - codeHash must be a sha256 hex digest";
if (record.accepted.indexOf(i) !== -1) throw "Recovery claim - guardian already accepted";
const a = { ...record.assignments[i] };
if (a.claimedBy && a.sentAt) throw "Recovery claim - code already sent; use resend";
if (a.claimedBy && this.now() - new Date(a.claimedAt).getTime() < CLAIM_TIMEOUT_MS) {
throw "Recovery claim - already claimed";
}
const openedAt = new Date(a.releasedAt || record.startedAt).getTime();
if (gateway !== a.origin && this.now() - openedAt < CLAIM_TIMEOUT_MS) {
throw "Recovery claim - not this gateway's assignment yet";
}
if (!apply) return;
if (a.codeHash) a.retiredHashes = [...(a.retiredHashes || []), a.codeHash];
a.claimedBy = gateway;
a.claimedAt = this.iso(this.now());
a.codeHash = input.codeHash;
a.fallback = gateway !== a.origin;
const assignments = record.assignments.slice();
assignments[i] = a;
recordStream.setState({ assignments });
}/** * `sent` (gateway): the gateway that claimed guardian `i` records the * email's `resendId`, once. Emits `code-sent`. */
private async runSent(apply: boolean): Promise<void> {
const gateway = await this.requireMinigate();
const input: any = (this.transactions.$i as any).admin;
const recordStream = this.named("$o", "record");
const record = recordStream.getState();
this.requireOpen(record);
const i = this.guardianIndex(record, input.i);
const a = { ...record.assignments[i] };
if (a.claimedBy !== gateway) throw "Recovery sent - only the claimer may record the send";
if (a.sentAt) throw "Recovery sent - already sent";
if (typeof input.resendId !== "string" || !input.resendId || input.resendId.length > 200) throw "Recovery sent - resendId required";
if (!apply) return;
a.sentAt = this.iso(this.now());
a.resendId = input.resendId;
const assignments = record.assignments.slice();
assignments[i] = a;
recordStream.setState({ assignments });
this.event.emit("code-sent", { record: recordStream.getId(), i });
}/** * Owner alerts get the same claim-then-send lock as guardian codes (spec * §5.4): a gateway that claims the "notify the owner" job and then fails to * send must not strand that alert forever. `phase: "claim"` records who is * attempting the send (timing out after CLAIM_TIMEOUT_MS, same as a * guardian code claim); `phase: "sent"` - only the claimer, once - commits * it. Both phases require an open record; thresholdMet skips the awaiting- * codes expiry refusal specifically (the alert may still be due after the * session's own expiry window closes). */
private async runNotified(apply: boolean): Promise<void> {
const gateway = await this.requireMinigate();
const input: any = (this.transactions.$i as any).admin;
const which = input.which;
const phase = input.phase;
if (which !== "started" && which !== "thresholdMet") throw "Recovery notified - which must be started or thresholdMet";
if (phase !== "claim" && phase !== "sent") throw "Recovery notified - phase must be claim or sent";
const recordStream = this.named("$o", "record");
const record = recordStream.getState();
if (!this.looksLikeRecord(record)) throw "Recovery notified - $o.record is not a recovery record";
if (which === "thresholdMet") {
if (OPEN_STATUSES.indexOf(record.status) === -1) throw "Recovery - record is not open";
} else {
this.requireOpen(record);
}
const notified: any = { ...((record.ownerNotified && record.ownerNotified[which]) || {}) };
if (phase === "claim") {
if (notified.sentAt) throw "Recovery notified - already sent";
if (notified.claimedBy && this.now() - new Date(notified.claimedAt).getTime() < CLAIM_TIMEOUT_MS) {
throw "Recovery notified - already claimed";
}
if (which === "thresholdMet" && !record.thresholdMetAt) throw "Recovery notified - threshold not met yet";
if (!apply) return;
const next = { claimedBy: gateway, claimedAt: this.iso(this.now()) };
recordStream.setState({ ownerNotified: { ...(record.ownerNotified || {}), [which]: next } });
} else {
if (notified.claimedBy !== gateway) throw "Recovery notified - only the claimer may record the send";
if (notified.sentAt) throw "Recovery notified - already sent";
if (typeof input.resendId !== "string" || !input.resendId || input.resendId.length > 200) throw "Recovery notified - resendId required";
if (!apply) return;
const next = { ...notified, sentAt: this.iso(this.now()), resendId: input.resendId };
recordStream.setState({ ownerNotified: { ...(record.ownerNotified || {}), [which]: next } });
}
}/** * `resend` (the recovery's new key, `$i.record`): re-opens guardian `i`'s * assignment for a fresh code - the old hash is retired - up to * MAX_RESENDS times, once a code was sent and while the guardian has not * been accepted. Emits `recovery-resend`. */
private async runResend(apply: boolean): Promise<void> {
const recordStream = this.named("$i", "record");
if (!recordStream.hasSignature()) throw "Recovery resend - must be signed by the recovery's new key";
const record = recordStream.getState();
this.requireOpen(record);
const i = this.guardianIndex(record, (this.transactions.$i as any).record.i);
if (record.accepted.indexOf(i) !== -1) throw "Recovery resend - guardian already accepted";
const a = record.assignments[i];
if (!a.sentAt) throw "Recovery resend - nothing to resend yet";
if ((a.resends || 0) >= MAX_RESENDS) throw "Recovery resend - resend limit reached";
if (!apply) return;
const assignments = record.assignments.slice();
assignments[i] = {
origin: a.origin,
resends: (a.resends || 0) + 1,
retiredHashes: [...(a.retiredHashes || []), a.codeHash],
releasedAt: this.iso(this.now()),
};
recordStream.setState({ assignments });
this.event.emit("recovery-resend", { record: recordStream.getId(), i });
}/** The record, whether the new key signed it ($i.record) or a minigate named it ($o.record). */
private async recordForKeyOrMinigate(): Promise<any> {
const inputs: any = this.transactions.$i || {};
if (inputs.record) {
const signedRecord = this.named("$i", "record");
if (!signedRecord.hasSignature()) throw "Recovery - must be signed by the recovery's new key";
return signedRecord;
}
await this.requireMinigate();
return this.named("$o", "record");
}/** Refuses unless the record names `target`. */
private requireTargetOf(record: any, target: any, message = "Recovery - $o.target is not this recovery's target"): void {
if (record.target !== target.getId()) throw message;
}/** * A record naming the right target is not enough: the target's own * `recovery.active` marker is the binding (finalize already treats it this * way, §4.4). Without this, a record-shaped stream naming a real target * could still freeze it via submit, or a stale/foreign record could be * cancelled to clear a genuine overridden recovery's active/frozen marker. */
private requireActiveRecovery(recordStream: any, target: any): void {
const active = ((target.getState().recovery) || {}).active;
if (active !== recordStream.getId()) throw "Recovery - not this identity's active recovery";
}/** * Closes the record with `reason`, clears the target's `active` and * `frozen` markers, stamps `lastClosedAt` (which starts the cooldown) and * emits `recovery-closed`. */
private closeRecord(recordStream: any, record: any, target: any, reason: "cancelled" | "expired" | "locked"): void {
const at = this.iso(this.now());
recordStream.setState({ status: reason, closedAt: at, closedReason: reason });
const recovery = { ...(target.getState().recovery || {}) };
delete recovery.active;
delete recovery.frozen;
recovery.lastClosedAt = at;
target.setState({ recovery });
this.event.emit("recovery-closed", { record: recordStream.getId(), target: target.getId(), reason });
}/** A code as typed: upper-cased, spaces and hyphens removed ("" for a non-string). */ private normalise(code: any): string {
return typeof code === "string" ? code.toUpperCase().replace(/[\s-]/g, "") : "";
}/** * `submit` (the new key, `$i.record`; target on `$o.target`): checks 1 to * MAX_GUARDIANS codes against the assignments' hashes * (`sha256(<record>:<i>:<code>)`). Each match accepts that guardian; each * miss counts a failed attempt, and MAX_FAILED_ATTEMPTS closes the record * as `locked`. Reaching the threshold moves the record to `waiting` with * `finalAt` = now + 48 h, freezes the target and emits * `recovery-threshold-met`; every guardian accepting sets `overridden` * (the owner can then no longer cancel). */
private async runSubmit(apply: boolean): Promise<void> {
const recordStream = this.named("$i", "record");
if (!recordStream.hasSignature()) throw "Recovery submit - must be signed by the recovery's new key";
const target = this.named("$o", "target");
const record = recordStream.getState();
this.requireTargetOf(record, target);
this.requireActiveRecovery(recordStream, target);
this.requireOpen(record);
const codes = (this.transactions.$i as any).record.codes;
if (!Array.isArray(codes) || codes.length < 1 || codes.length > MAX_GUARDIANS) {
throw `Recovery submit - between 1 and ${MAX_GUARDIANS} codes per submission`;
}
if (!apply) return;
const accepted: number[] = record.accepted.slice();
let failed = record.failedAttempts || 0;
for (const raw of codes) {
const code = this.normalise(raw);
let matched = false;
if (CODE_PATTERN.test(code)) {
for (let i = 0; i < record.assignments.length; i++) {
const a = record.assignments[i];
if (accepted.indexOf(i) !== -1 || !a.codeHash) continue;
if (a.codeHash === this.sha256(`${recordStream.getId()}:${i}:${code}`)) {
accepted.push(i);
matched = true;
break;
}
}
}
if (!matched) failed++;
}
if (failed >= MAX_FAILED_ATTEMPTS) {
recordStream.setState({ accepted, failedAttempts: failed });
this.closeRecord(recordStream, record, target, "locked");
return;
}
const update: any = { accepted, failedAttempts: failed };
if (record.status === "awaiting-codes" && accepted.length >= record.threshold) {
const now = this.now();
update.status = "waiting";
update.thresholdMetAt = this.iso(now);
update.finalAt = this.iso(now + WAIT_MS);
target.setState({ recovery: { ...(target.getState().recovery || {}), frozen: true } });
this.event.emit("recovery-threshold-met", {
record: recordStream.getId(),
target: target.getId(),
finalAt: update.finalAt,
});
}
if (accepted.length >= record.guardianCount) update.overridden = true;
recordStream.setState(update);
}/** * `cancel` (the target's own stake-100 key on `$i.owner`): closes its * active, open recovery `$o.record` as `cancelled` - refused once * `overridden`. */
private async runCancel(apply: boolean): Promise<void> {
const owner = this.named("$i", "owner");
this.requireStake100(owner);
const recordStream = this.named("$o", "record");
const record = recordStream.getState();
this.requireTargetOf(record, owner, "Recovery cancel - $i.owner is not this recovery's target");
this.requireActiveRecovery(recordStream, owner);
if (OPEN_STATUSES.indexOf(record.status) === -1) throw "Recovery cancel - record is not open";
if (record.overridden) throw "Recovery cancel - refused: every guardian confirmed this recovery (all-guardian override)";
if (!apply) return;
this.closeRecord(recordStream, record, owner, "cancelled");
}/** * `expire` (the new key or a gateway): closes an `awaiting-codes` record * whose 7-day session has passed as `expired`. */
private async runExpire(apply: boolean): Promise<void> {
const recordStream = await this.recordForKeyOrMinigate();
const target = this.named("$o", "target");
const record = recordStream.getState();
this.requireTargetOf(record, target);
this.requireActiveRecovery(recordStream, target);
if (record.status !== "awaiting-codes" || this.now() < new Date(record.expiresAt).getTime()) {
throw "Recovery expire - not expired";
}
if (!apply) return;
this.closeRecord(recordStream, record, target, "expired");
}/** * `finalize` (the new key or a gateway), once a `waiting` record reaches * `finalAt`: migrates the account. Creates the new identity for the new * key (stake 100, plus the carried non-owner keys), copying the old state * except recovery and treasury fields - restrictions and agent usage only * for carried keys, treasury only when its key is carried - with * `recoveredFrom`. Varnir.Markets positions (`mkt`) MOVE to the new identity * like `layer2`; its order markers (`mko`, for orders the old identity signed) * and its eligibility records (`el`, attested for the old identity) are not * copied. The old identity is tombstoned (`layer2`, Swap's * `orderHold` / `orders` / `pendingOrderApprovals` and Markets' `mkt` / `el` * emptied; Markets' `mko` markers are KEPT on the tombstone, a second defence * against replaying an order the old identity signed, * `recoveredTo`, `recoveredAt`, `recoveryRecord`; volatile recovery * cleared) and the record completed. Refused when the target is already * recovered, the record is not its active one, the recorded new identity * id does not match the key, or that identity already exists. Emits * `recovery-completed`. */
private async runFinalize(apply: boolean): Promise<void> {
const recordStream = await this.recordForKeyOrMinigate();
const target = this.named("$o", "target");
const record = recordStream.getState();
this.requireTargetOf(record, target);
if (record.status !== "waiting") throw "Recovery finalize - record is not waiting";
if (this.now() < new Date(record.finalAt).getTime()) throw "Recovery finalize - finalAt has not been reached";
const old = target.getState();
if (old.recoveredTo) throw "Recovery finalize - target is already recovered";
this.requireActiveRecovery(recordStream, target);
if (this.sha256(record.newKey.public + "identity") !== record.newIdentity) {
throw "Recovery finalize - recorded identity id does not match the new key";
}
if (await this.streamExists(record.newIdentity)) {
throw "Recovery finalize - the new identity already exists";
}
if (!apply) return;
const carriedAuthorities = (target.getAuthorities() || []).filter(
(a: any) => a.stake !== 100 && a.public !== record.newKey.public && record.carryKeys.indexOf(a.hash) !== -1
);
// >>> owner-gate
// Only stake 0 or 80 is carried (see runStart); anything else is left behind, so no carried key holds more than 80.
// Bounded by the target's authority list.
for (let i = carriedAuthorities.length - 1; i >= 0; i--) {
if (carriedAuthorities[i].stake !== 0 && carriedAuthorities[i].stake !== 80) carriedAuthorities.splice(i, 1);
}
// <<< owner-gate
const carriedHashes = carriedAuthorities.map((a: any) => a.hash);
const carried = carriedAuthorities.map((a: any) => {
const copy: any = { public: a.public, type: a.type, stake: a.stake };
if (a.label !== undefined) copy.label = a.label;
if (a.expire !== undefined) copy.expire = a.expire;
return copy;
});
const pick = (map: any): any => {
const out: any = {};
for (const hash of carriedHashes) if (map && map[hash] !== undefined) out[hash] = map[hash];
return out;
};
const created = this.newActivityStream("identity", record.newKey.public);
created.setAuthorities([{ public: record.newKey.public, type: record.newKey.type, stake: 100 }, ...carried]);
const version = (old.recovery.version || 0) + 1;
const next: any = { ...old };
delete next.recovery;
delete next.pendingTreasury;
delete next.hasTreasury;
delete next.requiresTreasury;
next.restrictions = pick(old.restrictions);
next.agentUsage = pick(old.agentUsage);
if (old.hasTreasury && carriedHashes.indexOf(old.hasTreasury) !== -1) {
next.hasTreasury = old.hasTreasury;
if (old.requiresTreasury !== undefined) next.requiresTreasury = old.requiresTreasury;
}
// Prediction markets (docs/contracts/markets.md): positions move with the balance; markers and eligibility
// records belong to the old identity (its signed orders, its tenants' attestations) and do not.
delete next.mko;
delete next.el;
// >>> tenant-membership (testnet only; production gets it with the migration of the testnet contracts)
// A tenant membership record (`tm`, written only by Varnir.Tenants join, with the old identity's id in its hash)
// belongs to the old identity too: copied, it would bind the new identity to a tenant it never joined (the member
// rule would refuse its untagged wallets for a record no tenant can revoke, its hash naming the old id). The new
// identity joins again if it wants to.
delete next.tm;
// <<< tenant-membership
next.recoveredFrom = target.getId();
next.recovery = { enabled: false, version };
created.setState(next);
const now = this.iso(this.now());
// setState MERGES, so every balance-bearing field must be emptied here
// explicitly. Varnir.Swap's order holds (orderHold), their markers
// (orders) and open order proposals (pendingOrderApprovals) were copied
// to the new identity above; left on the tombstone too, the same held
// funds would exist on both identities.
target.setState({
layer2: {},
orderHold: {},
orders: {},
pendingOrderApprovals: {},
mkt: {},
el: {},
recovery: { enabled: false, version },
recoveredTo: created.getId(),
recoveredAt: now,
recoveryRecord: recordStream.getId(),
});
await target.getVolatile();
target.setVolatile({ recovery: null });
recordStream.setState({ status: "completed", closedAt: now, closedReason: "completed" });
this.event.emit("recovery-completed", {
oldIdentity: target.getId(),
newIdentity: created.getId(),
record: recordStream.getId(),
});
}/** A stored balance (`{hex}`, number or decimal string) as a bigint; anything else is 0. */ private toBigInt(value: any): bigint {
if (value && typeof value === "object" && typeof value.hex === "string") return BigInt(value.hex);
if (typeof value === "number") return BigInt(Math.trunc(value));
if (typeof value === "string" && value.length) return BigInt(value);
return BigInt(0);
}/** * `sweep` (the new identity's stake-100 key on `$i.new`, or a gateway * with `$o.new`): moves every positive balance that reached the * tombstoned `$o.old` after migration onto the new identity. The two must * be a recovery pair (`recoveredTo` / `recoveredFrom`); refused when there * is nothing to sweep. Emits `recovery-swept`. */
private async runSweep(apply: boolean): Promise<void> {
const inputs: any = this.transactions.$i || {};
let fresh: any;
if (inputs.new) {
fresh = this.named("$i", "new");
this.requireStake100(fresh);
} else {
await this.requireMinigate();
fresh = this.named("$o", "new");
}
const old = this.named("$o", "old");
const oldState = old.getState();
const newState = fresh.getState();
if (oldState.recoveredTo !== fresh.getId() || newState.recoveredFrom !== old.getId()) {
throw "Recovery sweep - old and new identities are not a recovery link";
}
const moved: any = {};
const layer2: any = JSON.parse(JSON.stringify(newState.layer2 || {}));
for (const network of Object.keys(oldState.layer2 || {})) {
for (const token of Object.keys(oldState.layer2[network] || {})) {
const amount = this.toBigInt(oldState.layer2[network][token] && oldState.layer2[network][token].balance);
if (amount <= BigInt(0)) continue;
if (!layer2[network]) layer2[network] = {};
const have = this.toBigInt(layer2[network][token] && layer2[network][token].balance);
layer2[network][token] = { ...(layer2[network][token] || {}), balance: (have + amount).toString() };
if (!moved[network]) moved[network] = {};
moved[network][token] = amount.toString();
}
}
if (!Object.keys(moved).length) throw "Recovery sweep - nothing to sweep";
if (!apply) return;
fresh.setState({ layer2 });
old.setState({ layer2: {} });
this.event.emit("recovery-swept", { oldIdentity: old.getId(), newIdentity: fresh.getId(), moved });
}