Testnet Mode — switch back to Production in the menuheader when you're done.
VarnirKeyHealthFix extends Event
/**
* Voting round: after the social-recovery guard, refuses an MPC-TSS key,
* a key with no `recovery` in progress, a wrong token and a requester
* whose public-key hash is not the recorded `recovery.owner`.
*
* @returns {Promise<boolean>}
* @memberof VarnirKeyHealthFix
*/ public vote(): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
// Social recovery (spec §4.5): a recovered identity is dead, a frozen one cannot move money.
const recoveryRefusal = this.refuseRecoveredStreams([]);
if (recoveryRefusal) return reject(recoveryRefusal);
// Owner-signed key retirement (class comment).
const entry = this.transactions.$entry;
if (entry === "retire" || entry === "frozensweep" || entry === "purge") {
try {
this.setTimeout(MPC2_VOTE_TIMEOUT_MS);
this.assertOwnerAuthority();
if (entry === "retire") {
this.voteRetire();
} else if (entry === "frozensweep") {
await this.voteFrozenSweep();
} else {
this.votePurge();
}
return resolve(true);
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
}
// Get Stream Activity (owner ofthe request not the key)
// const owner: Activity = this.getActivityStreams(
// this.transactions.$i.owner
// );
const ownerGetId = this.ActiveCrypto.Hash.getHash(
this.transactions.$i.admin.publicKey
);
const key: Activity = this.getActivityStreams(this.transactions.$o.key);
const keyData = key.getState();
// An old (#200) mpc-tss key has no node-level refresh: its parts are
// never sent anywhere again (retired untouched, plan Task 5.2). Only an
// mpc2 key (mpcProtocol, from Create's mpc2 keygen) is redistributed,
// on its own path below (class comment).
if (keyData.keyMethod === 'mpc-tss' && keyData.mpcProtocol === undefined) {
return reject("Recovery not supported for old MPC-TSS keys (no mpcProtocol): retire them");
}
// Only Create's mpc2 keygen writes mpcProtocol, always with mpc-tss; the
// Standard path would send an mpc2 part to /redistribute as a whole key.
if (keyData.keyMethod !== 'mpc-tss' && keyData.mpcProtocol !== undefined) {
return reject("mpcProtocol on a key that is not mpc-tss");
}
// A node that has already activated these tables spent its repair token
// (re-review R-3), but must still take part when the same requester
// retries the activation to complete a split one forward (R-1). It then
// holds only current parts and changes nothing of its own.
const retryActivated = entry === "mpcactivate" && !keyData.recovery && keyData.mpcRefresh &&
keyData.mpcRefresh.owner === ownerGetId &&
JSON.stringify(keyData.partHashes) === JSON.stringify(this.transactions.$i.admin.tables);
if (retryActivated) {
// Authorised by the activation record below; no token to compare.
} else if (keyData.recovery) {
if (keyData.recovery.token !== this.transactions.$i.admin.token) {
return reject("Token not matching");
}
if (keyData.recovery.owner !== ownerGetId) {
return reject("Requestee not matching");
}
} else {
return reject("No Recovery in progress");
}
if (keyData.mpcProtocol !== undefined) {
try {
this.setTimeout(MPC2_REDISTRIBUTE_VOTE_TIMEOUT_MS);
// Two phases (PR #359 review H-1, H-2): the default entry stages
// the new parts beside the old ones; `mpcactivate` swaps them in
// after a canary signs under them.
if (entry === "mpcactivate") {
await this.voteMpc2Activate(key, keyData);
} else {
await this.voteMpc2Redistribute(key, keyData);
}
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
} else if (entry === "mpcactivate") {
return reject("mpcactivate is for an mpc2 key");
}
return resolve(true);
});
}/**
* Commit round, on each node: picks this node's share from its volatile
* (current, else up to three levels of `history`; empty when none or the
* volatile is unreadable), posts it to `/redistribute`, clears the key's
* `recovery` and writes the returned share, address and hashes as the new
* volatile with the old one under `history`. When the volatile was
* missing, the new one is also written straight to the node's local
* database.
*
* @returns {Promise<any>}
* @memberof VarnirKeyHealthFix
*/ public commit(): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
const entry = this.transactions.$entry;
if (entry === "retire") {
this.commitRetire();
return resolve(true);
}
if (entry === "frozensweep") {
this.commitFrozenSweep();
return resolve(true);
}
if (entry === "purge") {
await this.commitPurge();
return resolve(true);
}
if (entry === "mpcactivate") {
if (this.mpc2Activate) {
await this.commitMpc2Activate();
} else {
// Committing without having voted (PR #359 review L-1): this node
// knows nothing it could activate, so it writes nothing.
this.returnToRemote({activated: false, reason: "this node did not vote"});
}
return resolve(true);
}
if (this.mpc2Redistribute) {
await this.commitMpc2Redistribute();
return resolve(true);
}
// An mpc2 key must never fall through to the Standard commit below,
// which would post its part to `/redistribute` as a whole key: a node
// committing without having voted writes nothing (review L-1).
const fixed: any = this.getActivityStreams(this.transactions.$o.key).getState();
if (fixed && fixed.mpcProtocol !== undefined) {
this.returnToRemote({committed: false, reason: "this node did not vote"});
return resolve(true);
}
// Clear recovery in state we can just assume it is ok, then run another check
const key: Activity = this.getActivityStreams(this.transactions.$o.key);
const keyData = key.getState();
let volatileMissing = false;
let payload = {
umid: this.umid,
network: keyData.symbol,
address: "",
part: "",
splits: {
threshold: THRESHOLD,
total: TOTAL
}
};
let volatile;
try {
// Can't always fetch volatile
volatile = await key.getVolatile();
// Only will work once, if public private empty check history!
if (volatile.public && volatile.private) {
if (volatile.private.part) {
payload = {
umid: this.umid,
network: keyData.symbol,
address: volatile?.public.address || "",
part: volatile?.private.part || "",
splits: {
threshold: THRESHOLD,
total: TOTAL
}
};
} else {
if (volatile.history && volatile.history.private.part) {
payload = {
umid: this.umid,
network: keyData.symbol,
address: volatile.history.public.address || "",
part: volatile.history.private.part || "",
splits: {
threshold: THRESHOLD,
total: TOTAL
}
};
} else {
if (volatile?.history?.history && volatile.history.history.private.part) {
payload = {
umid: this.umid,
network: keyData.symbol,
address: volatile.history.history.public.address || "",
part: volatile.history.history.private.part || "",
splits: {
threshold: THRESHOLD,
total: TOTAL
}
};
} else {
if (volatile?.history?.history.history && volatile.history.history.history.private.part) {
payload = {
umid: this.umid,
network: keyData.symbol,
address: volatile.history.history.history.public.address || "",
part: volatile.history.history.history.private.part || "",
splits: {
threshold: THRESHOLD,
total: TOTAL
}
};
}
}
}
}
} else {
volatileMissing = true;
// await HTTP.send(`http://localhost:5259/activeledger/`, "POST", [], {
// _id: `${key.getId()}:volatile`,
// });
}
} catch {
// Could be a temporary database issue however not a problem as "restore" keeps history
volatile = {};
payload = {
umid: this.umid,
network: keyData.symbol,
address: "",
part: "",
splits: {
threshold: THRESHOLD,
total: TOTAL
}
};
volatileMissing = true;
// await HTTP.send(`http://localhost:5259/activeledger/`, "POST", [], {
// _id: `${key.getId()}:volatile`,
// });
}
this.setTimeout(1200000)
// Probably same error running in vote so running here for now
const response = await HTTP.send(
`https://${CVM_HOST}/redistribute`,
"POST",
[],
payload,
false,
20
);
this.keyGenOutput = response.data as KeyGenOutput;
delete keyData.recovery;
key.setState(keyData);
const keyVolatileData = {
private: {
part: this.keyGenOutput.part,
},
public: {
address: this.keyGenOutput.address,
key: this.keyGenOutput.address,
hashes: this.keyGenOutput.hashes,
},
history: JSON.parse(JSON.stringify(volatile)),
}
key.setVolatile(keyVolatileData);
// If missing seed it there directly (as we wont have it pulled in Activeledger)
if (volatileMissing) {
await HTTP.send(`http://localhost:5259/activeledger/`, "POST", [], {
_id: `${key.getId()}:volatile`,
...keyVolatileData
});
}
resolve(true);
});
} 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;
}/** * Throws unless `$i.owner` has authority on this contract's own stream * (`$o.contract`), as Create's `mod` checks. Retiring, sweeping and purging * decide what happens to a key's coins and parts: only the contract owner * may ask, and the node quorum still decides. */
private assertOwnerAuthority(): void {
if (!this.transactions.$o || !this.transactions.$o.contract) {
throw "Missing Contract Output";
}
const contract: Activity = this.getActivityStreams(this.transactions.$o.contract);
// The stream must be THIS contract's, or any stream the signer controls
// would do.
if (typeof this.transactions.$contract !== "string" || this.transactions.$contract.substring(0, 64) !== contract.getId()) {
throw "Contract Not Matching";
}
const signer = this.getActivityStreams(this.transactions.$i.owner).getId();
if (!(contract as any).getAuthorities().some((v: any) => v.public === signer)) {
throw "No Contract Authority";
}
}/** `$o.key`'s activity and state, refused unless it is an mpc-tss key: the only keys these entries apply to. */
private mpcKeyOnOutput(): {key: Activity; state: any}/** `retire` vote: see the class comment. */
private voteRetire(): void {
const {state} = this.mpcKeyOnOutput();
// Retired once: a second record would move the date the pool dropped it.
if (state.retired !== undefined) {
throw "The key is already retired";
}
}/** `retire` commit: the record, and the event every gateway drops the key from its pool on. */
private commitRetire(): void {
const key: Activity = this.getActivityStreams(this.transactions.$o.key);
const state = key.getState() as any;
state.retired = {at: this.cDate, umid: this.umid};
key.setState(state);
this.event.emit("wallet-retired", {stream: key.getId(), network: state.network, symbol: state.symbol, address: state.address});
}/** * Throws unless the ledger freeze is switched on: Varnir.CryptoTransfer's * contract data `mpc2FreezeEnabled: true` (Adam 2026-10-09, * docs/decisions/2026-10-09-mpc-freeze-behind-flag.md). Missing, false, * malformed or unreadable is OFF. Why a flag, default off: recording a * freeze starts the frozen-key machinery (a new deposit address, held * Bitcoin deposits, the owner's sweep), which needs much more testing * first. While it is off, a key the CVMs refuse in memory simply stays * unsigned, and minigate pages "[MPC-FREEZE] ... should be frozen" for a * person to act on; nothing is written to the ledger. */
private async assertFreezeEnabled(what: string): Promise<void> {
const flagContract = this.mpc2HaltContract();
let data: any = {};
try {
const doc: any = /^[0-9a-f]{64}$/.test(flagContract) ? await this.getAnyStreamReadOnly(`${flagContract}:data`) : null;
data = doc && typeof doc === "object" && doc.data && typeof doc.data === "object" ? doc.data : {};
} catch (e) {
data = {};
}
if (data.mpc2FreezeEnabled !== true) {
throw `${what}: the ledger freeze is off (mpc2FreezeEnabled); a person reviews the key by hand`;
}
}/** * The signed-proof switch (decision 2026-10-10, review M3 of PR #430): true * only when Varnir.CryptoTransfer's contract data holds * `mpc2RequireSignedProof: true`. Missing, false, malformed, unreadable or * an unconfigured contract id is OFF, which is the rule before the switch * (a canary or a signed proof admits an Advanced wallet). */
private async mpc2SignedProofRequired(): Promise<boolean> {
const id = this.mpc2HaltContract();
if (!/^[0-9a-f]{64}$/.test(id)) {
return false;
}
try {
const doc: any = await this.getAnyStreamReadOnly(`${id}:data`);
const data = doc && typeof doc === "object" && doc.data && typeof doc.data === "object" ? doc.data : {};
return data.mpc2RequireSignedProof === true;
} catch (e) {
return false;
}
}/** `frozensweep` vote: see the class comment. */
private async voteFrozenSweep(): Promise<void> {
// Behind the freeze flag (Adam 2026-10-09): no sweep while it is off.
await this.assertFreezeEnabled("frozensweep");
const {key, state} = this.mpcKeyOnOutput();
// Only an mpc2 key has CVMs that could honour a sweep; an old key is
// retired untouched (plan Task 5.2).
if (state.mpcProtocol !== MPC2_PROTOCOL) {
throw "frozensweep: not an mpc2 key";
}
// A sweep exists for a frozen key only: any other key signs normally.
if (state.mpcFrozen === undefined) {
throw "frozensweep: the key is not frozen";
}
// Only a stall freeze (PR #416 review M3). After a strike the peer sent
// the bad message, the abort oracle itself, and a sweep would run the
// share with it again: the key waits for the peer to be replaced. A
// record from before kinds were kept counts as a strike (fail closed).
if (!state.mpcFrozen || state.mpcFrozen.kind !== "stall") {
throw "frozensweep: the key was not frozen for a stall; it waits for the peer to be replaced";
}
// A second authorisation is a top-up (review H1, L1): the total stays
// within the lifetime cap, since each signing runs the frozen share again.
if (state.mpcSweep !== undefined) {
const had = state.mpcSweep && typeof state.mpcSweep.signings === "number" ? state.mpcSweep.signings : 1;
if (had + this.sweepSignings() > MPC2_SWEEP_LIFETIME_SIGNINGS) {
throw `frozensweep: a key may be authorised at most ${MPC2_SWEEP_LIFETIME_SIGNINGS} signings in all`;
}
}
if (state.mpcPurged !== undefined) {
throw "frozensweep: the key is purged";
}
if (!this.transactions.$o.to) {
throw "frozensweep: no destination ($o.to)";
}
// How many signings the sweep may take: each one runs the frozen share
// with the peer once more, so the owner fixes the number here and the
// CVMs hold to it too.
this.sweepSignings();
const to: Activity = this.getActivityStreams(this.transactions.$o.to);
if (to.getId() === key.getId()) {
throw "frozensweep: a key cannot be swept to itself";
}
const dest = to.getState() as any;
// The destination is fixed to a fresh Advanced pool wallet (spec §4.5,
// operator-reviewed rotation): an mpc2 key that has proved it can sign
// (canary), on the same chain, in the pool (no owner), and not itself
// frozen or retired. Anything else could strand or misdirect the coins.
if (!dest || dest.keyMethod !== "mpc-tss" || dest.mpcProtocol !== MPC2_PROTOCOL) {
throw "frozensweep: the destination must be an mpc2 key";
}
if (dest.network !== state.network) {
throw "frozensweep: the destination is on another network";
}
if (dest.owner !== null && dest.owner !== undefined) {
throw "frozensweep: the destination must be an unassigned pool wallet";
}
if (dest.mpcFrozen !== undefined) {
throw "frozensweep: the destination is frozen";
}
if (dest.retired !== undefined || dest.mpcPurged !== undefined) {
throw "frozensweep: the destination is retired";
}
// A canary or a signed DiffConsensus proof (decision 2026-10-10, PR #430
// review L1): either shows the destination's parts sign for its Q, as the
// pool rule (poolLifecycleRefusal) accepts. With `mpc2RequireSignedProof`
// on, only the signed proof, as for any unowned pool wallet (review M3).
const destSigned = !!(dest.diffConfirmed && dest.diffConfirmed.sig);
if (!destSigned && (await this.mpc2SignedProofRequired())) {
throw "frozensweep: the destination has no signed DiffConsensus proof (mpc2RequireSignedProof)";
}
if (dest.mpcCanary === undefined && !destSigned) {
throw "frozensweep: the destination has no canary or signed DiffConsensus proof";
}
// Another key, not another stream over the frozen share (review M3 of
// PR #349: a freeze holds for its Q under any key id).
if (dest.publicKey === state.publicKey) {
throw "frozensweep: the destination has the frozen key's Q";
}
if (typeof dest.address !== "string" || dest.address.length === 0) {
throw "frozensweep: the destination has no address";
}
// Each node asks its own CVMs. A key frozen against a suspect peer is not
// swept while that peer is suspect (plan Task 2.6), and a CVM whose
// freeze record is broken is not asked to sign anything.
const keyId = key.getId();
let response: any;
try {
response = await HTTP.send(
`${MPC2_EGRESS_URL}/mpc2/status`,
"POST",
[],
{umid: this.umid, network: state.network, keyId, keyMethod: "mpc-tss", mpcProtocol: MPC2_PROTOCOL, payload: {}},
false,
MPC2_STATUS_HTTP_TIMEOUT_S
);
} catch (e) {
throw "frozensweep: the egress agent did not answer";
}
const both = response ? response.data : null;
for (const [label, party, who] of [["a", 0, "CVM-A"], ["b", 1, "CVM-B"]] as [string, number, string][]) {
const answer = both && typeof both === "object" ? both[label] : null;
const report = answer && answer.status === "ok" ? answer.report : null;
// A node that cannot read both CVMs cannot say the peer is trusted.
if (!report || typeof report !== "object" || answer.umid !== this.umid || report.umid !== this.umid || report.party !== party) {
throw `frozensweep: no status report from ${who}`;
}
if (report.peerSuspect !== null && report.peerSuspect !== undefined) {
throw `frozensweep: ${who} holds its peer suspect; the sweep waits for the peer to be replaced`;
}
if (report.halted !== null && report.halted !== undefined) {
throw `frozensweep: ${who} is halted (${String(report.halted)})`;
}
// No strike on record against the peer (review M3): one strike does
// not make it suspect, but it is the peer that sent a bad message.
if (report.strikes !== 0) {
throw `frozensweep: ${who} reports a strike against its peer; the sweep waits for the peer to be replaced`;
}
}
}/** * `$i.owner.signings`: absent is 1, else a whole number from 1 to * MPC2_SWEEP_MAX_SIGNINGS. Throws otherwise: a typo must not buy more runs * of a frozen share than the owner meant. */
private sweepSignings(): number {
const raw = this.transactions.$i.owner ? this.transactions.$i.owner.signings : undefined;
if (raw === undefined) {
return 1;
}
if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 1 || raw > MPC2_SWEEP_MAX_SIGNINGS) {
throw `frozensweep: signings must be a whole number from 1 to ${MPC2_SWEEP_MAX_SIGNINGS}`;
}
return raw;
}/** `frozensweep` commit: the one authorisation, and retirement (a swept key is never assigned again). */
private commitFrozenSweep(): void {
const key: Activity = this.getActivityStreams(this.transactions.$o.key);
const to: Activity = this.getActivityStreams(this.transactions.$o.to);
const state = key.getState() as any;
const prev = state.mpcSweep;
// A first authorisation, or a top-up (version + 1) that keeps what was
// signed and armed and adds signings.
state.mpcSweep = {
at: this.cDate,
umid: this.umid,
to: to.getId(),
toAddress: (to.getState() as any).address,
signings: (prev ? (typeof prev.signings === "number" ? prev.signings : 1) : 0) + this.sweepSignings(),
signed: prev && Array.isArray(prev.signed) ? prev.signed : [],
attempts: prev && Array.isArray(prev.attempts) ? prev.attempts : [],
version: prev && typeof prev.version === "number" ? prev.version + 1 : 1,
...(prev && typeof prev.signedStream === "string" ? {signedStream: prev.signedStream} : {}),
};
if (state.retired === undefined) {
state.retired = {at: this.cDate, umid: this.umid};
}
key.setState(state);
}/** `purge` vote: see the class comment. */
private votePurge(): void {
const {state} = this.mpcKeyOnOutput();
if (state.mpcPurged !== undefined) {
throw "The key is already purged";
}
// Deleting parts is final: only a key nobody assigns any more.
if (state.retired === undefined) {
throw "Only a retired key can be purged";
}
// An assigned deposit wallet keeps receiving: its user still pays to the
// address, and the ledger still credits it (PR #358 re-review Q1). Its
// parts are what moves those coins, so it must be released or its owner
// moved to a fresh wallet before any purge.
if (state.owner !== null && state.owner !== undefined) {
throw "purge: the key is assigned to an owner; release or re-assign it first";
}
const basis = this.transactions.$i.owner ? this.transactions.$i.owner.basis : undefined;
if (basis === "swept") {
// The sweep must have been signed, not only authorised: until then the
// parts are what moves the coins out.
if (!state.mpcSweep || typeof state.mpcSweep.signedStream !== "string" || state.mpcSweep.signedStream.length === 0) {
throw "purge: the key's sweep has not been signed";
}
} else if (basis === "zero-balance") {
// A purge on the owner's word is final, so it waits (PR #358 review
// L1): MPC2_PURGE_DELAY_MS of consensus time after retirement. In that
// window every payout bound to the key before it retired (CryptoTransfer
// binds no new one to a retired key) is signed, held at most 24 h by
// the new-recipient hold, and confirmed or refunded; and a deposit sent
// to the old address by someone who had it is seen and credited.
const retiredAt = new Date(state.retired.at).getTime();
const now = new Date(this.cDate).getTime();
if (!Number.isFinite(retiredAt) || now - retiredAt < MPC2_PURGE_DELAY_MS) {
throw "purge: a zero-balance purge waits 7 days after retirement";
}
} else {
throw "purge: basis must be swept or zero-balance";
}
}/** * `purge` commit: this node's parts are deleted, `history` too (it keeps * earlier parts), and the key records why. The public half stays, so the * address and tables remain readable. */
private async commitPurge(): Promise<void> {
const key: Activity = this.getActivityStreams(this.transactions.$o.key);
const state = key.getState() as any;
let volatile: any = null;
try {
volatile = await key.getVolatile();
} catch (e) {
volatile = null;
}
key.setVolatile({private: {}, public: volatile && volatile.public ? volatile.public : {}});
state.mpcPurged = {at: this.cDate, umid: this.umid, basis: this.transactions.$i.owner.basis};
key.setState(state);
}/** * The pinned signers `[CVM_A_SIGNER, CVM_B_SIGNER]` (checksummed). Throws * while either is blank (not configured until gate G3) or malformed, or * when they are equal: one key on both hosts lets one host sign both * parties' tables (PR #355 review L-2). */
private mpc2Signers(): [string, string] {
const [rawA, rawB] = this.mpc2SignerConstants();
if (rawA === "" || rawB === "") {
throw "mpc2 redistribute: the CVM signers are not configured on this network";
}
let a = "";
let b = "";
try {
a = utils.getAddress(rawA);
b = utils.getAddress(rawB);
} catch (e) {
throw "mpc2 redistribute: a CVM signer address is malformed";
}
if (a === b) {
throw "mpc2 redistribute: the two CVM signers must differ";
}
return [a, b];
}/** The per-tree constants, read in one place (tests pin other values here). */
private mpc2SignerConstants(): [string, string] {
return [CVM_A_SIGNER, CVM_B_SIGNER];
}/** * The pinned receipt-key addresses, by partIndex (checksummed). Throws * unless they are exactly four well-formed, distinct addresses: blank is * "not configured on this network" (refuse, never skip the check), and one * key at two indexes would let one agent receipt two nodes' deliveries. */
private mpc2OperatorSigners(): string[] {
return this.mpc2CheckOperators(this.mpc2OperatorSignerConstants());
}/** The rules of mpc2OperatorSigners for any set: the tree's constants, or the set a stage recorded. */
private mpc2CheckOperators(raw: any): string[] {
if (!Array.isArray(raw) || raw.length !== TOTAL || raw.some((a: any) => typeof a !== "string" || a === "")) {
throw "mpc2 redistribute: the node receipt keys (MPC2_OPERATOR_SIGNERS) are not configured on this network";
}
let out: string[] = [];
try {
out = raw.map((a: any) => utils.getAddress(a));
} catch (e) {
throw "mpc2 redistribute: a node receipt key address is malformed";
}
if (out.some((a: string, i: number) => out.indexOf(a) !== i)) {
throw "mpc2 redistribute: the four node receipt keys must differ";
}
return out;
}/** The per-tree constant, read in one place (tests pin other values here). */
private mpc2OperatorSignerConstants(): string[] {
return MPC2_OPERATOR_SIGNERS;
}/** * The receipt tuple for one delivery, built from what is being committed, * never from what a node sent: verifying a signature over this binds every * field (the refresh, the key, its network, the party, the index, the part). */
private mpc2Receipt(umid: string, keyId: string, network: string, party: number, partIndex: number, partHash: string): any {
return {umid, keyId, network, party, partIndex, partHash};
}/** * The address whose key made `receiptSig` (`r ‖ s ‖ v` hex, v 27/28) over * SHA-256(MPC2_RECEIPT_DOMAIN + "\n" + canonical JSON of `receipt`), or "" * when it is malformed. Pinned by the published vector * (infra/mpc-egress/test/vectors/receipt-v1.json). */
private mpc2ReceiptSigner(receipt: any, receiptSig: any): string {
if (typeof receiptSig !== "string" || !/^[0-9a-f]{128}(1b|1c)$/.test(receiptSig)) {
return "";
}
try {
const digest = utils.sha256(utils.toUtf8Bytes(MPC2_RECEIPT_DOMAIN + "\n" + this.mpc2Canonical(receipt)));
return utils.recoverAddress(digest, "0x" + receiptSig);
} catch (e) {
return "";
}
}/** * Both of one node's receipts verify: for each party, `receiptSigs[party]` * recovers, over the tuple rebuilt for this refresh `umid`, this key and * network, that party, `partIndex` and that party's table entry at * `partIndex`, to the receipt key pinned for `partIndex`. A receipt from * another node's key, for another index, part, party, key or refresh, or * missing, fails. */
private mpc2ReceiptsVerify(receiptSigs: any, umid: string, keyId: string, network: string, partIndex: number, tables: string[][], operators: string[]): boolean {
if (!Array.isArray(receiptSigs) || receiptSigs.length !== 2) return false;
for (const party of [0, 1]) {
const r = this.mpc2Receipt(umid, keyId, network, party, partIndex, tables[party][partIndex - 1]);
if (this.mpc2ReceiptSigner(r, receiptSigs[party]) !== operators[partIndex - 1]) return false;
}
return true;
}/** * Canonical JSON as the CVMs sign it (packages/cvm-attest canonical.ts): * object keys sorted, no whitespace, strings and numbers as JSON. */
private mpc2Canonical(v: any): string {
if (Array.isArray(v)) {
return "[" + v.map((x) => this.mpc2Canonical(x)).join(",") + "]";
}
if (v !== null && typeof v === "object") {
return "{" + Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + this.mpc2Canonical(v[k])).join(",") + "}";
}
if (typeof v === "number" && !Number.isFinite(v)) {
throw "mpc2 redistribute: a table holds a non-finite number";
}
return JSON.stringify(v);
}/** * The address whose key made `signerSig` (`r ‖ s ‖ v` hex, v 27/28) over * SHA-256(MPC2_REDISTRIBUTE_DOMAIN + "\n" + canonical JSON of `table`), * or "" when it is malformed. Pinned by the published vector * (apps/confidentialVM/test/vectors/redistribute-table-v1.json). */
private mpc2TableSigner(table: any, signerSig: any): string {
if (typeof signerSig !== "string" || !/^[0-9a-f]{128}(1b|1c)$/.test(signerSig)) {
return "";
}
try {
const digest = utils.sha256(utils.toUtf8Bytes(MPC2_REDISTRIBUTE_DOMAIN + "\n" + this.mpc2Canonical(table)));
return utils.recoverAddress(digest, "0x" + signerSig);
} catch (e) {
return "";
}
}/** Four distinct SHA-256 hex hashes. */
private mpc2IsTable(t: any): boolean {
return Array.isArray(t) && t.length === TOTAL &&
t.every((h: any, i: number) => typeof h === "string" && /^[0-9a-f]{64}$/.test(h) && t.indexOf(h) === i);
}/** The mpc2 redistribute vote (class comment, steps 1 to 3). Throws a string on any refusal. */
private async voteMpc2Redistribute(key: Activity, state: any): Promise<void> {
// A frozen key is never refreshed (the CVMs refuse it too, by key and by
// Q): new parts would let a key the CVMs stopped sign again. A purged key
// has no parts left to refresh.
if (state.mpcFrozen !== undefined) {
throw "mpc2 redistribute: the key is frozen";
}
if (state.mpcPurged !== undefined) {
throw "mpc2 redistribute: the key is purged";
}
if (state.mpcProtocol !== MPC2_PROTOCOL) {
throw "mpc2 redistribute: unknown mpcProtocol";
}
// Off until consensus messages are signed (PR #359 review M-1), and never
// with a peer a CVM held suspect (PR #358 review M2).
if (!this.mpc2RedistributeEnabled()) {
throw "mpc2 redistribute is off on this network until security.signedConsensus is on";
}
await this.assertNoMpcHalt();
const signers = this.mpc2Signers();
// Before any call: without the pinned receipt keys no delivery could be
// verified, so the CVMs' new parts would be handed out for nothing.
const operators = this.mpc2OperatorSigners();
const keyId = key.getId();
// The CVMs name a key by its stream id, as at keygen and signing.
if (typeof keyId !== "string" || !/^[0-9a-f]{64}$/.test(keyId)) {
throw "mpc2 redistribute: the key id must be 64 lowercase hex";
}
const network = state.network;
if (typeof network !== "string" || !/^[A-Za-z0-9-]{1,32}$/.test(network)) {
throw "mpc2 redistribute: the key has no network";
}
const q = state.publicKey;
if (typeof q !== "string" || !/^0[23][0-9a-f]{64}$/.test(q) || (state.pubkey !== undefined && state.pubkey !== q)) {
throw "mpc2 redistribute: the key has no compressed publicKey";
}
// The payload is the stored tables exactly; each CVM checks the old
// parts against them before it rebuilds its share.
const old = state.partHashes;
if (!Array.isArray(old) || old.length !== 2 || !this.mpc2IsTable(old[0]) || !this.mpc2IsTable(old[1]) ||
old[0].some((h: string) => old[1].indexOf(h) !== -1)) {
throw "mpc2 redistribute: the key's partHashes must be two disjoint tables of four distinct hashes";
}
let volatile: any = null;
let volatileMissing = false;
try {
volatile = await key.getVolatile();
} catch (e) {
volatile = null;
volatileMissing = true;
}
if (!volatile || !volatile.private) {
volatileMissing = true;
}
const held = (p: any, table: string[]) =>
typeof p === "string" && p.length > 0 && table.indexOf(this.ActiveCrypto.Hash.getHash(p, "sha256")) !== -1 ? p : undefined;
// Only a part that still hashes into its table counts: the CVM refuses
// any other, and the node is then simply one that lost its part (asks
// without it, which is not a vote, and still gets its new one).
const part = held(volatile && volatile.private ? volatile.private.part : undefined, old[0]);
const part2 = held(volatile && volatile.private ? volatile.private.part2 : undefined, old[1]);
let response: any;
try {
response = await HTTP.send(
`${MPC2_EGRESS_URL}/mpc2/redistribute`,
"POST",
[],
{
umid: this.umid,
network,
keyId,
keyMethod: "mpc-tss",
mpcProtocol: MPC2_PROTOCOL,
...(part === undefined ? {} : {part}),
...(part2 === undefined ? {} : {part2}),
// Exactly what the CVMs agree on: no `splits` or `threshold` (C3).
payload: this.mpc2RedistributePayload(state, old),
},
false,
MPC2_REDISTRIBUTE_HTTP_TIMEOUT_S
);
} catch (e) {
throw "mpc2 redistribute: the egress agent did not answer";
}
const both = response ? response.data : null;
if (!both || typeof both !== "object" || Array.isArray(both)) {
throw "mpc2 redistribute: no answer from the egress agent";
}
const a = this.mpc2CheckRedistributed(both.a, 0, "CVM-A", keyId, network, q, signers[0], operators);
const b = this.mpc2CheckRedistributed(both.b, 1, "CVM-B", keyId, network, q, signers[1], operators);
// One node, one index: part i of A's share and part i of B's.
if (a.partIndex !== b.partIndex) {
throw "mpc2 redistribute: partIndex differs between CVM-A and CVM-B";
}
const all = [...old[0], ...old[1]];
// New parts are made with fresh randomness: a new hash equal to an old
// one, or to the other party's, is a replayed or crossed table.
for (const h of [...a.partHashes, ...b.partHashes]) {
if (all.indexOf(h) !== -1) {
throw "mpc2 redistribute: a new table repeats an old hash";
}
}
if (a.partHashes.some((h: string) => b.partHashes.indexOf(h) !== -1)) {
throw "mpc2 redistribute: the two new tables overlap";
}
this.mpc2Redistribute = {
partIndex: a.partIndex,
keyId,
network,
operators,
receiptSigs: [a.receiptSig, b.receiptSig],
tables: [a.partHashes, b.partHashes],
parts: [a.part, b.part],
volatile,
volatileMissing,
};
// This node's delivery, with its agent's two receipts (class comment,
// step 4), which every node verifies again at commit: the consensus
// message only carries them.
this.setThisInterNodeComms({
partIndex: a.partIndex,
tables: [a.partHashes, b.partHashes],
delivered: [a.partHashes[a.partIndex - 1], b.partHashes[b.partIndex - 1]],
receipts: [both.a.receipt, both.b.receipt],
receiptSigs: [both.a.receiptSig, both.b.receiptSig],
});
}/** * The redistribute payload: the stored Q and tables, plus the key's * `mpcFrozen` exactly as stored whenever it has one (PR #357). The vote * refuses a frozen key before any call, so today it is never sent; it is * there so that a CVM that forgot a freeze at a restart still refuses the * key (`ledger-frozen`) should a later path ever reach it. */
private mpc2RedistributePayload(state: any, old: string[][]): any {
return {
publicKey: state.publicKey,
partHashes: [old[0].slice(), old[1].slice()],
...(state.mpcFrozen !== undefined ? {mpcFrozen: state.mpcFrozen} : {}),
};
}/** One CVM's redistribute answer, checked against the party it must come from. Throws a string naming the CVM. */
private mpc2CheckRedistributed(raw: any, party: number, who: string, keyId: string, network: string, q: string, signer: string, operators: string[]): any {
const isObject = (x: any) => !!x && typeof x === "object" && !Array.isArray(x);
// A refusal (frozen, key-busy, quorum-complete...) is not a new table.
if (!isObject(raw) || raw.status !== "ok") {
throw `mpc2 redistribute: ${who} refused`;
}
if (raw.umid !== this.umid) {
throw `mpc2 redistribute: ${who} answered for another umid`;
}
// Filed under its own role: a swapped pair would store B's table as A's
// (PR #350 review M3, as Create checks at keygen).
if (raw.party !== party) {
throw `mpc2 redistribute: ${who}'s answer is not from party ${party}`;
}
if (raw.publicKey !== q) {
throw `mpc2 redistribute: ${who} answered for another Q`;
}
if (!this.mpc2IsTable(raw.partHashes)) {
throw `mpc2 redistribute: ${who}'s new table must be four distinct hashes`;
}
if (typeof raw.partIndex !== "number" || !Number.isInteger(raw.partIndex) || raw.partIndex < 1 || raw.partIndex > TOTAL) {
throw `mpc2 redistribute: ${who}'s partIndex must be 1 to 4`;
}
// The signed table must say exactly this request and exactly the table
// being committed (review M-1): nothing on the node-to-CVM path can then
// swap in random parts with their hashes.
const t = raw.table;
if (!isObject(t) || Object.keys(t).length !== 7 || t.v !== 1 || t.umid !== this.umid || t.keyId !== keyId ||
t.network !== network || t.party !== party || t.publicKey !== q ||
JSON.stringify(t.partHashes) !== JSON.stringify(raw.partHashes)) {
throw `mpc2 redistribute: ${who}'s signed table is not this request's new table`;
}
// Checked here, by every node, not only by the agent (PR #355 review
// L-3): one compromised agent could otherwise feed its node a table the
// CVMs never made.
if (this.mpc2TableSigner(t, raw.signerSig) !== signer) {
throw `mpc2 redistribute: ${who}'s table signerSig is not its pinned signer's`;
}
// This node really holds its new part: it opens to the signed entry at
// its own index.
if (typeof raw.part !== "string" || raw.part.length === 0 ||
this.ActiveCrypto.Hash.getHash(raw.part, "sha256") !== raw.partHashes[raw.partIndex - 1]) {
throw `mpc2 redistribute: ${who}'s new part is not this node's entry in the signed table`;
}
// The agent's receipt must be exactly the tuple this node is about to
// share (step 4): every field equal, nothing more, so what other nodes
// verify is the delivery this node claims.
const expected = this.mpc2Receipt(this.umid, keyId, network, party, raw.partIndex, raw.partHashes[raw.partIndex - 1]);
if (!isObject(raw.receipt) || this.mpc2Canonical(raw.receipt) !== this.mpc2Canonical(expected)) {
throw `mpc2 redistribute: ${who}'s delivery receipt is not for this part`;
}
// And signed by the receipt key pinned for this index: checked here so a
// node whose agent's key is not the pinned one votes no at once rather
// than sharing a delivery every commit would refuse.
if (this.mpc2ReceiptSigner(expected, raw.receiptSig) !== operators[raw.partIndex - 1]) {
throw `mpc2 redistribute: ${who}'s delivery receipt is not signed by the receipt key pinned for part ${raw.partIndex}`;
}
return raw;
}/** * The mpc2 redistribute commit (class comment, step 5). From the inter-node * data, which is the same on every node under `$unanimous`, so every node * decides the same way. */
private async commitMpc2Redistribute(): Promise<void> {
const mine = this.mpc2Redistribute!;
const comms: any = this.getInterNodeComms() || {};
const entries = Object.keys(comms).map((k) => comms[k]);
const tables = JSON.stringify(mine.tables);
const seen: number[] = [];
let reason = "";
// Every node of the TOTAL must have received both its new parts: one
// missing could leave a party below threshold once the old parts go.
if (entries.length !== TOTAL) {
reason = `${entries.length} of ${TOTAL} nodes delivered`;
}
for (const e of entries) {
if (reason) break;
if (!e || typeof e !== "object" || typeof e.partIndex !== "number" || e.partIndex < 1 || e.partIndex > TOTAL ||
seen.indexOf(e.partIndex) !== -1) {
reason = "the nodes' part indexes are not 1 to 4 once each";
break;
}
seen.push(e.partIndex);
// One pair of tables for every node, or the nodes would store
// different hashes and the key could never sign again.
if (JSON.stringify(e.tables) !== tables) {
reason = "the nodes received different tables";
break;
}
// Each node opened exactly its own entry of each table.
if (!Array.isArray(e.delivered) || e.delivered[0] !== mine.tables[0][e.partIndex - 1] ||
e.delivered[1] !== mine.tables[1][e.partIndex - 1]) {
reason = "a node's delivered part is not its entry";
break;
}
// And its agent says so (step 4): both receipts verify, for this
// refresh, against the key pinned for its index. Without this, a
// forged consensus message could claim a delivery no agent made, and
// the old parts would later be deleted while a party's new set is short.
if (!this.mpc2ReceiptsVerify(e.receiptSigs, this.umid, mine.keyId, mine.network, e.partIndex, mine.tables, mine.operators)) {
reason = "a node's delivery receipt does not verify";
break;
}
}
if (reason) {
// Nothing written: the old tables and parts stay in force, and the
// recovery token stays so KeyHealthFix can retry under a new umid.
this.returnToRemote({committed: false, reason});
return;
}
const key: Activity = this.getActivityStreams(this.transactions.$o.key);
// Phase one of two (PR #359 review H-1, H-2): the new parts are stored
// beside the old ones, in this node's volatile only, and nothing in the
// key's state changes. Signing keeps using the old tables and parts. The
// new set takes over only at `mpcactivate`, after a canary has signed
// under it; a node that wrote nothing here (it saw fewer than four
// deliveries, or never voted) simply has no pending set, and activation
// then waits. So no split commit, and no garbage table from a hostile
// CVM, can ever leave a node without the parts that rebuild the share.
const current = mine.volatile && typeof mine.volatile === "object" ? mine.volatile : {};
const volatile = {
...current,
private: current.private && typeof current.private === "object" ? current.private : {},
public: current.public && typeof current.public === "object" ? current.public : {},
pending: {
umid: this.umid,
partIndex: mine.partIndex,
tables: [mine.tables[0].slice(), mine.tables[1].slice()],
part: mine.parts[0],
part2: mine.parts[1],
// This node's own receipts, shown again at `mpcactivate` (which has
// no fresh delivery to receipt) so activation also counts only
// verified deliveries.
receiptSigs: mine.receiptSigs.slice(),
// The receipt keys these receipts were verified against (PR #395
// review L-1). Activation verifies against this record, not today's
// constants, so rotating MPC2_OPERATOR_SIGNERS mid-refresh (after a
// split activation, say) cannot leave the key unable to complete.
operators: mine.operators.slice(),
},
};
key.setVolatile(volatile);
// As on the Standard path: a volatile that was missing is not pulled by
// the engine, so it is seeded into this node's store directly.
if (mine.volatileMissing) {
await HTTP.send(`http://localhost:5259/activeledger/`, "POST", [], {
_id: `${key.getId()}:volatile`,
...volatile,
});
}
this.returnToRemote({committed: "pending", tables: volatile.pending.tables});
}/**
* The `mpcactivate` vote (PR #359 review H-1, H-2): phase two. `$i.admin.
* tables` names the new tables a staged redistribute returned. This node
* finds the parts it holds for them: its pending set (not yet active), or
* its current parts if it already activated them (a retry after a split
* activation), or none. With parts, it runs one canary signing under the
* NEW tables (`mpc2/sign`, `tx: {canary: true}`), which exercises both
* parties' new parts, and checks the signature recovers to Q. It shares
* `{partIndex, tables, holds, delivered, canary}` and votes yes; commit
* decides from all four nodes' data.
*/ private async voteMpc2Activate(key: Activity, state: any): Promise<void> {
if (state.mpcFrozen !== undefined) {
throw "mpc2 activate: the key is frozen";
}
if (state.mpcPurged !== undefined) {
throw "mpc2 activate: the key is purged";
}
if (state.mpcProtocol !== MPC2_PROTOCOL) {
throw "mpc2 activate: unknown mpcProtocol";
}
if (!this.mpc2RedistributeEnabled()) {
throw "mpc2 redistribute is off on this network until security.signedConsensus is on";
}
await this.assertNoMpcHalt();
// Before the canary: activation verifies every node's receipts too, so
// the receipt keys must be configured on this network at all.
let operators = this.mpc2OperatorSigners();
const keyId = key.getId();
const network = state.network;
const q = state.publicKey;
if (typeof keyId !== "string" || !/^[0-9a-f]{64}$/.test(keyId) || typeof network !== "string" ||
typeof q !== "string" || !/^0[23][0-9a-f]{64}$/.test(q)) {
throw "mpc2 activate: the key's id, network or Q is malformed";
}
const t = this.transactions.$i.admin ? this.transactions.$i.admin.tables : undefined;
if (!Array.isArray(t) || t.length !== 2 || !this.mpc2IsTable(t[0]) || !this.mpc2IsTable(t[1]) ||
t[0].some((h: string) => t[1].indexOf(h) !== -1)) {
throw "mpc2 activate: tables must be two disjoint tables of four distinct hashes";
}
const tables = JSON.stringify(t);
let volatile: any = null;
try {
volatile = await key.getVolatile();
} catch (e) {
volatile = null;
}
let holds: "pending" | "current" | "none" = "none";
let parts: string[] = [];
// The receipts this node stored with these tables at the stage (kept
// through activation, for a retry after a split one).
let receipts: any = null;
const pending = volatile && volatile.pending;
if (pending && JSON.stringify(pending.tables) === tables) {
holds = "pending";
parts = [pending.part, pending.part2];
receipts = {umid: pending.umid, receiptSigs: pending.receiptSigs, operators: pending.operators};
} else if (JSON.stringify(state.partHashes) === tables && volatile && volatile.private) {
holds = "current";
parts = [volatile.private.part, volatile.private.part2];
const kept = volatile.receipts;
if (kept && JSON.stringify(kept.tables) === tables) {
receipts = {umid: kept.umid, receiptSigs: kept.receiptSigs, operators: kept.operators};
}
}
// The set the stage verified these receipts against (review L-1): every
// node that staged recorded the same one, from the constants of that
// deploy. A missing or malformed record refuses rather than falling back.
if (receipts) {
operators = this.mpc2CheckOperators(receipts.operators);
}
let partIndex = 0;
if (holds !== "none") {
const ia = t[0].indexOf(this.ActiveCrypto.Hash.getHash(String(parts[0]), "sha256"));
const ib = t[1].indexOf(this.ActiveCrypto.Hash.getHash(String(parts[1]), "sha256"));
// Both new parts at this node's one index, or they are not this node's.
if (ia === -1 || ia !== ib) {
holds = "none";
} else {
partIndex = ia + 1;
}
}
// "none": this node holds no part of the new tables, so it ran no canary
// (not a failure: activation simply waits for it).
let canary: "ok" | "late" | "failed" | "none" = "none";
if (holds !== "none") {
canary = await this.mpc2ActivationCanary(keyId, network, q, t, parts, state);
}
this.mpc2Activate = {keyId, network, operators, tables: t, holds, partIndex, canary};
this.setThisInterNodeComms({
partIndex,
tables: t,
holds,
delivered: holds === "none" ? [] : [t[0][partIndex - 1], t[1][partIndex - 1]],
// The stage's receipts for this node's delivery (class comment, step
// 6): every node verifies all four at commit.
receiptUmid: receipts ? receipts.umid : null,
receiptSigs: receipts ? receipts.receiptSigs : null,
canary,
});
}/** * One canary signing under the new tables (KeyHealthCheck `mpccanary`'s * checks, here because the canary decides the swap): "ok" when both CVMs' * acknowledgements name this request and one signature, over * SHA-256(MPC2_CANARY_DOMAIN ‖ keyId) computed here, recovering to Q; * "failed" when a CVM refused the new parts themselves (`part`, `share`: * garbage parts, H-2) or an answer came back and does not verify; "late" * for everything else, which says nothing about the parts: a timeout, an * unreachable agent, boot-hold, key-busy, rate limits, a node that came * after the quorum (PR #359 re-review R-4). Only "failed" can discard. */
private async mpc2ActivationCanary(keyId: string, network: string, q: string, tables: string[][], parts: string[], state: any): Promise<"ok" | "late" | "failed"> {
let response: any;
try {
response = await HTTP.send(
`${MPC2_EGRESS_URL}/mpc2/sign`,
"POST",
[],
{
umid: this.umid,
network,
keyId,
keyMethod: "mpc-tss",
mpcProtocol: MPC2_PROTOCOL,
part: parts[0],
part2: parts[1],
payload: {
publicKey: q,
partHashes: tables,
tx: {canary: true},
...(state.mpcFrozen !== undefined ? {mpcFrozen: state.mpcFrozen} : {}),
},
},
false,
MPC2_SIGN_HTTP_TIMEOUT_S
);
} catch (e) {
// A timeout or an unreachable agent says nothing about the parts: a
// retry, never a discard (PR #359 re-review R-4).
return "late";
}
const both = response ? response.data : null;
if (both && both.status === "error") {
// Only a refusal about the parts themselves is a failed canary: a part
// that does not open to its entry (`part`), or a rebuilt share that is
// not this party's share of Q (`share`). Everything else (boot-hold,
// key-busy, rate-limit, aux-not-ready, a late node, no channel) is
// transient or not about the parts, so it is "late" (R-4).
return typeof both.error === "string" && /^cvm-[ab]-(part|share)$/.test(both.error) ? "failed" : "late";
}
const isObject = (x: any) => !!x && typeof x === "object" && !Array.isArray(x);
// No answer at all: nothing came back to verify.
if (both === null || both === undefined) return "late";
// From here on something came back: anything that fails to verify fails.
if (!isObject(both)) return "failed";
for (const [answer, party] of [[both.a, 0], [both.b, 1]] as [any, number][]) {
const ack = isObject(answer) ? answer.ack : null;
if (!isObject(answer) || answer.status !== "ok" || answer.umid !== this.umid || !isObject(ack) || ack.party !== party ||
ack.umid !== this.umid || ack.keyId !== keyId || ack.network !== network || ack.publicKey !== q ||
!Array.isArray(ack.signatures) || ack.signatures.length !== 1) {
return "failed";
}
}
if (JSON.stringify(both.a.ack.signatures) !== JSON.stringify(both.b.ack.signatures)) return "failed";
const digest = utils.sha256(utils.concat([utils.toUtf8Bytes(MPC2_CANARY_DOMAIN), "0x" + keyId])).slice(2);
const sig = both.a.signature;
const entry = both.a.ack.signatures[0];
if (!isObject(sig) || sig.canary !== digest || !isObject(entry) || entry.digest !== digest || entry.r !== sig.r ||
entry.s !== sig.s || entry.v !== sig.v || typeof sig.r !== "string" || !/^[0-9a-f]{64}$/.test(sig.r) ||
typeof sig.s !== "string" || !/^[0-9a-f]{64}$/.test(sig.s) || (sig.v !== 0 && sig.v !== 1)) {
return "failed";
}
try {
const recovered = utils.recoverAddress("0x" + digest, "0x" + sig.r + sig.s + (27 + sig.v).toString(16));
return recovered === utils.computeAddress("0x" + q) ? "ok" : "failed";
} catch (e) {
return "failed";
}
}/** * The `mpcactivate` commit, from all four nodes' data. Nothing is decided * unless exactly TOTAL nodes, indexes 1 to 4 once each, all name these * tables and hold their own entries of them (pending, or already current): * a node that sees fewer entries (no `$unanimous`) neither activates nor * discards (PR #359 re-review R-1). Then: * - **some node already current** (a split activation): the old set is no * longer whole on every node, so never discard; the nodes still holding * pending parts activate, forward, when THRESHOLD - 1 canaries signed in * this round (so one node can neither block it with a "failed" nor force * it alone). * - **all pending, a canary "failed"** (it came back and did not verify, or * a CVM refused the new parts): discard; each node drops its pending set * (its own volatile only) and the old tables and parts stay whole. * - **all pending, no failure**: activate when at least THRESHOLD canaries * are "ok". * Activating makes each node's pending parts current and only then deletes * the old ones; the key's state gets the new tables and a fresh `mpcCanary`, * and `recovery` is deleted (the token is spent, R-3) with `mpcRefresh` * recording the requester, so the same requester can complete a split * activation. A node that had already activated changes nothing of its own. */
private async commitMpc2Activate(): Promise<void> {
const mine = this.mpc2Activate!;
const comms: any = this.getInterNodeComms() || {};
const entries = Object.keys(comms).map((k) => comms[k]);
const tables = JSON.stringify(mine.tables);
const key: Activity = this.getActivityStreams(this.transactions.$o.key);
const seen: number[] = [];
let ok = 0;
let failed = 0;
let current = 0;
let complete = entries.length === TOTAL;
// One stage made these tables, so every node's receipts name its umid.
const stageUmid = complete && entries[0] && typeof entries[0] === "object" ? entries[0].receiptUmid : null;
for (const e of entries) {
if (!e || typeof e !== "object" || JSON.stringify(e.tables) !== tables || (e.holds !== "pending" && e.holds !== "current") ||
typeof e.partIndex !== "number" || e.partIndex < 1 || e.partIndex > TOTAL || seen.indexOf(e.partIndex) !== -1 ||
!Array.isArray(e.delivered) || e.delivered[0] !== mine.tables[0][e.partIndex - 1] || e.delivered[1] !== mine.tables[1][e.partIndex - 1]) {
complete = false;
break;
}
// A node counts only if its agent's stage receipts for these tables
// verify (step 4): an entry for a node whose agent never received its
// parts makes the round incomplete, so it neither activates nor
// discards. This does NOT authenticate `holds` or `canary` (PR #395
// review M-1, class comment step 6): genuine stage receipts can be
// replayed with forged claims while consensus is unsigned.
if (typeof stageUmid !== "string" || !/^[0-9a-f]{64}$/.test(stageUmid) || e.receiptUmid !== stageUmid ||
!this.mpc2ReceiptsVerify(e.receiptSigs, stageUmid, mine.keyId, mine.network, e.partIndex, mine.tables, mine.operators)) {
complete = false;
break;
}
seen.push(e.partIndex);
if (e.canary === "ok") ok++;
if (e.canary === "failed") failed++;
if (e.holds === "current") current++;
}
// Nothing is decided on fewer than all four nodes' data: no activation,
// and no discard either (PR #359 re-review R-1).
if (!complete) {
this.returnToRemote({activated: false, reason: "not every node holds the new parts"});
return;
}
let activate = false;
if (current > 0) {
// Partly active already (a split activation): the old set is no longer
// whole, so the only safe direction is forward (R-1). Never discard; the
// nodes still holding pending parts activate. One node's word can
// neither block this (a "failed" is ignored here) nor force it: it
// needs THRESHOLD - 1 canaries "ok" in this round, so at least one
// honest node's canary signed under the new parts.
activate = ok >= THRESHOLD - 1;
} else if (failed > 0) {
// All four still hold pending sets (none activated), and a canary came
// back and failed verification: discard, and the old set stays whole.
await this.mpc2DropPending(key, tables);
this.returnToRemote({activated: false, discarded: true, reason: "a canary under the new tables failed"});
return;
} else {
activate = ok >= THRESHOLD;
}
if (!activate) {
this.returnToRemote({activated: false, reason: "too few canaries signed under the new tables"});
return;
}
const state = key.getState() as any;
state.partHashes = [mine.tables[0].slice(), mine.tables[1].slice()];
state.mpcCanary = {at: this.cDate, umid: this.umid};
// The refresh is done, so its repair token is spent (re-review R-3): a
// new redistribute needs a new KeyHealthCheck. Who asked, and for which
// tables, is kept so the same requester can complete a split activation.
if (state.recovery) {
state.mpcRefresh = {at: this.cDate, umid: this.umid, owner: state.recovery.owner, tables: [mine.tables[0].slice(), mine.tables[1].slice()]};
}
delete state.recovery;
key.setState(state);
if (mine.holds === "pending") {
let volatile: any = null;
try {
volatile = await key.getVolatile();
} catch (e) {
volatile = null;
}
const pending = volatile && volatile.pending;
if (pending && JSON.stringify(pending.tables) === tables) {
// The old parts go only now, with the new set complete on all four
// nodes: an old part kept is worth something to whoever collects two
// more of the same epoch.
key.setVolatile({
private: {part: pending.part, part2: pending.part2},
public: {...(volatile.public || {}), hashes: mine.tables[0].slice(), hashes2: mine.tables[1].slice(), publicKey: state.publicKey, pubkey: state.publicKey},
// Kept so this node can show its receipts again if this activation
// turns out split and is retried (it then "holds" as current).
receipts: {umid: pending.umid, tables: [mine.tables[0].slice(), mine.tables[1].slice()], receiptSigs: pending.receiptSigs, operators: pending.operators},
});
}
}
this.returnToRemote({activated: true, partHashes: state.partHashes});
}/** Drops this node's pending set for `tables` (a JSON string), if it has one; nothing else changes. */
private async mpc2DropPending(key: Activity, tables: string): Promise<void> {
let volatile: any = null;
try {
volatile = await key.getVolatile();
} catch (e) {
return;
}
if (volatile && volatile.pending && JSON.stringify(volatile.pending.tables) === tables) {
const kept: any = {};
for (const k of Object.keys(volatile)) {
if (k !== "pending") kept[k] = volatile[k];
}
key.setVolatile(kept);
}
}/** The per-tree switch, read in one place (tests pin it here). */
private mpc2RedistributeEnabled(): boolean {
return MPC2_REDISTRIBUTE_ENABLED;
}/** The per-tree constant, read in one place (tests pin another value here). */
private mpc2HaltContract(): string {
return MPC2_HALT_CONTRACT;
}/** * Throws while Varnir.CryptoTransfer's ledger halt (`mpchalt`) stands (PR * #358 review M2): a redistribute and an activation canary are sessions * with the peer the lockout stops. KeyHealthCheck's rule, read the same way; * blank or unreadable refuses. */
private async assertNoMpcHalt(): Promise<void> {
const haltContract = this.mpc2HaltContract();
if (!/^[0-9a-f]{64}$/.test(haltContract)) {
throw "mpc2: the halt record's contract is not configured on this network";
}
let doc: any;
try {
doc = await this.getAnyStreamReadOnly(`${haltContract}:data`);
} catch (e) {
throw "mpc2: cannot read the ledger halt record";
}
const data = doc && typeof doc === "object" && doc.data && typeof doc.data === "object" ? doc.data : {};
if (data.mpc2Halt !== undefined && data.mpc2Halt !== null) {
throw "mpc2: MPC signing is halted on the ledger (peer lockout)";
}
}