Testnet Mode — switch back to Production in the menuheader when you're done.
VarnirCryptoTransfer extends PostProcessEvent
Send a wallet's native L1 balance (TRX/ETH) to an external address - $entry: "sign" is rewritten to "presign" internally for every network this system runs, so it queues an async sign+broadcast rather than completing inline.
{
"$sigs": {
"<owner identity stream id>": "<base64 signature of $tx, signed with the owner's private key>"
},
"$tx": {
"$contract": "<Varnir.CryptoTransfer's deployed contract id>",
"$namespace": "varnir",
"$entry": "sign",
"$i": {
"owner": {
"$stream": "<owner identity stream id>",
"network": "TRX-NILE",
"token": "#native",
"amount": "<raw integer string, sun/wei - no hex, no decimal point>",
"to": "<L1 recipient address>"
}
},
"$r": {
"wallet": "<the specific wallet stream id to send from>"
}
}
}/**
* Voting round, run on every node. In order:
*
* 1. Social-recovery guard: only `$o.to`, `$o.recipient` and `$o.owner`
* (streams that are only credited) may be recovered or frozen.
* 2. For every entry except `presigned`, `cancel`, `btcbump`, `btccancel`
* and the gateway hold entries (all gateway-signed, no `$i.owner`):
* refuse a `read` key (or stake 9000) and an `offledger` key; hand
* `void` and the owner hold entries to voteVoid / voteHoldOwner; run
* the repeat guard and the spending policy for `transfer` / `sign` /
* `presign` (both skipped for a genuine co-sign confirm); the AFX check;
* then, on an identity with `hasTreasury`, the treasury branch: it
* either checks the proposal named on `$o.approved` and copies its
* terms over the request, or marks the spend as needing approval
* (`requiresTreasury`).
* 3. `sign` is rewritten to `presign`, and the entry's own vote runs.
*
* A spend needing approval resolves early: commit() then raises a
* proposal instead of moving money. An unknown entry is rejected with
* "Unknown entry point"; a non-string error becomes "Runtime Vote Revert".
*
* @returns {Promise<boolean>}
* @memberof VarnirCryptoTransfer
*/ public vote(): Promise<boolean> {
//this.traceUnhandled("vote phase");
return new Promise<boolean>((resolve, reject) => {
// A throw anywhere in voteSteps (most of it runs before the entry try
// below) used to escape an `async` Promise executor: the vote never
// settled and the error became an unhandled rejection. It now settles as
// a refusal. A refusal already given, or a resolve, is not changed:
// a Promise settles once.
this.voteSteps(resolve, reject).catch((error) => {
reject(typeof error === "string" ? error : "Runtime Vote Revert");
this.ActiveLogger.error(
error,
`Rehandled Error - Varnir.CryptoTransfer#Vote - ${this.umid}`
);
});
});
}/**
* Commit round.
*
* When vote() set `requiresTreasury`, nothing moves: a `transfer.multisign`
* proposal stream is written (`request` = `$i.owner`, the recipient for a
* transfer, `proposedBy` = the signing key's hash, `at`, `expiresAt` =
* cDate + PROPOSALLIFETIMEMS), a summary is added to the identity's
* `pendingTreasury`, `treasury-pending` is emitted and the repeat-guard
* record is stored.
*
* Otherwise the entry's own commit runs. After a confirmed proposal
* (`$o.approved`) the proposal is stamped `approved` / `approvedAt` and
* removed from `pendingTreasury`. A non-string error becomes "Runtime
* Commit Revert".
*
* @returns {Promise<any>}
* @memberof VarnirCryptoTransfer
*/ public commit(): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
if (this.requiresTreasury) {
// When this proposal stops being confirmable. Written as an absolute
// instant, not as an age a reader has to add PROPOSALLIFETIMEMS to,
// so "is this still live" is answerable from the record alone - by
// the confirm path here, by the SDK, and by a person reading the
// stream. ISO-8601 because it crosses into JSON and back and has to
// mean the same thing on both sides.
//
// this.cDate is the per-transaction CONSENSUS timestamp, identical on
// every node, so every node computes the SAME expiry and the proposal
// does not desync the cluster. new Date(this.cDate) only READS it.
// NEVER Date.now()/new Date().
const proposalExpiresAt = new Date(
new Date(this.cDate).getTime() + PROPOSALLIFETIMEMS
).toISOString();
const raisedTo = this.transactions.$o?.to;
const raisedToStream = raisedTo?.$stream ?? raisedTo;
const raisedRecipient =
this.transactions.$entry === "transfer" &&
typeof raisedToStream === "string" &&
raisedToStream
? {
// Exactly as named: vote() refused anything but a bare id.
stream: raisedToStream,
...(raisedTo?.wallet
? { wallet: this.filterPrefix(String(raisedTo.wallet)) }
: {}),
...(this.transactions.$i.owner.toAddress !== undefined
? { toAddress: String(this.transactions.$i.owner.toAddress) }
: {}),
}
: null;
// Do we even need to create a document to store the request? Probably then make sure to reference
this.multiSignRequest = this.newActivityStream("transfer.multisign");
this.multiSignRequest.setState({
requiresTreasury: true,
umid: this.umid,
entry: this.transactions.$entry,
request: this.transactions.$i.owner,
// Everything the eventual commit needs about who is credited. An
// on-ledger transfer names its recipient on $o.to, which request
// ($i.owner) does not carry; the confirm restores these from HERE,
// never from the confirming transaction.
...(raisedRecipient ? { recipient: raisedRecipient } : {}),
// Which KEY raised this, not which identity - both halves of a
// propose/confirm pair are signed for the same identity, so this is
// the only thing that can tell a verifier apart from the proposer.
// Read back in vote() to refuse a self-confirmation.
proposedBy: this.signingKeyHash(
this.getActivityStreams(this.transactions.$i.owner)
),
// The proposal stream is the authority on the terms, so the lifetime
// lives here too and not only on the identity's summary below - the
// confirm path reads THIS, and a summary that drifted from it must
// not be able to decide whether a payment may still be released.
at: this.cDate,
expiresAt: proposalExpiresAt,
});
// Prevent someone else from including this?
// We may only reference this not need to pull it in, So that maybe irrelevant as Treasury overrides it all
//this.multiSignRequest.setAuthorities(this.getActivityStreams(this.transactions.$i.owner).getAuthorities());
// Register it on the identity itself so a treasury key can FIND it.
// Streams are only readable by id and nothing indexes them, so
// without this the proposer has to hand the id to its approver out
// of band - which is exactly the step an automated approver cannot
// do. The identity stream is the one document an approver already
// reads (it is where balances live), so putting a summary here makes
// "what is waiting for me" a poll of something they hold rather than
// new infrastructure. Kept to a summary, not a copy of the request:
// the proposal stream remains the authority on the terms, and this
// is a pointer plus enough to decide whether to go and read it.
const proposalOwner = this.getActivityStreams(
this.transactions.$i.owner
);
const proposalOwnerState = proposalOwner.getState();
if (!proposalOwnerState.pendingTreasury) {
proposalOwnerState.pendingTreasury = {};
}
// Drop summaries long past their expiry (pending-treasury-bounds).
this.prunePendingTreasury(proposalOwnerState);
proposalOwnerState.pendingTreasury[this.multiSignRequest.getId()] = {
umid: this.umid,
network: this.transactions.$i.owner.network,
token: this.transactions.$i.owner.token,
amount: this.transactions.$i.owner.amount,
to: this.transactions.$i.owner.to,
// The raising key, so the per-key cap can count it (pending-treasury-bounds).
proposedBy: this.signingKeyHash(proposalOwner),
at: this.cDate,
// Carried on the summary as well so a listing can say "expired"
// rather than "pending" without fetching every proposal stream.
// Nothing runs on a timer: expiry makes it unusable, voiding clears
// it, and a later write prunes it PENDINGTREASURYGRACEMS after expiry.
expiresAt: proposalExpiresAt,
};
proposalOwner.setState(proposalOwnerState);
// Same payload again as an event, so a gateway can push this to a
// subscriber rather than every approver polling. Emitted now even
// though nothing consumes it yet: it costs one line here and means
// the transport can be chosen later without touching a contract that
// moves money a second time.
this.event.emit("treasury-pending", {
identity: proposalOwner.getId(),
proposal: this.multiSignRequest.getId(),
umid: this.umid,
network: this.transactions.$i.owner.network,
token: this.transactions.$i.owner.token,
amount: this.transactions.$i.owner.amount,
to: this.transactions.$i.owner.to,
expiresAt: proposalExpiresAt,
});
// ---- repeat-guard:raise:begin ----
// A raised proposal counts as the payment for the guard, so an
// identical re-raise inside the window is refused in vote(). Partial
// setState: Activity.setState merges top-level keys, so this cannot
// clobber the pendingTreasury write above (testnet) or anything else.
if (this.repeatRecord) {
const repeatOwner = this.getActivityStreams(this.transactions.$i.owner);
const repeatState = repeatOwner.getState();
this.withRecentPayment(repeatState);
repeatOwner.setState({recentPayments: repeatState.recentPayments});
}
// ---- repeat-guard:raise:end ----
return resolve(true);
} else {
try {
let commitProxy;
switch (this.transactions.$entry) {
case "transfer":
commitProxy = this.commitGasFree();
break;
//case "sign":
// this.setTimeout(60000);
// commitProxy = this.commitSign();
// break;
case "presign":
commitProxy = this.commitPreSign();
break;
case "presigned":
this.setTimeout(60000);
commitProxy = this.commitPreSigned();
break;
case "cancel":
this.setTimeout(60000);
commitProxy = this.commitCancel();
break;
case "btcbump":
case "btccancel":
commitProxy = this.btcCommitReplace();
break;
case "btcmove":
commitProxy = this.btcCommitMove();
break;
case "sweeparm":
commitProxy = this.commitSweepArm();
break;
case "mod":
commitProxy = this.commitMod();
break;
case "mpchalt":
commitProxy = this.commitMpcHalt();
break;
case "tronmpcarm":
commitProxy = this.commitTronMpcArm();
break;
case "recordlanded":
commitProxy = this.commitRecordLanded();
break;
case "void":
commitProxy = this.commitVoid();
break;
case "tenantpayout":
commitProxy = this.commitTenantPayout();
break;
case "tenantsettle":
commitProxy = this.commitTenantSettle();
break;
// >>> tenant-pays
case "tenantwdsettle":
commitProxy = this.commitTenantWdSettle();
break;
case "tenantwdrelease":
commitProxy = this.commitTenantWdRelease();
break;
// <<< tenant-pays
case "holdnotify":
case "holdrelease":
case "holdcancel":
case "holdconfig":
case "holdlearn":
commitProxy = this.commitHold();
break;
default:
// Leave commitProxy as null
}
if (commitProxy) {
let commitResults = await commitProxy;
if (this.approved) {
// Mark approved as completed
const data = this.approved.getState();
data.approved = this.umid;
data.approvedAt = this.cDate;
this.approved.setState(data);
// And drop it from the identity's pending list, so that list
// stays the size of what is actually outstanding rather than
// growing forever on the hottest document in the system.
//
// Deliberately only when this.ownerState is already loaded -
// which it is on this path, since a confirmation runs the
// proposer's own stored entry and forcedNetworks rewrites that
// to presign for every network Varnir has, so commitPreSign
// has just populated it. Re-reading the owner here instead
// would hand back the PRE-commit state, and writing that back
// would silently undo the balance debit commitPreSign just
// made. A pending entry left behind is stale but harmless -
// the proposal it points at reads back as approved.
if (this.owner && this.ownerState?.pendingTreasury) {
delete this.ownerState.pendingTreasury[this.approved.getId()];
this.prunePendingTreasury(this.ownerState);
this.owner.setState(this.ownerState);
}
}
return resolve(commitResults);
} else {
return reject("Unknown entry point");
}
} catch (error) {
this.ActiveLogger.error(
error,
`Rehandled Error - Varnir.CryptoTransfer#Commit - ${this.umid}`
);
return reject(
typeof error === "string" ? error : "Runtime Commit Revert"
);
}
}
});
} 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;
} private creditsDefaults(): any {
const three = (instant: number, standard: number, economy: number) => ({instant, standard, economy});
const tron = {native: three(30, 20, 10), token: three(600, 400, 240)};
const bsc = {native: three(30, 20, 10), token: three(40, 20, 10)};
const eth = {native: three(30, 20, 10), token: {live: true}};
return {
periodMs: 30 * 24 * 60 * 60 * 1000,
renewWindowMs: 7 * 24 * 60 * 60 * 1000,
linkLimits: {trader: 5},
weights: {
networks: {eth, sep: eth, trx: tron, niles: tron, shasta: tron, bnb: bsc, tbnb: bsc},
live: {
factorsPct: three(250, 180, 130),
minimums: three(300, 200, 120),
creditMicroUsd: 6700,
gasMicroUsd: {eth: 1000000, sep: 1000000},
},
},
};
} private creditsSpeed(speed: any): string | null {
if (speed === undefined || speed === null) return "economy";
return speed === "instant" || speed === "standard" || speed === "economy" ? speed : null;
} private creditsIsCount(n: any, max: number): boolean {
return typeof n === "number" && Number.isInteger(n) && n >= 0 && n <= max;
} private creditsWeight(weights: any, network: string, assetClass: string, speed: string): number | string {
// Not named `net` - the engine's contract sandbox refuses that exact
// identifier ("Security Violation: Unauthorized identifier 'net'",
// confirmed live against a local deploy), evidently blocklisted after
// Node's core `net` module regardless of it being a plain local const.
const netCode = String(network).toLowerCase();
const missing = `No credit weight for ${assetClass} withdrawals on ${network}`;
const nets = weights && weights.networks ? weights.networks : {};
const entry = nets[netCode] ? nets[netCode][assetClass] : undefined;
if (!entry || ["instant", "standard", "economy"].indexOf(speed) === -1) return missing;
if (entry.live === true) {
const live = weights.live || {};
const gas = live.gasMicroUsd ? live.gasMicroUsd[netCode] : undefined;
const factor = live.factorsPct ? live.factorsPct[speed] : undefined;
const minimum = live.minimums ? live.minimums[speed] : undefined;
const unit = live.creditMicroUsd;
if (
!this.creditsIsCount(gas, 1000000000) ||
!this.creditsIsCount(factor, 10000) ||
!this.creditsIsCount(minimum, 1000000) ||
!this.creditsIsCount(unit, 1000000000) ||
unit === 0
) {
return `No live gas reading for ${network}`;
}
const numerator = gas * factor;
const denominator = 100 * unit;
return Math.max(minimum, Math.floor((numerator + denominator - 1) / denominator));
}
const w = entry[speed];
return this.creditsIsCount(w, 1000000) && w > 0 ? w : missing;
} private creditsWeightsRefusal(next: any, prev: any): string | null {
const speeds = ["instant", "standard", "economy"];
const maxStep = 2;
// Not `path` - the engine's contract sandbox refuses that exact
// identifier too (see creditsWeight's own note); it blocks a plain
// parameter name the same as a local const.
const step = (fieldPath: string, now: any, before: any, max: number): string | null => {
if (!this.creditsIsCount(now, max) || now === 0) return `Weights: ${fieldPath} must be a positive integer up to ${max}`;
if (this.creditsIsCount(before, max) && before > 0 && (now > before * maxStep || now * maxStep < before)) {
return `Weights: ${fieldPath} ${before} -> ${now} moves more than x${maxStep} in one update`;
}
return null;
};
if (!next || typeof next !== "object" || !next.networks || typeof next.networks !== "object") {
return "Weights: networks required";
}
const old = prev && typeof prev === "object" ? prev : {};
const oldNets = old.networks && typeof old.networks === "object" ? old.networks : {};
for (const name of Object.keys(oldNets)) {
if (!next.networks[name]) return `Weights: ${name} cannot be removed`;
}
const liveNets: string[] = [];
for (const name of Object.keys(next.networks)) {
if (!/^[a-z0-9-]{2,16}$/.test(name)) return `Weights: network ${name} must be a lowercase canonical code`;
// Not `net` - see creditsWeight's own note on the sandbox's blocklist.
const netEntry = next.networks[name];
for (const cls of ["native", "token"]) {
const e = netEntry && netEntry[cls];
if (!e || typeof e !== "object") return `Weights: ${name}.${cls} required`;
if (e.live === true) {
if (cls === "native") return `Weights: ${name}.native cannot be live-priced`;
liveNets.push(name);
continue;
}
const was = oldNets[name] && oldNets[name][cls] && oldNets[name][cls].live !== true ? oldNets[name][cls] : {};
for (const s of speeds) {
const r = step(`${name}.${cls}.${s}`, e[s], was[s], 1000000);
if (r) return r;
}
}
}
// A live block is validated whenever it is PRESENT, not only when a
// network is currently live-priced - otherwise a caller can stash an
// unvalidated (or junk) live block while every network is fixed, and it
// becomes the unbounded "before" the next time a network switches live.
if (liveNets.length || (next.live !== undefined && next.live !== null)) {
const live = next.live;
const oldLive = old.live && typeof old.live === "object" ? old.live : {};
if (!live || typeof live !== "object") return "Weights: live pricing block required";
for (const part of ["factorsPct", "minimums"]) {
if (!live[part] || typeof live[part] !== "object") return `Weights: live.${part} required`;
for (const s of speeds) {
const r = step(`live.${part}.${s}`, live[part][s], oldLive[part] ? oldLive[part][s] : undefined, part === "factorsPct" ? 10000 : 1000000);
if (r) return r;
}
}
const unitRefusal = step("live.creditMicroUsd", live.creditMicroUsd, oldLive.creditMicroUsd, 1000000000);
if (unitRefusal) return unitRefusal;
for (const name of liveNets) {
const gas = live.gasMicroUsd ? live.gasMicroUsd[name] : undefined;
const was = oldLive.gasMicroUsd ? oldLive.gasMicroUsd[name] : undefined;
const r = step(`live.gasMicroUsd.${name}`, gas, was, 1000000000);
if (r) return r;
}
}
// The raw per-field checks above miss a class switching live<->fixed (the
// "was"/"before" resets to {} across the switch, so the step bound never
// applies) and miss several raw fields moving together within their own
// x2 bounds but compounding past x2 on the computed price. Close both:
// bound the EFFECTIVE weight too, for every network/class/speed this
// update and the prior one can both price.
for (const name of Object.keys(oldNets)) {
for (const cls of ["native", "token"]) {
for (const s of speeds) {
const before = this.creditsWeight(old, name, cls, s);
if (typeof before !== "number") continue; // no valid prior price to bound against
const after = this.creditsWeight(next, name, cls, s);
if (typeof after !== "number") continue; // already refused above; defensive only
if (after > before * maxStep || after * maxStep < before) {
return `Weights: ${name}.${cls}.${s} effective weight ${before} -> ${after} moves more than x${maxStep} in one update`;
}
}
}
}
return null;
} private creditsFreshPlan(tier: string, startMs: number, cfg: any, terms: any): any {
const d = this.creditsDefaults();
const limits = (cfg && cfg.linkLimits) || d.linkLimits;
// A tier adds no credits (credits-only, 2026-10-17): every tier but
// Enterprise includes 0 and rolls over 0, whatever a stale config holds.
// Enterprise keeps its own admin-assigned terms.
const enterprise = tier === "enterprise";
return {
tier,
periodStart: startMs,
periodEnd: startMs + d.periodMs,
included: enterprise ? Number(terms.included) : 0,
includedUsed: 0,
rollover: 0,
rolloverUsed: 0,
rolloverExpiresAt: null,
overageUsed: 0,
overageCap: null,
rolloverCap: enterprise ? Number(terms.rolloverCap) : 0,
linkLimit: enterprise ? Number(terms.linkLimit) : Number(limits[tier] || 0),
linked: [],
autoRenew: false,
renewal: null,
paidUmid: null,
};
} private creditsEffectivePlan(record: any, nowMs: number, cfg: any): any {
const periodMs = this.creditsDefaults().periodMs;
const tiers = ["free", "lite", "hobbyist", "trader", "enterprise"];
if (
!record ||
typeof record !== "object" ||
tiers.indexOf(record.tier) === -1 ||
typeof record.periodEnd !== "number" ||
typeof record.periodStart !== "number"
) {
return this.creditsFreshPlan("free", nowMs, cfg, null);
}
let plan = JSON.parse(JSON.stringify(record));
for (let guard = 0; nowMs >= plan.periodEnd && guard < 2000; guard++) {
const start = plan.periodEnd;
const unused = Math.max(0, Number(plan.included || 0) - Number(plan.includedUsed || 0));
const keepCap = plan.overageCap === undefined ? null : plan.overageCap;
let next: any;
if (plan.tier === "free") {
const skipped = Math.floor((nowMs - start) / periodMs);
next = this.creditsFreshPlan("free", start + skipped * periodMs, cfg, null);
} else if (plan.tier === "enterprise") {
const skipped = Math.floor((nowMs - start) / periodMs);
next = this.creditsFreshPlan("enterprise", start + skipped * periodMs, cfg, plan);
// An idle period's unused allowance is the whole allowance.
next.rollover = Math.min(skipped > 0 ? next.included : unused, next.rolloverCap);
next.linked = (plan.linked || []).slice(0, next.linkLimit);
} else if (plan.renewal && ["lite", "hobbyist", "trader"].indexOf(plan.renewal.tier) !== -1) {
next = this.creditsFreshPlan(plan.renewal.tier, start, cfg, null);
next.rollover = Math.min(unused, next.rolloverCap);
next.autoRenew = plan.autoRenew === true;
// The price the owner agreed to auto-renew at travels with the mandate.
next.agreedPrice = next.autoRenew && plan.agreedPrice ? plan.agreedPrice : null;
next.linked = (plan.linked || []).slice(0, next.linkLimit);
next.paidUmid = plan.renewal.umid || null;
} else {
next = this.creditsFreshPlan("free", start, cfg, null);
}
next.overageCap = keepCap;
next.rolloverExpiresAt = next.rollover > 0 ? next.periodEnd : null;
plan = next;
}
return plan;
}/** The identity's credit balance: `state.credits.balance`, or 0 when absent. */
private creditsBalance(state: any): number {
return state && state.credits && typeof state.credits.balance === "number" ? state.credits.balance : 0;
}/** The monthly allowance spent so far this period: `state.credits.allowance.used`, or 0 when absent. A caller compares it before and after a charge or refund to tell whether the allowance moved (credits-changed). */
private creditsAllowanceUsed(state: any): number {
const a = state && state.credits ? state.credits.allowance : null;
return a && typeof a === "object" && Number.isInteger(a.used) ? a.used : 0;
}/** * Moves the balance by `delta` (whole credits; negative spends). Returns a * refusal, or null after mutating `state.credits`: the new balance, and the * move at the front of `recent` (newest first, at most 50), carrying * `allowance` when the monthly allowance moved too (creditsTakeCharge, * creditsRefundCharge). The balance never goes below zero. A refusal * leaves `state` untouched. */
private creditsMove(state: any, delta: number, reason: CreditReason, umid: string, at: number, allowance?: number): string | null {
const CREDITS_RECENT_MAX = 50;
if (!Number.isInteger(delta)) return "Credits - amount must be a whole number";
const balance = this.creditsBalance(state);
if (balance + delta < 0) return `Credits - not enough credits: this needs ${-delta} and ${balance} are available`;
const credits = state.credits && typeof state.credits === "object" ? state.credits : {};
const next = balance + delta;
const recent = Array.isArray(credits.recent) ? credits.recent : [];
const entry: any = { at, delta, balance: next, reason, umid };
// The monthly allowance's part of a charge (negative) or refund (positive).
if (typeof allowance === "number" && Number.isInteger(allowance) && allowance !== 0) entry.allowance = allowance;
credits.balance = next;
credits.recent = [entry].concat(recent).slice(0, CREDITS_RECENT_MAX);
state.credits = credits;
return null;
}/** `listPrice` less the tier's discount (`cfg.discountsPct[tier]`, 0 when absent), rounded in the user's favour. */
private creditsDiscounted(listPrice: number, tier: string, cfg: any): number {
const pcts = cfg && cfg.discountsPct ? cfg.discountsPct : {};
const pct = typeof pcts[tier] === "number" ? pcts[tier] : 0;
return listPrice - Math.floor((listPrice * pct) / 100);
}/** * The anti-abuse unlock shared by Free's free payout and the monthly * allowance: either 7 days of consensus time have passed since the * identity's first wallet (`state.credits.firstWalletAt`), or its largest * deposit into some stablecoin partition listed in * `cfg.stablecoins[network][token]` (decimals) reached 10 whole units. * Native coins never unlock it. */
private creditsUnlocked(state: any, cfg: any, nowMs: number): boolean {
const FREE_PAYOUT_UNLOCK_MS = 7 * 24 * 60 * 60 * 1000;
const FREE_PAYOUT_MIN_UNITS = 10;
const credits = state && state.credits && typeof state.credits === "object" ? state.credits : {};
if (typeof credits.firstWalletAt === "number" && nowMs >= credits.firstWalletAt + FREE_PAYOUT_UNLOCK_MS) return true;
const coins = cfg && cfg.stablecoins && typeof cfg.stablecoins === "object" ? cfg.stablecoins : {};
const deposits = credits.maxDeposit && typeof credits.maxDeposit === "object" ? credits.maxDeposit : {};
for (const netCode of Object.keys(coins)) {
const tokens = coins[netCode] && typeof coins[netCode] === "object" ? coins[netCode] : {};
for (const token of Object.keys(tokens)) {
const decimals = tokens[token];
const seen = deposits[netCode] ? deposits[netCode][token] : undefined;
if (!Number.isInteger(decimals) || decimals < 0 || decimals > 36) continue;
if (typeof seen !== "string" || !/^[0-9]{1,80}$/.test(seen)) continue;
if (BigInt(seen) >= BigInt(FREE_PAYOUT_MIN_UNITS) * BigInt(10) ** BigInt(decimals)) return true;
}
}
return false;
}/** `cfg.freePayoutsPerMonth`: 1 when absent (the original Free payout), else a whole number; anything else is 0. */
private creditsFreePayoutsPerMonth(cfg: any): number {
const n = cfg ? cfg.freePayoutsPerMonth : undefined;
if (n === undefined || n === null) return 1;
return Number.isInteger(n) && n > 0 ? n : 0;
}/** The free-payout month marker while it still applies at `nowMs`, as `{start, end, used}`, else null. */ private creditsFreePayoutMonth(state: any, nowMs: number): { start: number; end: number; used: number }/**
* Free's free payouts this plan period (any network or token). Open when
* the effective tier is Free, `cfg.freePayoutsPerMonth` (1 when absent) are
* not used up this month (`state.credits.freePayoutMonth`, the plan month
* they were last used in, `{start, end, used}`; a marker without `used`
* counts as 1; it applies while `nowMs` is before its `end`), and the
* identity is unlocked (creditsUnlocked).
*/ private creditsFreePayoutAvailable(state: any, plan: any, cfg: any, nowMs: number): boolean {
if (!plan || plan.tier !== "free" || typeof plan.periodStart !== "number") return false;
const perMonth = this.creditsFreePayoutsPerMonth(cfg);
if (perMonth === 0) return false;
const month = this.creditsFreePayoutMonth(state, nowMs);
if (month && month.used >= perMonth) return false;
return this.creditsUnlocked(state, cfg, nowMs);
}/** * Takes a split charge (creditsSplitCharge) from `state`: the balance part * as one `reason` move recording the allowance part, and the allowance * part added to `state.credits.allowance` for its period (a new period * starts from 0 used). Returns a refusal (the balance moved since vote: a * broken invariant) or null. */
private creditsTakeCharge(state: any, split: any, reason: CreditReason, umid: string, at: number): string | null {
const refusal = this.creditsMove(state, -split.fromBalance, reason, umid, at, -split.fromAllowance);
if (refusal) return refusal;
if (split.fromAllowance > 0) {
const a = state.credits.allowance;
const used = a && typeof a === "object" && a.period === split.allowancePeriod && Number.isInteger(a.used) ? a.used : 0;
state.credits.allowance = { period: split.allowancePeriod, end: split.allowanceEnd, used: used + split.fromAllowance };
}
return null;
}/** * Records a used free payout: `state.credits.freePayoutMonth` is the plan * month it was taken in, with `used` counting the month's free payouts. An * identity with no plan record gets a month that starts now * (creditsEffectivePlan's fresh Free plan), so this marker - not the plan * record, which belongs to Varnir.Plans - keeps the count per month. */
private creditsUseFreePayout(state: any, charge: any): void {
const credits = state.credits && typeof state.credits === "object" ? state.credits : {};
const month = credits.freePayoutMonth;
const same = month && typeof month === "object" && month.start === charge.periodStart;
const used = same ? (Number.isInteger(month.used) && month.used >= 0 ? month.used : 1) : 0;
credits.freePayoutMonth = { start: charge.periodStart, end: charge.periodEnd, used: used + 1 };
state.credits = credits;
}/** * Gives back a withdrawal charge whose payout did not happen, where it came * from. A used free payout comes back only while the marker is still the * month it was taken in (a later month has its own). The charge's * `fromAllowance` goes back to the allowance only while * `state.credits.allowance` is still the period it was taken from * (`allowancePeriod`); otherwise it lapses. The rest (`fromBalance`, or * the whole `credits` on a charge with no split) comes back as one * "refund" move. Returns the credits given back to the balance. The caller * guards against refunding twice. */
private creditsRefundCharge(state: any, charge: any, umid: string, at: number): number {
if (!charge || typeof charge !== "object") return 0;
if (charge.freePayout === true) {
const credits = state && state.credits && typeof state.credits === "object" ? state.credits : null;
const month = credits ? credits.freePayoutMonth : null;
if (month && typeof month === "object" && month.start === charge.periodStart) {
const used = Number.isInteger(month.used) && month.used >= 0 ? month.used : 1;
credits.freePayoutMonth = used > 1 ? { start: month.start, end: month.end, used: used - 1 } : null;
}
return 0;
}
const n = charge.credits;
if (!Number.isInteger(n) || n <= 0) return 0;
const fromAllowance = Number.isInteger(charge.fromAllowance) && charge.fromAllowance > 0 && charge.fromAllowance <= n ? charge.fromAllowance : 0;
const fromBalance = n - fromAllowance;
let restored = 0;
const credits = state && state.credits && typeof state.credits === "object" ? state.credits : null;
const a = credits ? credits.allowance : null;
if (fromAllowance > 0 && a && typeof a === "object" && a.period === charge.allowancePeriod && Number.isInteger(a.used)) {
restored = Math.min(fromAllowance, a.used);
a.used -= restored;
}
if (fromBalance === 0 && restored === 0) return 0;
return this.creditsMove(state, fromBalance, "refund", umid, at, restored) === null ? fromBalance : 0;
}/**
* Returns `[{id, partitions: layer2}]` for the stream on `$o.wallet`.
* Nothing in this contract calls it, and no code in this repository does.
*
* @returns {Promise<any>}
* @memberof VarnirCryptoTransfer
*/ public readUsersWalletBalances(): Promise<any> {
return new Promise<any>(async (r) => {
const walletStream = this.getActivityStreams(this.transactions.$o.wallet);
const data = walletStream.getState();
const output = [];
// Balances are now on the user wallet
output.push({
id: walletStream.getId(),
partitions: data.layer2,
});
r(output);
});
}/**
* Makes sure the passed object has the relevant layer 2 structure.
*
* Used to key by a `partitions[id]` dict where `id` was always the
* document's own stream id (never a different party's) - genuinely
* redundant, confirmed by reading every call site in this file, so
* simplified to a single `balance` field instead of a one-entry dict.
*
* @private
* @param {*} obj
* @memberof VarnirCryptoTransfer
*/ private hasValidSchemaObject(obj: any) {
const defaultBalance = this.getBN(0);
// Make sure layer 2 object exists on this wallet
// (Must be a better way to do this, but this will always work and be dynamic)
if (!obj.layer2) {
obj.layer2 = {};
}
// Ensure that this network has been setup for layer 2 operations (+ token)
if (!obj.layer2[this.layer2TDetails.network]) {
obj.layer2[this.layer2TDetails.network] = {
[this.layer2TDetails.token]: { balance: defaultBalance },
};
}
// Double check token as it maybe a new token on an old network
if (!obj.layer2[this.layer2TDetails.network][this.layer2TDetails.token]) {
obj.layer2[this.layer2TDetails.network][this.layer2TDetails.token] = { balance: defaultBalance };
}
}/**
* Gets the layer 2 balance for the current network/token on this stream.
*
* @private
* @param {*} obj
* @returns
* @memberof VarnirCryptoTransfer
*/ private getL2Balance(obj: any) {
return obj.layer2[this.layer2TDetails.network][this.layer2TDetails.token].balance;
}/**
* Sets the layer 2 balance for the current network/token on this stream.
*
* @private
* @param {*} obj
* @param {BN} value
* @memberof VarnirCryptoTransfer
*/ private setL2Balance(obj: any, value: BN) {
obj.layer2[this.layer2TDetails.network][this.layer2TDetails.token].balance = value;
}/**
* Convert to a big number (native BigInt-backed, see the BN class above)
*
* @private
* @param {*} [data]
* @returns {BN}
* @memberof VarnirCryptoTransfer
*/ private getBN(data?: any): BN {
if (data) {
if (data.hex) {
return BN.from(data.hex);
} else {
return BN.from(data);
}
} else {
return BN.from("0x00");
}
}/**
* The amount a transfer or withdrawal moves: present, a whole number, and
* greater than 0. Anything else (missing, "", non-numeric, fractional, zero,
* negative) is refused before it can touch a balance or a spend counter.
*
* @private
* @param {*} raw
* @returns {BN}
* @memberof VarnirCryptoTransfer
*/ private requirePositiveAmount(raw: any): BN {
let amount: BN | undefined;
if (raw !== undefined && raw !== null && raw !== "") {
try {
amount = this.getBN(raw);
} catch (e) {
amount = undefined;
}
}
if (!amount || !amount.gt(0)) {
throw "Transfer Issue : amount must be a number greater than 0";
}
return amount;
}/**
* `transfer` vote: an L2 transfer from `$i.owner` to the identity on
* `$o.to`, for `$i.owner.network` / `token` (default `#native`).
*
* Refuses `$i.owner.to` (the recipient must be an output). When the payer
* named an address (`$o.to.wallet`, optional `$i.owner.toAddress`) the
* wallet must exist, be owned by the recipient and be on this network, and
* `toAddress` must be its address; a `toAddress` without a wallet is
* refused. The amount must be a positive whole number no larger than the
* sender's balance. Then decides the new-recipient hold (holdDecideL2).
*
* @private
* @returns {Promise<boolean>}
* @memberof VarnirCryptoTransfer
*/ private async voteGasFree(): Promise<any> {
// Check we have a receipent
if (this.transactions.$i.owner.to) {
//throw new Error(
throw "to should now be defined as $o";
//);
}
// Balance now sits on the owner!
this.owner = this.getActivityStreams(this.transactions.$i.owner);
this.ownerState = this.owner.getState();
// Set the cache for paritions
this.layer2TDetails.network = this.transactions.$i.owner.network;
this.layer2TDetails.token = this.transactions.$i.owner.token || "#native";
// The wallet this transfer pays through, when the payer named an address
// rather than an identity. The ledger - not the payer's SDK or a gateway -
// decides who that address belongs to: the wallet's on-ledger owner must
// be the identity being credited, so a stale or wrong lookup fails here
// instead of paying the wrong identity.
const namedWallet = this.transactions.$o?.to?.wallet;
// An address only means something once the ledger has tied it to a
// wallet the recipient owns. Unbound, it would ride out on the
// l2-transfer event and could be counted against someone else's invoice.
if (this.transactions.$i.owner.toAddress !== undefined && !namedWallet) {
throw "Recipient address requires a wallet";
}
if (namedWallet) {
const wallet: any = await this.getAnyStreamReadOnly(this.filterPrefix(namedWallet));
if (!wallet || !wallet._id) {
throw "Recipient wallet not found";
}
const recipientId = this.filterPrefix(this.transactions.$o.to.$stream ?? this.transactions.$o.to);
if (!wallet.owner || wallet.owner !== recipientId) {
throw "Recipient wallet is not owned by the recipient";
}
if (this.canonicalNetwork(String(wallet.network ?? "")) !== this.canonicalNetwork(String(this.layer2TDetails.network))) {
throw "Recipient wallet is on another network";
}
const paid = this.transactions.$i.owner.toAddress;
if (paid !== undefined && !this.sameL1Address(String(paid), String(wallet.address ?? ""))) {
throw "Recipient address does not match the wallet";
}
}
// Check for L2 object exists
this.hasValidSchemaObject(this.ownerState);
// Check balance with what they want to send
const senderBalance = this.getBN(this.getL2Balance(this.ownerState));
// We need to manage amount to send + fee
let totalNeededToSend = this.requirePositiveAmount(this.transactions.$i.owner.amount);
// No Varnir fee on an on-ledger transfer, native or token (credit-only
// model): the recipient gets exactly `amount` and no fee stream is written.
this.varnirFee = this.getBN();
// A tenant-tagged transfer also pays the tenant's fee, in the same asset, on top of `amount`.
this.tenantPrep = this.tenantPrepare("transfer", this.owner.getId(), String(totalNeededToSend));
if (this.tenantPrep) {
this.varnirFee = this.getBN(this.tenantPrep.fee);
totalNeededToSend = totalNeededToSend.add(this.varnirFee);
// >>> tenant-pays
// Stage D: a transfer is a normal op (O1): refused here when its shard's float cannot pay its price.
this.tenantFloat = this.tenantFloatPlan(this.tenantPrep, false);
// <<< tenant-pays
}
if (totalNeededToSend.lt(0)) {
throw "Transfer Issue : Has to be greater than 0";
}
// Now Check the balance is enough
if (senderBalance.lt(totalNeededToSend)) {
throw `Part-Balance to low : ${senderBalance} < ${totalNeededToSend}`;
}
// New-recipient hold (design §2b): the first payment to an identity this
// sender has never paid is escrowed in commitGasFree, not credited.
this.holdDecideL2(
this.filterPrefix(String(this.transactions.$o?.to?.$stream ?? this.transactions.$o?.to ?? ""))
);
//return {leader:true};
return true;
}/**
* `transfer` commit: debits the sender and credits `$o.to` by `amount`
* (a self-send changes no balance). A held transfer goes to
* commitHeldTransfer instead. The repeat-guard record and the agent spend
* counter ride the sender's balance write. Emits `l2-transfer` and returns
* both identities' `layer2`.
*
* @returns {Promise<any>}
* @memberof VarnirCryptoTransfer
*/ public async commitGasFree(): Promise<any> {
const recipient = this.getActivityStreams(this.transactions.$o.to);
const recipentState = recipient.getState();
this.hasValidSchemaObject(recipentState);
//If Self send is true, We only need to minus fees (transfer and deposits)
const selfSend = recipient.getId() === this.owner.getId();
// Held (design §2b): debit the sender, escrow in a new l2.hold stream,
// and leave the recipient untouched until the hold is released.
if (this.holdPending && !selfSend) {
return this.commitHeldTransfer(recipient);
}
let selfSendFees = this.getBN();
// Get Balances
let senderBalance = this.getBN(this.getL2Balance(this.ownerState));
let receiverBalance = this.getBN(this.getL2Balance(recipentState) || 0);
// This is the sender their varnirFee is for sending
if(!selfSend) {
this.setL2Balance(
this.ownerState,
senderBalance.sub(this.varnirFee.add(this.transactions.$i.owner.amount))
);
}else{
selfSendFees = this.varnirFee.add(selfSendFees);
}
const tmpAmount = this.getBN(this.transactions.$i.owner.amount);
// The tenant's fee (zero for the hub) accrues on the shard the tenant signed.
if (this.tenantPrep) this.tenantApply(this.tenantPrep, `${this.layer2TDetails.network}:${this.layer2TDetails.token}`);
// >>> tenant-pays
if (this.tenantPrep) this.tenantFloatApply(this.tenantFloat, this.tenantPrep);
// <<< tenant-pays
// No Varnir fee on the ledger: the recipient gets exactly `amount`.
if (!selfSend) {
this.setL2Balance(recipentState, receiverBalance.add(tmpAmount));
}
// Increment the agent spend counter (no-op for an ungoverned key) in the
// SAME setState as the balance debit (design §4.4). Placed before the
// branch so whichever setState below runs persists it with the balance.
this.withRecentPayment(this.ownerState);
this.bumpAgentUsage();
if(!selfSend) {
this.owner.setState(this.ownerState);
recipient.setState(recipentState);
}else{
// Sending to self just remove the fees as one. Nothing else to "move"
this.setL2Balance(this.ownerState, senderBalance.sub(selfSendFees));
this.owner.setState(this.ownerState);
}
// Lets minigate's own SSE listener push this into the scanner's
// transaction history - see apps/minigate/src/index.ts and the
// wallet-assigned event this mirrors (apps/contracts/testnet/Varnir.AssignOwner.ts).
this.event.emit('l2-transfer', {
umid: this.umid,
from: this.owner.getId(),
to: recipient.getId(),
network: this.layer2TDetails.network,
token: this.layer2TDetails.token,
amount: this.transactions.$i.owner.amount,
fee: this.varnirFee.toString(),
selfSend,
...(this.tenantPrep ? {tenant: this.tenantPrep.tenantId} : {}),
when: this.cDate,
...(this.transactions.$o?.to?.wallet ? {wallet: this.filterPrefix(this.transactions.$o.to.wallet)} : {}),
// Only emitted when a wallet was named - and therefore verified above.
...(this.transactions.$o?.to?.wallet && this.transactions.$i.owner.toAddress !== undefined ? {toAddress: String(this.transactions.$i.owner.toAddress)} : {}),
});
let remoteResponse = [
{
id: recipient.getId(),
partitions: recipentState.layer2,
},
{
id: this.owner.getId(),
partitions: this.ownerState.layer2,
},
];
if (remoteResponse) {
this.returnToRemote(remoteResponse);
}
return true;
}/**
* `presign` vote: an L1 withdrawal from `$i.owner`'s balance (a `sign`
* arrives here rewritten).
*
* The amount must be a positive whole number. The gas hold comes from
* trusted inputs only: computeGasHold, or btcPreSignHold on Bitcoin. A
* native send is not delegated and needs `amount + hold`; a token send is
* delegated (Varnir fronts the gas) and needs `amount`. Caches the payload
* (`$i.owner.signtx`, else `$i.owner`) and the optional `$r.wallet` for
* commitPreSign, then decides the new-recipient hold (holdDecideL1).
*
* @private
* @returns {Promise<boolean>}
* @memberof VarnirCryptoTransfer
*/ private async votePreSign(): Promise<boolean> {
// Partial Copy of voteGasFree (TODO : reduce code)
// Balance now sits on the owner!
this.owner = this.getActivityStreams(this.transactions.$i.owner);
this.ownerState = this.owner.getState();
// Set the cache for paritions
this.layer2TDetails.network = this.transactions.$i.owner.network;
this.layer2TDetails.token = this.transactions.$i.owner.token || "#native";
// Check for L2 object exists
this.hasValidSchemaObject(this.ownerState);
// Check balance with what they want to send
const senderBalance = this.getBN(this.getL2Balance(this.ownerState));
// We need to manage amount to send + fee. The amount itself must be
// positive: a native send adds the hold on top, so a check on the sum alone
// would let an amount in [-hold, 0) through, and commitPreSign would then
// walk a governed key's agentUsage.spent DOWN below its periodCap.
let totalNeededToSend = this.requirePositiveAmount(this.transactions.$i.owner.amount);
// Delegation is decided HERE, by the ledger, from the asset alone (RV1):
// a native send pays its own gas; a token send is always delegated -
// Varnir fronts the gas, whatever the sender's native balance. No Varnir
// fee is taken on either (credit-only model).
//
// $i.owner.minNative / $i.owner.delegated / metadata.feesEstimate are still
// accepted for old callers and deliberately IGNORED. minNative "0" used to
// make any balance - even zero - non-delegated, leaving the gas to a
// native balance that could not pay it (B5).
//
// The hold comes from trusted inputs only (constants, or the owner's own
// `mod` overrides) and is recorded on every send: debited for a native
// send, and for a token send kept as the price/limit envelope that caps
// what the pool wallet may burn on Varnir's behalf.
// Bitcoin sizes its hold from the speed's fee-rate cap and the recipient
// type (spec §5.3); every other chain from its gas constants.
const hold = this.btcParams(this.layer2TDetails.network) !== null
? this.btcPreSignHold()
: this.computeGasHold(this.layer2TDetails.network, this.layer2TDetails.token);
this.gasHold = hold;
this.varnirFee = this.getBN();
if (this.layer2TDetails.token === "#native") {
// A native send pays its own gas: the hold rides on top of the amount.
this.delegated = false;
totalNeededToSend = totalNeededToSend.add(hold.amount);
} else {
this.delegated = true;
}
if (totalNeededToSend.lt(0)) {
throw "Transfer Issue : Has to be greater than 0";
}
// Now Check the balance is enough
if (senderBalance.lt(totalNeededToSend)) {
throw `Part-Balance to low : ${senderBalance} < ${totalNeededToSend}`;
}
// The credit charge (credits-only pricing): priced here, once, and
// refused before anything moves when it cannot be paid in full.
// >>> tenant-pays
// Stage E: a tenant-tagged withdrawal is paid by the tenant's shard float at Varnir's price (D2), never from the
// user's own credits, plan or allowance; an untagged one takes the line below exactly as before (the exit).
if (this.transactions.$i.owner.tenant) this.tenantWithdraw = await this.tenantWithdrawPlan(senderBalance, totalNeededToSend); else
// <<< tenant-pays
this.creditCharge = await this.withdrawalCreditCharge();
if (this.transactions.$i.owner.amount) {
const oStreamId = this.transactions.$r?.wallet;
const oStream = oStreamId ? this.getReadOnlyStream("wallet") : {};
const oStreamData = oStream;
// No new payout is bound to a retired wallet (Task 3.3, PR #358 review
// L1), so its in-flight payouts are only those bound before retirement,
// which the purge delay outlasts.
this.refuseRetiredBinding(oStream);
// Make sure the partition exists otherwise balance to low (cant use ?.)
this.walletOutputsCache[oStreamId] = {
stream: oStream,
streamId: oStreamId,
data: oStreamData,
transaction: {
amount: this.transactions.$i.owner.amount, // ETH
nonce: this.transactions.$i.owner.nonce || 0, // ETH
},
payload: this.transactions.$i.owner.signtx
? this.transactions.$i.owner.signtx
: this.transactions.$i.owner,
};
}
// New-recipient hold (design §4 step 3): decided here, for sign, a direct
// presign and a confirmed proposal alike, so no client can skip it.
this.holdDecideL1();
return true;
}/** * The Varnir.Plans config named by PLANS_CONFIG_STREAM, or null on a tree * that names none (production: never charges). On a tree that names one, * a read that fails, or a stream that is not the plans config, REFUSES * (ruling C3, fail closed): a node that charged nothing while its peers * charged would fork the balance; a refused withdrawal is visible and * heals once the node can read the config. */
private async readPlansConfig(): Promise<any | null> {
if (!PLANS_CONFIG_STREAM) return null;
const refusal = "Credits - the plans config could not be read; the withdrawal was not made, try again shortly";
let doc: any;
try {
doc = await this.getAnyStreamReadOnly(PLANS_CONFIG_STREAM);
} catch (e) {
throw refusal;
}
if (!doc || typeof doc !== "object" || doc.kind !== "varnir.plans.config") throw refusal;
return doc;
}/** * The presign's credit charge, or null while charging is off (no config, or * `creditsLive !== true`). The sender pays from its own balance at its own * effective tier: the network's Economy weight, or 0 for Free's free * payout, taken from the monthly allowance first and the balance for the * rest (creditsSplitCharge). Throws the refusal for a network with no * weight and for a charge the allowance and balance cannot pay together - * before anything moves. */
private async withdrawalCreditCharge(): Promise<{identity: string; credits: number; freePayout: boolean; periodStart: number; periodEnd: number; fromAllowance: number; fromBalance: number; allowancePeriod: number | null; allowanceEnd: number | null}/** Takes this.creditCharge from `state` (commitPreSign), and emits `credits-changed`. */
private takeCreditCharge(state: any): void {
const charge = this.creditCharge;
if (!charge) return;
if (charge.freePayout) {
// The month marker lives in state.credits; state.plan is Varnir.Plans' (ruling C2).
this.creditsUseFreePayout(state, charge);
return;
}
// Cannot refuse: vote priced this charge against this same owner state,
// locked for the transaction, and refused it there when short. Kept as a
// guard so a broken invariant fails loudly rather than charging nothing.
const refusal = this.creditsTakeCharge(state, charge, "withdrawal", this.umid, new Date(this.cDate).getTime());
if (refusal) throw refusal;
this.emitCredits(charge.identity, -charge.fromBalance, state, "withdrawal", 0 - charge.fromAllowance);
}/** `credits-changed`, as Varnir.Plans emits it, for a balance move here. */
private emitCredits(identity: string, delta: number, state: any, reason: CreditReason, allowance: number): void {
// `allowance` is the monthly allowance's part of the move (negative: spent, positive: given back); `allowanceUsed` is what is spent now.
this.event.emit("credits-changed", {identity, delta, balance: this.creditsBalance(state), allowance, allowanceUsed: this.creditsAllowanceUsed(state), reason, umid: this.umid});
}/**
* `presign` commit: debits `amount` (plus the gas hold on a native send)
* from the sender, with the repeat-guard record and the agent spend
* counter in the same write, and writes an `l1.presign` stream with the
* withdrawal (sender, network, token, amount, toAddress, delegated,
* gasHold, payload, secondaryKey, created) and, when held, its `hold`
* block. A held withdrawal also records the pending recipient and emits
* `withdrawal-held`. postProcess() emits `signature-presigned`.
*
* @returns {Promise<any>}
* @memberof VarnirCryptoTransfer
*/ public async commitPreSign(): Promise<any> {
const walletkeys = Object.keys(this.walletOutputsCache);
const returnOutput: ReturnOutput = {
hex: {},
layer2: [],
};
// Get Balances
let senderBalance = this.getBN(this.getL2Balance(this.ownerState));
// A non-delegated (native) send's gas hold leaves the sender's native
// partition - the same partition as the amount - now, and is settled
// against the real gas at ConfirmWithdraw. A delegated (token) send debits
// the amount only: its hold is Varnir's envelope, not the user's money.
const holdAmt = this.delegated ? this.getBN() : this.getBN(this.gasHold?.amount ?? 0);
// move around the partiton
this.setL2Balance(
this.ownerState,
senderBalance.sub(this.transactions.$i.owner.amount).sub(holdAmt)
);
// The credit charge priced in vote, in the same write as the debit.
this.takeCreditCharge(this.ownerState);
// >>> tenant-pays
// Stage E: the tenant's user fee leaves the sender in the same write (held on the presign until tenantwdsettle),
// and the reserve is taken from the shard float in this same transaction.
if (this.tenantWithdraw) this.tenantWithdrawTake(this.ownerState);
// <<< tenant-pays
// Increment the agent spend counter (no-op for an ungoverned key) in the
// SAME setState as the balance debit above (design §4.4).
this.withRecentPayment(this.ownerState);
this.bumpAgentUsage();
this.owner.setState(this.ownerState);
// Loop the raw tx output
// Assuming only 1 $o for now at this point
//const eventData = {} as any;
// loop wallet cache again
// not optimal this solution but shoulkd be drop in replacement
for (let i = walletkeys.length; i--;) {
const streamId = walletkeys[i];
// Wallet Layer 2 Management (Pending Transactions)
const outputCache = this.walletOutputsCache[streamId];
// Cannot assume wallet has schema now (as no longer being deposited)
this.hasValidSchemaObject(outputCache.data);
const layer2Wallet =
outputCache.data.layer2[this.layer2TDetails.network][
this.layer2TDetails.token
];
// Need to remove the signed for "amount" off the wallet
// Could use set/getL2 here but I have the reference already
layer2Wallet.balance = this.getBN(
layer2Wallet.balance
).sub(outputCache.transaction.amount);
// Update transaction into wallet
//outputCache.stream.setState(outputCache.data);
// Return output
returnOutput.layer2 = [
{
id: this.owner.getId(),
partitions: this.ownerState.layer2,
},
];
// !Warning! Only works with 1 !Warning!
this.eventData.umid = this.umid;
this.eventData.sender = this.owner.getId();
this.eventData.network = this.layer2TDetails.network;
this.eventData.token = this.layer2TDetails.token;
this.eventData.amount = this.transactions.$i.owner.amount;
this.eventData.toAddress = outputCache.payload.to || "NA";
this.eventData.stream = outputCache.streamId;
this.eventData.wallet = outputCache.data.address;
//this.eventData.signed = outputCache.sigRequest.signature;
this.eventData.varnirFee = this.varnirFee.toString();
this.eventData.delegated = this.delegated;
this.eventData.gasHold = this.gasHold ?? null;
this.eventData.creditCharge = this.creditCharge;
this.eventData.metadata = this.transactions.metadata || null;
this.eventData.secondaryKey = this.isSecondary();
//this.eventData.nonce = this.nonceResponse;
this.eventData.created = this.cDate;
this.eventData.transaction = outputCache.transaction;
this.eventData.payload = outputCache.payload;
//this.eventData.origin = (this as any).origin || null;
this.eventData._dbIndex = this.transactions._dbIndex || 0;
// Now we need to push this data into its own stream to be "locked" on
const signed = this.newActivityStream("l1.presign");
// New-recipient hold: votePreSigned refuses this presign until the
// block says it may go (design §3).
if (this.holdPending) {
this.eventData.hold = this.holdBlock(signed.getId(), "l1", this.holdPending);
}
signed.setState(this.eventData);
// Add to event data the stream to be locked on to.
this.eventData.preSignedStream = signed.getId();
}
// >>> tenant-pays
// Stage E: the open reserve is indexed on its shard (wdOpen), so the gateways' sweep finds it without an event.
if (this.tenantWithdraw) this.tenantWithdrawIndex(this.eventData.preSignedStream);
// <<< tenant-pays
if (this.holdPending && this.eventData.hold) {
// The pending known entry needs the presign id, so it rides a second
// setState of the same (already debited) owner state.
this.holdRememberPending(this.ownerState, this.holdPending, this.eventData.preSignedStream);
this.owner.setState(this.ownerState);
(returnOutput as any).hold = this.eventData.hold;
this.emitWithdrawalHeld(this.eventData.preSignedStream, "l1", this.eventData.toAddress, this.eventData.hold);
}
// We may still need to do the "change" as below if they don't have partitions
this.returnToRemote(returnOutput);
return true;
}/**
* `presigned` vote (gateway only, assertMinigateSigner): signs the L1
* transaction for the presign on `$o.presigned`.
*
* Refuses a presign already signed, and one still held or cancelled
* (holdSignGate). Bitcoin goes to btcVotePreSigned. Otherwise, for the
* pool wallet on `$r.wallet`: on eth/sep a sign within TIMEDIFF (13 s of
* consensus time) of the wallet's last one is refused; the wallet's
* `:volatile` must hold this node's key share (else `key-health` and
* "Check Key Health"); the debited network, the wallet's network and the
* requested one must agree (assertSigningNetwork); and the wallet must be
* the one bound at presign.
*
* The payload is built per chain from the presign record and `$i.admin`:
* EVM (nonce from `$o[wallet].nonce`, `$i.admin.nonce` or the legacy nonce
* endpoint; token contract from the debited partition; gas limit from the
* hold or the network constant; price from `$i.admin`, clamped to the
* hold's cap), Tron, or Solana; any other chain is refused. This node's
* key share then goes to the confidentialVM (signWithWallet) and the
* signature is kept for commitPreSigned.
*
* @private
* @returns {Promise<boolean>}
* @memberof VarnirCryptoTransfer
*/ private async votePreSigned(): Promise<boolean> {
await this.assertMinigateSigner();
// Balance now sits on the owner!
// this.owner = this.getActivityStreams(this.transactions.$i.owner);
// this.ownerState = this.owner.getState();
this.preSigned = this.getActivityStreams(this.transactions.$o.presigned);
this.preSignedData = this.preSigned.getState();
// TODO may need to manage multiple records IF it failed on nonce issue.
// but nonce fetching may have been resolved
if (this.preSignedData.signedStream) {
throw "Already Signed";
}
// New-recipient hold: refused while held, and for good once cancelled.
// Enforced whatever the kill switch says - a hold, once written, stands.
this.holdSignGate(this.preSignedData.hold);
// >>> tenant-pays
// Stage E: a tagged presign whose reserve was settled as never sent (expired) is never signed or armed afterwards.
if (this.preSignedData.tenantReserve && this.preSignedData.tenantReserve.state !== "reserved") throw "Tenants - this withdrawal's tenant reserve is settled (expired): it is never signed";
// <<< tenant-pays
// A frozen key signs only its ledger-authorised sweep (plan Task 3.3,
// KeyHealthFix `frozensweep`): a consolidation of its own coins to
// `mpcSweep.toAddress`. Decided here, before any route is chosen, so the
// one exception is in force for this wallet only (signingRoute). Bitcoin's
// sweep is `btcmove`, never a presign: a Bitcoin presign binds no wallet.
const sweepWalletId = this.transactions.$r ? this.transactions.$r.wallet : undefined;
if (sweepWalletId && this.btcParams(String(this.preSignedData.network || "").toLowerCase()) === null) {
this.mpc2Sweep = this.presignSweep(sweepWalletId, this.getReadOnlyStream("wallet"));
}
// An armed, unsigned presign (`tronmpcarm`, Task 3.3) signs only from the
// armed wallet, only on the mpc2 path (PR #360 review H1), before any route
// is chosen. Otherwise a retry by another gateway, or one that lost its
// queue file, could pick a Standard wallet (or another mpc2 one) for a
// walletless presign and sign a second payout while the armed bytes, perhaps
// already signed, can still land: paid twice. A re-arm may move it.
const tronArm = this.preSignedData.tronMpc;
if (tronArm !== undefined && !this.preSignedData.signedStream) {
if (!tronArm || typeof tronArm !== "object" || typeof tronArm.wallet !== "string" || this.transactions.$r.wallet !== tronArm.wallet) {
throw "Signing Issue : the presign is armed for another wallet (tronmpcarm)";
}
if (this.signingRoute(this.getReadOnlyStream("wallet"), this.transactions.$r.wallet) !== "mpc2") {
throw "Signing Issue : an armed presign signs only on the mpc2 path";
}
}
// Set the cache for paritions
this.layer2TDetails.network = this.preSignedData.network;
this.layer2TDetails.token = this.preSignedData.token;
// Bitcoin: many inputs from many wallets, its own path (spec §8.2).
if (this.btcParams(this.layer2TDetails.network) !== null) {
return this.btcVotePreSigned();
}
if (this.preSignedData.amount) {
const oStreamId = this.transactions.$r.wallet;
const oStream = this.getReadOnlyStream("wallet");
const oStreamData = oStream;
const oStreamVolatile = await this.getAnyStreamReadOnly(
`${oStreamId}:volatile`
);
// Slow down call based on last signing
if (this.layer2TDetails.network.toLowerCase() === 'eth' || this.layer2TDetails.network.toLowerCase() === 'sep') {
if (oStreamData.signed?.when) {
const then = new Date(oStreamData.signed?.when);
const now = new Date(this.cDate);
const timeDiff = now.getTime() - then.getTime();
if (timeDiff <= TIMEDIFF) {
throw `Signing to soon (${timeDiff}/${TIMEDIFF})`;
}
}
}
// JIT attempt to detect bad key
if (!oStreamVolatile.public || !oStreamVolatile.private) {
this.event.emit("key-health", {
id: oStreamId,
});
throw "Check Key Health";
}
// Make sure the partition exists otherwise balance to low (cant use ?.)
this.walletOutputsCache[oStreamId] = {
stream: oStream,
streamId: oStreamId,
data: oStreamData,
transaction: this.preSignedData.transaction,
part: oStreamVolatile.private.part,
part2: oStreamVolatile.private.part2,
keyMethod: oStreamData.keyMethod === 'mpc-tss' ? 'mpc-tss' : 'standard',
address: oStreamVolatile.public.address,
payload: null,
};
let payload;
// Moved payload creation here so can create once and post in commit
const requestedNetwork = this.preSignedData.payload?.network?.toLowerCase();
const walletNetwork = this.walletOutputsCache[oStreamId].data.network?.toLowerCase();
// The wallet decides which chain it signs for, not the request.
//
// requestedNetwork comes from $i.owner.signtx (or $i.owner), so it is
// caller-supplied, and it was preferred over the wallet's own network
// with the wallet used only as a FALLBACK - never as a check. The L2
// debit meanwhile comes from $i.owner.network. Nothing bound the two,
// and the same secp256k1 key controls the same address on every EVM
// chain: a caller could debit a testnet partition and have a MAINNET
// transaction signed from the same address.
//
// Compared canonically because the two legitimately spell the same
// network differently - the ledger says "TRX-NILE" where the pregen pool
// says "niles" - and only when the wallet actually carries a network, so
// a row without one behaves exactly as before rather than failing.
// The DEBITED partition is the authority. Not the request, and not the
// wallet either - the wallet has to agree with the debit.
//
// My first attempt at this compared requestedNetwork against
// walletNetwork, which is the wrong pair: the debit is keyed on
// layer2TDetails.network (set from preSignedData.network above), and
// nothing compared THAT to anything. It was also skippable - the guard
// only ran `if (requestedNetwork && ...)`, so omitting `network` from
// $i.owner.signtx turned it off and networkType fell through to the
// wallet's own chain, which is exactly the value an attacker wants.
// Debit a BNB partition, point phase two at an ETH wallet, sign an
// Ethereum transaction. Both defects are closed here; both are tested.
this.assertSigningNetwork(
String(this.layer2TDetails.network || "").toLowerCase(),
walletNetwork,
requestedNetwork,
);
// The wallet named at SIGN time must be the one bound at presign.
// Without this a caller re-points phase two at any wallet they like,
// which is what made the network swap reachable in the first place.
if (this.preSignedData.stream && this.transactions.$r.wallet !== this.preSignedData.stream) {
throw `Wallet changed since presign: ${this.transactions.$r.wallet} is not ${this.preSignedData.stream}`;
}
// A retired wallet finishes only the payouts bound to it before it
// retired (the binding is refused afterwards); an unbound payout is
// never signed from it (PR #358 review L1: the purge delay counts on it).
if (this.preSignedData.stream !== oStreamId) {
this.refuseRetiredBinding(oStreamData);
}
// Safe to prefer the request only because all three are now proven
// canonically identical; the switch below accepts either spelling.
const networkType = requestedNetwork ||
walletNetwork ||
this.walletOutputsCache[oStreamId].data.symbol?.toLowerCase();
// Every EVM chain takes the one "evm" branch: the four constants, or an
// enabled `evmNetworks` entry in this contract's data. Tron and Solana
// keep their own cases; anything else is refused below (default).
switch (this.evmNetworkData(networkType) ? "evm" : networkType) {
case "evm":
// Simple backwards compaitable
//const txDetails = this.preSignedData.payload;
// Is this safe? Will there always be admin and/or anything admin
// that could cause a problem? At least payload overwrites it all now
// so it should match txDetails above.
const txDetails = {...this.transactions.$i.admin, ...this.preSignedData.payload};
if (this.transactions.$o[oStreamId]?.nonce !== undefined) {
// 0 here is still valid, so check for undefined
this.nonceResponse = this.transactions.$o[oStreamId].nonce;
} else {
// Messy but safe way to move predetermined nonce
if (this.transactions.$i.admin?.nonce !== undefined) {
this.nonceResponse = this.transactions.$i.admin.nonce;
} else {
//if(!oStreamData.nonce) {
// Each node fetches this itself, so the nodes may disagree; the
// mpc2 path refuses it (mpc2ChainTx).
this.nonceFetchedByNode = true;
let retryCounts = 0;
try {
const url = this.nonceUrlFromName(networkType);
while (this.nonceResponse === undefined && retryCounts++ <= 4) {
const response = (
await HTTP.send(
url + this.walletOutputsCache[oStreamId].address,
"GET"
)
).data as any;
if (response.locked) {
throw "Wallet Signing Locked";
} else {
this.nonceResponse = response.nonce;
}
}
} catch (e) {
throw "Nonce Fetch Failed - " + e;
}
// No nonce came back: refuse, never guess. This used to fall back
// to the wallet stream's LAST signed nonce (a postfix increment
// returned the old value), so a reused nonce. A refused vote leaves the
// withdrawal pending and the gateway retries it next cycle.
if (this.nonceResponse === undefined) {
throw "Withdrawal - the nonce could not be read; try again shortly";
}
}
}
if (this.nonceResponse === undefined) {
throw "Nonce Undefined";
}
// A nonce is a non-negative integer, signed as a NUMBER. This used
// to sign `this.nonceResponse || "0"`, turning nonce 0 into the
// STRING "0"; the gateway then cached "0" + 1 = "01", reserved
// "011", and a Base Sepolia payout was signed at nonce 11 the chain
// never accepted (2026-09-29). A canonical decimal string from the
// gateway is normalised; anything else ("011", "x", -1) is refused.
const nonceValue: unknown = this.nonceResponse;
const nonceNumber =
typeof nonceValue === "string" && /^(0|[1-9][0-9]*)$/.test(nonceValue)
? Number(nonceValue)
: nonceValue;
if (typeof nonceNumber !== "number" || !Number.isSafeInteger(nonceNumber) || nonceNumber < 0) {
throw "Nonce Invalid";
}
this.nonceResponse = nonceNumber;
// Derived from the L2 partition being debited, NOT from
// txDetails.contractAddress. The caller supplies that field, so
// letting it pick the branch let a native-partition debit produce a
// token transfer - see networkTokenToContract's own comment.
const l1Contract = this.networkTokenToContract(networkType, this.layer2TDetails.token, null);
if (l1Contract && txDetails.contractAddress && l1Contract.toLowerCase() !== String(txDetails.contractAddress).toLowerCase()) {
throw `Requested contract ${txDetails.contractAddress} is not the contract for this balance`;
}
if (!l1Contract && txDetails.contractAddress) {
throw "A native transfer cannot carry a contract address";
}
if (l1Contract) {
// XX-20 (TODO : Merge with TRC20 or stick like this?)
const iface = new utils.Interface(this.contractAbiFragment);
const rawData = iface.encodeFunctionData("transfer", [
txDetails.to,
this.walletOutputsCache[oStreamId].transaction.amount,
]);
payload = {
from: this.walletOutputsCache[oStreamId].address,
to: l1Contract,
//gasPrice: txDetails.gas,
nonce: this.nonceResponse,
// Derived, never taken from txDetails. signtx.chainId used to win
// outright, so a caller whose debit, wallet and request all
// agreed on bnb could still have the transaction signed for
// Ethereum mainnet - the one field that actually decides the
// chain bypassed the binding above it.
chainId: this.requireEvmNetwork(networkType).chainId,
// Was constants.HexZero, which @ethersproject/constants does
// not export - it is AddressZero/HashZero/Zero and never had a
// HexZero - so this read undefined on every ERC20 send. Signing
// was unaffected only because an omitted value already means
// zero: the signed bytes are identical either way, verified by
// signing this exact payload both ways. Written literally now
// so it stops depending on that coincidence.
value: "0x0",
// Set by the gas block below from the network constant.
data: rawData,
toAddress: txDetails.to,
};
} else {
if (txDetails.data) {
// Custom transaction (from dex most likely)
throw "L2 Custom transaction not support Native/Token Only";
} else {
// Native Transaction
payload = {
to: txDetails.to,
from: this.walletOutputsCache[oStreamId].address,
value: this.getBN(
this.walletOutputsCache[oStreamId].transaction.amount
).toHexString(),
//gasPrice: txDetails.gas,
nonce: this.nonceResponse,
// Derived, never taken from txDetails. signtx.chainId used to win
// outright, so a caller whose debit, wallet and request all
// agreed on bnb could still have the transaction signed for
// Ethereum mainnet - the one field that actually decides the
// chain bypassed the binding above it.
chainId: this.requireEvmNetwork(networkType).chainId,
};
}
}
// GAS COMES FROM THE GATEWAY, NEVER FROM THE REQUEST - and only the
// price does: the gas LIMIT is a per-network constant, and the price
// is clamped to what the presign hold covers.
//
// gasLimit * price is an upper bound on what leaves the pooled wallet
// as miner fees, and the wallet pays that out of its own native
// balance regardless of whose transfer it is. The limit used to be
// ceil(metadata.feesEstimate / price) off the USER's presign metadata
// (B4) - a caller could sign an ERC20 transfer with too little gas to
// run, burning pool gas for a send that was then fully refunded. It
// is now the per-network constant the presign held for
// (evmNetworkData gasLimits), and $i.admin.gasLimit is no longer read.
//
// The price is minigate's live quote from $i.admin (never the merged
// txDetails, whose caller payload wins the spread), capped at the
// maxFeePerGas the presign hold was sized with, so gasLimit * price
// can never exceed the hold - the sender's money on a native send,
// Varnir's exposure on a (delegated) token send. A presign written
// before holds existed carries no gasHold and is clamped to the
// network cap (owner override first), bounding what a legacy
// delegated send can burn from the pool (RV8).
const hold = this.preSignedData.gasHold;
const evmChain = this.requireEvmNetwork(networkType);
const netCode = evmChain.code;
const limits = evmChain.gasLimits;
if (!limits) {
throw `No gas limits defined for network ${networkType}`;
}
payload.gasLimit = hold?.gasLimit ?? (l1Contract ? limits.token : limits.native);
const cap = this.getBN(
hold?.maxFeePerGas ?? this.getContractDataHelper().gasPriceCaps?.[netCode] ?? evmChain.gasPriceCap
);
const clamp = (v: any) => { const b = this.getBN(v); return b.gt(cap) ? cap : b; };
const gas = this.transactions.$i.admin || {};
if (gas.gas) {
// Legacy
payload.gasPrice = clamp(gas.gas).toHexString();
} else if (gas.maxPriorityFeePerGas && gas.maxFeePerGas) {
// eip 1559
const maxFee = clamp(gas.maxFeePerGas);
const prio = this.getBN(gas.maxPriorityFeePerGas);
payload.maxFeePerGas = maxFee.toHexString();
payload.maxPriorityFeePerGas = (prio.gt(maxFee) ? maxFee : prio).toHexString();
} else {
throw "No Gas Set (Legacy or EIP1559)";
}
break;
case "trx":
if (this.walletOutputsCache[oStreamId].transaction.hex) {
// We do check amounts but not the hex this way
payload = {
hex: this.walletOutputsCache[oStreamId].transaction.hex,
};
} else {
// TODO resolve duplicate but get it working relilably!
payload = {
network: "main",
//to: this.transactions.$i.owner.to,
to: this.preSignedData.payload.to,
address: this.walletOutputsCache[oStreamId].address,
amount: this.walletOutputsCache[oStreamId].transaction.amount,
//contractAddress: this.transactions.$i.owner.contractAddress,
//contractAddress: this.preSignedData.payload.contractAddress,
...this.tronContractFields(networkType),
...this.tronPresignFields(),
};
}
break;
// Tron's real testnet was never handled here - this switch fell
// through with no matching case, leaving `payload` as `undefined`
// from its declaration above. JSON.stringify silently drops an
// undefined value's key entirely, so confidentialVM's /sign route
// received a body with no `payload` field at all and correctly
// (but silently - no error surfaced anywhere in the chain)
// rejected it as invalid, every single time, for every native
// Tron Nile send this session.
//
// Both spellings, same as the "shasta"/"trx-shasta" pair right
// below: `networkType` is derived from THREE possible sources in
// priority order (this.preSignedData.payload?.network first, then
// the wallet row's own data.network, then data.symbol) - a real
// presigned transaction's preSignedData.payload.network carries
// the LEDGER's own spelling "TRX-NILE" (see wallet-client.ts's own
// doc comment on layer2NetworkCode - $i.owner.network has to be
// the ledger's spelling, not the pregen pool's "niles"), which
// lowercases to "trx-nile", NOT "niles" - confirmed live via
// temporary diagnostic logging showing exactly this value on a
// real stuck production transaction after a first attempt at this
// fix (case "niles" alone) still failed identically. The wallet
// row's own "niles" spelling is also covered here since it's a
// real fallback source per the same three-way priority chain.
//
// Signer.tronBuilder on the confidentialVM side already has its
// own `case 'niles':` and already typed 'niles' as a valid
// network - only this side was missing any case for either
// spelling. Mirrors "trx" exactly, just with the real testnet's
// network label.
case "niles":
case "trx-nile":
if (this.walletOutputsCache[oStreamId].transaction.hex) {
payload = {
hex: this.walletOutputsCache[oStreamId].transaction.hex,
};
} else {
payload = {
network: "niles",
to: this.preSignedData.payload.to,
address: this.walletOutputsCache[oStreamId].address,
amount: this.walletOutputsCache[oStreamId].transaction.amount,
...this.tronContractFields(networkType),
...this.tronPresignFields(),
};
}
break;
case "shasta":
case "trx-shasta":
if (this.walletOutputsCache[oStreamId].transaction.hex) {
// We do check amounts but not the hex this way
payload = {
hex: this.walletOutputsCache[oStreamId].transaction.hex,
};
} else {
payload = {
network: "shasta",
//to: this.transactions.$i.owner.to,
to: this.preSignedData.payload.to,
address: this.walletOutputsCache[oStreamId].address,
amount: this.walletOutputsCache[oStreamId].transaction.amount,
//contractAddress: this.transactions.$i.owner.contractAddress,
//contractAddress: this.preSignedData.payload.contractAddress,
...this.tronContractFields(networkType),
...this.tronPresignFields(),
};
}
break;
case 'sol':
case 'soldev':
const transferTransaction = new Transaction({
feePayer: new PublicKey(this.walletOutputsCache[oStreamId].address),
blockhash: this.transactions.$i.admin.latestBlockhash,
lastValidBlockHeight: this.transactions.$i.admin.lastValidBlockHeight
});
// Derived, for the same reason as the EVM branch above.
const contractAddr = this.networkTokenToContract(networkType, this.layer2TDetails.token, null);
if (!contractAddr && this.preSignedData.payload.contractAddress) {
throw "A native transfer cannot carry a contract address";
}
if (contractAddr) {
let createATA;
// token
if (this.transactions.$i.admin.createATA) {
// Create the ata instructiuon
createATA = createAssociatedTokenAccountInstruction(
new PublicKey(this.walletOutputsCache[oStreamId].address),
new PublicKey(this.transactions.$i.admin.toATA),
new PublicKey(this.preSignedData.payload.to),
new PublicKey(contractAddr),
this.transactions.$i.admin.programId ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID
)
}
if (createATA) {
transferTransaction.add(createATA);
}
const transferInstruction = createTransferCheckedInstruction(
new PublicKey(this.transactions.$i.admin.senderATA), // source
new PublicKey(contractAddr), // mint
new PublicKey(this.transactions.$i.admin.toATA), // destination
new PublicKey(this.walletOutputsCache[oStreamId].address), // owner
this.walletOutputsCache[oStreamId].transaction.amount, // amount,
6, // decimals
[], // multiSigners
this.transactions.$i.admin.programId ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID
);
transferTransaction.add(transferInstruction);
payload = transferTransaction.serializeMessage().toString('hex');
} else {
// native
const transferInstruction = SystemProgram.transfer({
fromPubkey: new PublicKey(this.walletOutputsCache[oStreamId].address),
toPubkey: new PublicKey(this.preSignedData.payload.to),
lamports: this.walletOutputsCache[oStreamId].transaction.amount
});
transferTransaction.add(transferInstruction);
payload = transferTransaction.serializeMessage().toString('hex');
}
break;
default:
// Fails closed: no payload is ever signed for a chain this contract
// does not know (it used to fall through with `payload` undefined).
throw `Unknown EVM network ${networkType}`;
}
this.walletOutputsCache[oStreamId].payload = payload;
if (
this.walletOutputsCache[oStreamId].stream &&
this.walletOutputsCache[oStreamId].transaction
) {
const payload = this.walletOutputsCache[oStreamId].payload;
let cryptoSymbol = this.walletOutputsCache[oStreamId].data.symbol;
// Payload is different based on network
switch (
this.walletOutputsCache[oStreamId].data.network ||
this.walletOutputsCache[oStreamId].data.symbol
) {
case "trx":
case "niles":
case "shasta":
cryptoSymbol = "trx";
break;
}
// This method wont work with $terra because prioir
// to this node everyone will be waiting
// so putting it before commit and ignoring the response
// we can then pull it here again
const cache = this.walletOutputsCache[oStreamId];
const sig = await this.signWithWallet(
{
part: cache.part,
part2: cache.part2,
keyMethod: cache.keyMethod,
address: cache.address,
network: networkType,
walletId: oStreamId,
wallet: oStreamData,
},
cryptoSymbol,
payload
);
this.walletOutputsCache[oStreamId].sigRequest = sig as any; // Fix any
this.signatureHex = sig.signature;
return true;
}
} else {
throw "Wallet Issue : Amount not found";
}
}/**
* Proves the $selfsign signer of a gateway entry ('presigned', 'cancel') is
* a minigate: $r.minigate is a genuine minigate and $i.admin.publicKey is
* one of its authorities. Throws the refusal otherwise.
*/ private async assertMinigateSigner(): Promise<void> {
// ---- Minigate authorisation ----
// The 'presigned' sign entry is submitted $selfsign (admin is NOT a locked
// $i input) on purpose: it lets all four minigates sign concurrently
// without serialising on a shared/owned input. But $selfsign only proves
// the signer holds the private key for $i.admin.publicKey - it does NOT
// prove the signer is a minigate. Without a check, anyone with a keypair
// and a presign stream id could self-sign their own 'presigned' entry and
// complete a victim's presign with a garbage nonce / too-low gasLimit: the
// L1 tx never mines but the L2 debit already happened and the "Already
// Signed" guard below blocks every retry, so the balance is destroyed.
//
// The signer names its minigate identity as a read-only $r reference (also
// unlocked, so concurrency is preserved) and we prove here that:
// 1. that stream is a genuine minigate - its :volatile carries the
// `minigate` flag, which only an operator/contract can write (no
// contract exposes a write to it), so a user cannot forge it. This is
// the same trust anchor Varnir.Correction relies on.
// 2. the self-signing key belongs to that minigate - $i.admin.publicKey
// (which $selfsign binds to the actual signer) is one of the identity's
// registered authorities, read from its :stream meta doc.
// Together these prove the self-signer IS a minigate. Both are needed: (1)
// alone lets an attacker reference a real minigate but sign with their own
// key; (2) alone lets an attacker reference their own stream with their own
// key as an authority. Both docs are provisioned once and never change, so
// there is no mid-update revision divergence across nodes.
const minigateRef = this.transactions.$r?.minigate;
if (!minigateRef) {
throw "Presigned not authorised - missing minigate reference";
}
const minigateVolatile: any = await this.getAnyStreamReadOnly(
`${minigateRef}:volatile`
);
if (!minigateVolatile?.minigate) {
throw "Presigned not authorised - reference is not a minigate";
}
const signingKey = this.transactions.$i.admin?.publicKey;
const minigateMeta: any = await this.getAnyStreamReadOnly(
`${minigateRef}:stream`
);
const authorised =
!!signingKey &&
Array.isArray(minigateMeta?.authorities) &&
minigateMeta.authorities.some((a: any) => a.public === signingKey);
if (!authorised) {
throw "Presigned not authorised - signing key is not a minigate authority";
}
}/** * True only when the owner `mod` stored `mpc2Enabled: true`. Absent or null * is false (the path is dark until the cutover, gate G5). Any other value * throws: a typo in contract data must not pick a protocol. */
private mpc2Enabled(): boolean {
const stored = this.getContractDataHelper().mpc2Enabled;
if (stored === undefined || stored === null) {
return false;
}
if (typeof stored !== "boolean") {
throw "Signing Issue : mpc2Enabled contract data is malformed";
}
return stored;
}/** * The ledger freeze switch (Adam 2026-10-09, * docs/decisions/2026-10-09-mpc-freeze-behind-flag.md): true only when the * owner `mod` stored `mpc2FreezeEnabled: true`; anything else is off. * KeyHealthCheck (`mpcfreeze`) and KeyHealthFix (`frozensweep`) read the * same field from this contract's data. Here it gates `sweeparm`, so no * frozen-key sweep runs while it is off. */
private mpc2FreezeEnabled(): boolean {
return this.getContractDataHelper().mpc2FreezeEnabled === true;
}/** * The gateway-submitted ledger halt switch (Adam 2026-10-09: "mpchalt put * it behind a flag as well"): true only when the owner `mod` stored * `mpc2LedgerHaltEnabled: true`; anything else is off. Separate from * `mpc2FreezeEnabled`, so the two are switched on independently. It gates * only the `mpchalt` entry: an `mpc2Halt` already in this contract's data * is honoured exactly as before, and the CVMs' in-memory peer-suspect * refusal is unchanged. */
private mpc2LedgerHaltEnabled(): boolean {
return this.getContractDataHelper().mpc2LedgerHaltEnabled === true;
}/** The `mod` validator for `mpc2Enabled`: absent leaves it alone, else exactly true or false. */
private assertMpc2Enabled(value: any): void {
if (value === undefined || value === null) {
return;
}
// A string "false" is truthy; only a real boolean may switch protocols.
if (typeof value !== "boolean") {
throw "mpc2Enabled must be true or false";
}
}/** * Which signer a wallet key uses, from the key stream's own state: "standard", * "mpc2" or "legacy-mpc" (the #200 routes). Throws the refusal otherwise. * The key's `mpcProtocol` decides; this contract's `mpc2Enabled` only * retires old keys and, in production, gates mpc-tss as a whole. */
private signingRoute(wallet: any, walletId?: string): "standard" | "mpc2" | "legacy-mpc" {
const w = wallet || {};
const hasProtocol = w.mpcProtocol !== undefined;
if (w.keyMethod !== "mpc-tss") {
// Only Create's mpc2 keygen writes mpcProtocol, and always with mpc-tss.
// A key carrying it under another method is not one Create made, and on
// the Standard path its mpc2 part would go to `/sign` as a whole key.
if (hasProtocol) {
throw "Signing Issue : mpcProtocol on a key that is not mpc-tss";
}
return "standard";
}
// A freeze (plan Task 3.3) is never lifted by signing. The CVMs refuse a
// frozen key too, but refusing here costs no call. Any value counts, so a
// malformed record fails closed. The one exception is the sweep this
// round was checked to be (`mpc2Sweep`, set by presignSweep or
// btcVoteMove for exactly this wallet): it is not a lifting, the key stays
// frozen, and the CVMs sign it only under their own sweep rule.
if (w.mpcFrozen !== undefined && !(this.mpc2Sweep && typeof walletId === "string" && walletId === this.mpc2Sweep.keyId)) {
throw "Signing Issue : the key is frozen";
}
// A purged key's parts are deleted (KeyHealthFix `purge`, Task 3.3):
// nothing can rebuild it, so a request would only cost a vote and raise
// a key-health event that tries to repair a key nobody may use. A key
// that is only retired still signs, so its coins can be moved out.
if (w.mpcPurged !== undefined) {
throw "Signing Issue : the key is purged";
}
const enabled = this.mpc2Enabled();
// Production's code-level guard (plan Global Constraints): with mpc2 off
// there, no mpc-tss key signs, old or new.
if (!enabled && !LEGACY_MPC_TSS_ALLOWED) {
throw "Signing Issue : MPC-TSS signing is off on this network";
}
if (hasProtocol) {
// An mpcProtocol key never falls back to the old routes (review H1). An
// unknown protocol is a key no CVM here can sign, so it is refused, not
// tried on the nearest path.
if (w.mpcProtocol !== MPC2_PROTOCOL) {
throw "Signing Issue : unknown mpcProtocol";
}
// The peer lockout, held on the ledger (`mpchalt`, Task 3.3): a CVM
// forgets it at a restart (it keeps nothing on disk), so this record is
// what keeps mpc2 signing off until an operator clears it with `mod`.
// Any stored value counts, so a malformed record fails closed.
const halt = this.getContractDataHelper().mpc2Halt;
if (halt !== undefined && halt !== null) {
throw `Signing Issue : MPC signing is halted on the ledger (peer lockout ${halt && typeof halt === "object" ? String(halt.sid) : "malformed record"})`;
}
return "mpc2";
}
// Once mpc2 is on, old keys are retired untouched (plan Task 5.2): their
// parts are never sent anywhere again.
if (enabled) {
throw "Signing Issue : old MPC-TSS keys are retired";
}
return "legacy-mpc";
}/**
* The mpc2 vote for one key: checks the key, builds the chain transaction,
* asks this node's egress agent for `mpc2/sign`, and checks both CVMs'
* answers. Returns `{status, umid, signature}` (CVM-A's signature), the
* shape signWithWallet's callers consume. Bitcoin (plan Task 4.3,
* btcMpc2SignTx) calls it for the one Advanced wallet a payout spends, with
* `{tx, inputs}` as the chain payload, and reads `signature.witnesses` by
* `inputIndex`.
*/ private async mpc2Sign(walletId: any, wallet: any, part: any, part2: any, chainPayload: any): Promise<any> {
// keyId is the wallet stream's id, which the engine made SHA-256(umid ‖
// "ntx.new.key") at Create: the keyId the CVMs used at keygen. A prefixed,
// re-cased or recomputed id gives another sid, sealing AAD and Bitcoin
// `inputs[k].wallet`, so every signature would be refused and the funds
// stuck (review of PR #350).
if (typeof walletId !== "string" || !/^[0-9a-f]{64}$/.test(walletId)) {
throw "Signing Issue : mpc2 keyId must be the wallet stream id, 64 lowercase hex";
}
// The key's own network, never the transaction's symbol: the CVMs keep no
// per-key record and build the digest for whatever network the request
// names, and seal the parts under it (review of PR #350).
const network = wallet.network;
if (typeof network !== "string" || !/^[A-Za-z0-9-]{1,32}$/.test(network)) {
throw "Signing Issue : mpc2 key has no network";
}
// Q from the key's state, never from the request: the CVMs refuse a
// rebuilt share whose key is not this Q. Compressed, as they accept it.
const q = wallet.publicKey;
if (typeof q !== "string" || !/^0[23][0-9a-f]{64}$/.test(q)) {
throw "Signing Issue : mpc2 key has no compressed publicKey";
}
// Create stores Q under both names, always equal (review L4). Two values
// mean the record was altered, and nobody can say which one is the key.
if (wallet.pubkey !== undefined && wallet.pubkey !== q) {
throw "Signing Issue : mpc2 key's pubkey differs from its publicKey";
}
const tables = this.mpc2PartHashes(wallet.partHashes);
// Both parts must be on this node: each CVM needs its own share's part.
if (typeof part !== "string" || part.length === 0 || typeof part2 !== "string" || part2.length === 0) {
this.event.emit("key-health", {id: walletId});
throw "Signing Issue : mpc2 key part missing on this node";
}
// Tables in [A, B] order: CVM party 0 checks this node's part against
// table 0 and party 1 against table 1. A swapped record would send a CVM
// the other party's parts; it shows here as parts in the wrong tables.
if (tables[0].indexOf(this.ActiveCrypto.Hash.getHash(part, "sha256")) === -1 ||
tables[1].indexOf(this.ActiveCrypto.Hash.getHash(part2, "sha256")) === -1) {
throw "Signing Issue : this node's part hash is not in the key's tables";
}
const tx = this.mpc2ChainTx(network, chainPayload);
let response: any;
try {
response = await HTTP.send(
`${MPC2_EGRESS_URL}/mpc2/sign`,
"POST",
[],
{
umid: this.umid,
network,
keyId: walletId,
keyMethod: "mpc-tss",
mpcProtocol: MPC2_PROTOCOL,
// Plaintext Shamir parts, to loopback only: the agent seals `part`
// to CVM-A's attested key and `part2` to CVM-B's (plan Task 2.8).
part,
part2,
// The full payload, never a hash of it: each CVM builds its digest
// from `tx` itself (spec §4.3). No `splits`, `threshold` or `remote`.
payload: this.mpc2Payload(wallet, tables, tx, walletId),
},
false,
MPC2_SIGN_HTTP_TIMEOUT_S
);
} catch (e) {
throw "Signing Issue : Try Again";
}
const reason = this.mpc2SignReplyRefusal(response ? response.data : null, walletId, network, q);
if (reason) {
this.event.emit("unreachable-consensus", {network, address: wallet.address});
throw `Signing Issue : mpc2 ${reason}`;
}
// Before anything is stored or broadcast: the returned signature must be
// Q's over exactly this payload (review M1). The acknowledgements alone
// prove nothing to the contract (their Ed25519 signatures are checked by
// the agent only), and CVM-A's `signature` is what l1.sign records.
this.mpc2AssertSigned(network, tx, q, response.data.a.signature, response.data.a.ack.signatures, walletId);
return {status: "ok", umid: this.umid, signature: response.data.a.signature};
}/** * Throws unless `signature`, CVM-A's chain output, is Q's signature over * `tx` and matches the acknowledged (digest, r, s). EVM: the signed * transaction parses, recovers to Q's address, and carries every approved * field unchanged. Tron: the signed object's raw_data_hex is the one * submitted, its txID is SHA-256 of it, and the signature recovers to Q's * address. Bitcoin (plan Task 4.3): mpc2AssertBtcSigned, one * acknowledgement per input of key `keyId`. Any other network throws. */
private mpc2AssertSigned(network: string, tx: any, q: string, signature: any, acks: any[], keyId: string): void {
const wallet = utils.computeAddress("0x" + q);
const code = network.toLowerCase();
if (this.btcParams(code) !== null) {
this.mpc2AssertBtcSigned(tx, q, signature, acks, keyId);
return;
}
// EVM and Tron sign one digest (input 0); more would be signatures this
// payout never asked for. Per chain, because Bitcoin signs one per input.
const oneSignature = () => {
if (acks.length !== 1 || !acks[0] || acks[0].inputIndex !== 0) {
throw "Signing Issue : mpc2 expected exactly one signature";
}
};
let digest: string;
let r: string;
let s: string;
if (MPC2_TRON_CODES.indexOf(code) !== -1) {
oneSignature();
const signed = signature;
// The bytes broadcast must be the bytes every node approved: another
// raw_data_hex is another payment.
if (!signed || typeof signed !== "object" || Array.isArray(signed) || signed.raw_data_hex !== tx.raw_data_hex) {
throw "Signing Issue : mpc2 signed Tron transaction is not the submitted raw_data_hex";
}
digest = utils.sha256("0x" + tx.raw_data_hex).slice(2);
// Tron identifies (and the broadcaster tracks) the payout by txID.
if (signed.txID !== digest) {
throw "Signing Issue : mpc2 Tron txID is not SHA-256(raw_data_hex)";
}
// r ‖ s ‖ v+27, the CVM's encoding (mpc2/digest.ts tronPlan).
const sig = Array.isArray(signed.signature) && signed.signature.length === 1 ? signed.signature[0] : null;
if (typeof sig !== "string" || !/^[0-9a-f]{128}(1b|1c)$/.test(sig)) {
throw "Signing Issue : mpc2 Tron signature malformed";
}
let recovered = "";
try {
recovered = utils.recoverAddress("0x" + digest, "0x" + sig);
} catch (e) {
recovered = "";
}
// Only Q's key can spend from the wallet; any other signer's bytes
// would be recorded as signed and never land.
if (recovered !== wallet) {
throw "Signing Issue : mpc2 Tron signature is not Q's";
}
r = sig.slice(0, 64);
s = sig.slice(64, 128);
} else if (this.evmNetworkData(code)) {
oneSignature();
let parsed: any;
try {
parsed = utils.parseTransaction(signature);
} catch (e) {
throw "Signing Issue : mpc2 signed EVM transaction does not parse";
}
// parseTransaction recovers `from` from the signature itself.
if (!parsed || parsed.from !== wallet) {
throw "Signing Issue : mpc2 signed EVM transaction is not signed by Q";
}
const num = (v: any) => BigInt(v === undefined || v === null ? 0 : v.toString());
const eip1559 = tx.maxFeePerGas !== undefined && tx.maxFeePerGas !== null;
// Every field the chain executes, against the approved payload: a
// signature by Q over anything else is a different payment.
// ethers v5 parses a legacy (gasPrice) transaction, EIP-155 or not, as
// type null; the CVMs sign a gasPrice payload as type 0 (review R1).
const parsedType = parsed.type === null || parsed.type === undefined ? 0 : parsed.type;
const same =
parsedType === (eip1559 ? 2 : 0) &&
String(parsed.to).toLowerCase() === String(tx.to).toLowerCase() &&
parsed.nonce === tx.nonce &&
parsed.chainId === tx.chainId &&
num(parsed.gasLimit) === num(tx.gasLimit) &&
num(parsed.value) === num(tx.value) &&
String(parsed.data || "0x").toLowerCase() === String(tx.data || "0x").toLowerCase() &&
(eip1559
? num(parsed.maxFeePerGas) === num(tx.maxFeePerGas) && num(parsed.maxPriorityFeePerGas) === num(tx.maxPriorityFeePerGas)
: num(parsed.gasPrice) === num(tx.gasPrice)) &&
(!parsed.accessList || parsed.accessList.length === 0);
if (!same) {
throw "Signing Issue : mpc2 signed EVM transaction is not the approved payload";
}
const unsigned: any = {
type: parsedType,
chainId: parsed.chainId,
nonce: parsed.nonce,
gasLimit: parsed.gasLimit,
to: parsed.to,
value: parsed.value,
data: parsed.data,
};
if (eip1559) {
unsigned.maxFeePerGas = parsed.maxFeePerGas;
unsigned.maxPriorityFeePerGas = parsed.maxPriorityFeePerGas;
unsigned.accessList = [];
} else {
unsigned.gasPrice = parsed.gasPrice;
}
digest = utils.keccak256(utils.serializeTransaction(unsigned)).slice(2);
r = String(parsed.r).slice(2).toLowerCase();
s = String(parsed.s).slice(2).toLowerCase();
} else {
// Never read an unknown chain's output as an EVM transaction.
throw `Signing Issue : mpc2 cannot verify signatures on ${network}`;
}
// The acknowledgements both CVMs agreed must describe this signature, so
// the agent's ackSig check (Task 2.8) covers what is broadcast.
if (acks[0].digest !== digest || acks[0].r !== r || acks[0].s !== s) {
throw "Signing Issue : mpc2 acknowledgement is not for this signature";
}
}/**
* The Bitcoin branch of mpc2AssertSigned (plan Task 4.3, PR #351 re-review
* R2). Throws unless CVM-A's `{witnesses}` and the acknowledgements cover
* exactly the inputs of `tx` (the `{tx, inputs}` this contract sent) whose
* wallet is `keyId`, each index once and in input order, and each witness
* is `[DER(r, s) ‖ 01, Q]` in strict, low-S DER with (r, s) Q's signature
* over the BIP143 sighash recomputed here (script code of HASH160(Q), the
* input's value), acknowledged as exactly that (digest, r, s). The CVMs run
* the same checks on their own digests; this is every node's own check of
* what it is about to record and broadcast, as for EVM and Tron (review M1).
*/ private mpc2AssertBtcSigned(tx: any, q: string, signature: any, acks: any[], keyId: string): void {
const unsigned = this.btcParseUnsigned(tx.tx);
if (!Array.isArray(tx.inputs) || tx.inputs.length !== unsigned.inputs.length) {
throw "Signing Issue : mpc2 Bitcoin inputs do not match the transaction";
}
// The set the CVMs must have signed, decided from the agreed payload
// (the CVM selects the same way: mpc2/digest.ts btcPlan). Fewer would be
// a transaction that never lands; more, signatures nobody asked for.
const expected: number[] = [];
for (let k = 0; k < tx.inputs.length; k++) {
if (tx.inputs[k].wallet === keyId) {
expected.push(k);
}
}
if (expected.length === 0 || expected.length > BTC_MPC2_MAX_INPUTS) {
throw "Signing Issue : mpc2 Bitcoin payload has no or too many inputs for this key";
}
if (!Array.isArray(acks) || acks.length !== expected.length || acks.some((a: any, j: number) => !a || a.inputIndex !== expected[j])) {
throw "Signing Issue : mpc2 expected one acknowledgement per input of this key, in order";
}
// Only witnesses: the contract assembles and serialises the transaction
// itself, so nothing else from the CVM can reach the broadcast.
const isObject = !!signature && typeof signature === "object" && !Array.isArray(signature);
if (!isObject || Object.keys(signature).length !== 1 || !Array.isArray(signature.witnesses)) {
throw "Signing Issue : mpc2 Bitcoin signature must be exactly {witnesses}";
}
const ws = signature.witnesses;
if (ws.length !== expected.length || ws.some((w: any, j: number) => !w || typeof w !== "object" || w.inputIndex !== expected[j])) {
throw "Signing Issue : mpc2 expected one witness per input of this key, in order";
}
const pub = this.btcHexToBytes(q);
const scriptCode = this.btcConcat([Uint8Array.from([0x19, 0x76, 0xa9, 0x14]), this.btcHash160(pub), Uint8Array.from([0x88, 0xac])]);
const pre = this.btcBip143Hashes(unsigned);
const halfN = BigInt("0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0");
const signer = utils.computeAddress("0x" + q);
for (let j = 0; j < expected.length; j++) {
const k = expected[j];
const w = ws[j].witness;
// P2WPKH: exactly <sig> <Q>. Another key in the witness cannot spend
// Q's output, and the witness program commits to HASH160(Q).
if (!Array.isArray(w) || w.length !== 2 || w[1] !== q || typeof w[0] !== "string" || !/^([0-9a-f]{2}){9,73}$/.test(w[0])) {
throw "Signing Issue : mpc2 Bitcoin witness does not carry Q";
}
const value = tx.inputs[k].value;
if (typeof value !== "string" || !/^[1-9][0-9]{0,15}$/.test(value)) {
throw "Signing Issue : mpc2 Bitcoin input value malformed";
}
const digest = this.btcBytesToHex(this.btcSighashP2wpkh(unsigned, k, scriptCode, BigInt(value), pre));
// Strict DER (BIP66) with SIGHASH_ALL: re-encoding (r, s) must give the
// exact bytes, so a malleated encoding is refused, not normalised.
const sigHex = w[0];
if (sigHex.slice(-2) !== "01") {
throw "Signing Issue : mpc2 Bitcoin witness must be strict DER with SIGHASH_ALL";
}
const rs = this.mpc2DerToRs(sigHex.slice(0, -2));
if (rs === null || this.mpc2RsToDer(rs.r, rs.s) !== sigHex.slice(0, -2)) {
throw "Signing Issue : mpc2 Bitcoin witness must be strict DER with SIGHASH_ALL";
}
// Low-S (BIP146): a high-S witness is non-standard and is not relayed.
if (BigInt("0x" + rs.s) > halfN) {
throw "Signing Issue : mpc2 Bitcoin signature is not low-S";
}
const v = acks[j].v;
let recovered = "";
try {
recovered = (v === 0 || v === 1) ? utils.recoverAddress("0x" + digest, {r: "0x" + rs.r, s: "0x" + rs.s, v: 27 + v}) : "";
} catch (e) {
recovered = "";
}
if (recovered !== signer) {
throw "Signing Issue : mpc2 Bitcoin witness is not Q's signature over its BIP143 sighash";
}
// What both CVMs acknowledged (and the agent verified under their
// attested keys) is this signature over this digest.
if (acks[j].digest !== digest || acks[j].r !== rs.r || acks[j].s !== rs.s) {
throw "Signing Issue : mpc2 acknowledgement is not for this signature";
}
}
}/** BIP143's hashPrevouts, hashSequence and hashOutputs for a parsed unsigned transaction (SIGHASH_ALL). */
private btcBip143Hashes(tx: any): {prevouts: Uint8Array; sequences: Uint8Array; outputs: Uint8Array}/** (r, s) as 64-hex each from a DER signature (no sighash byte), or null when it is not DER of two positive integers. */
private mpc2DerToRs(der: string): {r: string; s: string}/** Strict DER (BIP66) of (r, s), each 64-hex: minimal big-endian integers, a 00 only before a high bit. */
private mpc2RsToDer(r: string, s: string): string {
const int = (x: string): string => {
let h = x.replace(/^(00)+/, "");
if (h === "") {
h = "00";
}
if (parseInt(h.slice(0, 2), 16) >= 0x80) {
h = "00" + h;
}
return "02" + (h.length / 2).toString(16).padStart(2, "0") + h;
};
const body = int(r) + int(s);
return "30" + (body.length / 2).toString(16).padStart(2, "0") + body;
}/** * The key's part-hash tables as `[A, B]`: two tables of TOTAL distinct * SHA-256 hex hashes, disjoint. Throws otherwise. */
private mpc2PartHashes(t: any): string[][] {
// The CVMs refuse any other shape (mpc2/digest.ts parseSignPayload); a
// short or repeated table could also let a wrong part match an entry.
const table = (x: any) =>
Array.isArray(x) && x.length === TOTAL &&
x.every((h: any, i: number) => typeof h === "string" && /^[0-9a-f]{64}$/.test(h) && x.indexOf(h) === i);
if (!Array.isArray(t) || t.length !== 2 || !table(t[0]) || !table(t[1])) {
throw "Signing Issue : mpc2 key's partHashes must be two tables of four distinct hashes";
}
// Two independent shares have disjoint tables (Create checks it too). A
// shared entry means one table stands in for both.
if (t[0].some((h: string) => t[1].indexOf(h) !== -1)) {
throw "Signing Issue : mpc2 key's partHashes tables overlap";
}
return [t[0].slice(), t[1].slice()];
}/**
* The chain transaction (`tx`) an mpc2 key signs on `network`, from the
* payload votePreSigned or voteCancel built. EVM: that TransactionRequest as
* it is. Tron: the plain fields plus `$i.admin.raw_data_hex`. Bitcoin (Task
* 4.3): `{tx, inputs}`. Anything else is refused.
*/ private mpc2ChainTx(network: string, p: any): any {
const code = network.toLowerCase();
const isObject = !!p && typeof p === "object" && !Array.isArray(p);
if (this.evmNetworkData(code)) {
// The CVMs check every field of it themselves (mpc2/digest.ts evmPlan).
if (!isObject) {
throw "Signing Issue : mpc2 EVM payload must be a transaction";
}
// Every node must send the CVMs the same payload, or no quorum of 3
// agrees and the payout stalls after each node has voted (review L1). A
// nonce each node fetched for itself can differ between nodes; only the
// gateway's, inside the transaction, is the same everywhere.
if (this.nonceFetchedByNode) {
throw "Signing Issue : mpc2 EVM nonce must come from the gateway's transaction, not a per-node fetch";
}
return p;
}
if (MPC2_TRON_CODES.indexOf(code) !== -1) {
// A bare {hex} is a txID nobody can check against the payout (review C2,
// the TRC20 hole #200 left open); the CVMs refuse it, and this contract
// never produces it on the mpc2 path.
if (!isObject || p.hex !== undefined) {
throw "Signing Issue : an mpc2 Tron payload is never a bare hex";
}
// Built by the submitting gateway (it needs a live reference block, which
// a contract cannot fetch) and consensus input because it sits in
// `$i.admin`, which every node receives identically. The CVMs decode it
// and check it against the plain fields; here only its form, so a CVM is
// never asked to sign without it (spec §4.3: no fallback to building it).
const admin = this.transactions.$i ? this.transactions.$i.admin : undefined;
const raw = admin ? admin.raw_data_hex : undefined;
if (typeof raw !== "string" || !/^([0-9a-f]{2}){1,4096}$/.test(raw)) {
throw "Signing Issue : an mpc2 Tron payload needs the gateway's raw_data_hex (lowercase hex)";
}
// The presign stream id (PR #356 review L4): the CVMs refuse a Tron
// payload without it, and sign at most one txID per presign while an
// earlier one could land. It must be THIS presign's, from consensus
// (tronPresignFields reads $o.presigned), or the rule keys on nothing.
const presign = p.presign;
if (typeof presign !== "string" || !/^[0-9a-f]{64}$/.test(presign) || !this.preSigned || presign !== this.preSigned.getId()) {
throw "Signing Issue : an mpc2 Tron payload needs this presign's id";
}
// One txID per presign, on the ledger (plan Task 3.3, S3): only the
// bytes a committed `tronmpcarm` armed on this presign may be signed.
// Any gateway, or one that lost its queue file, can then only submit
// those, and a round that signed and failed leaves the arm in place.
const arm = this.preSignedData ? this.preSignedData.tronMpc : undefined;
if (!arm || typeof arm !== "object" || arm.raw_data_hex !== raw || arm.txID !== utils.sha256("0x" + raw).slice(2)) {
throw "Signing Issue : mpc2 Tron signs only the bytes armed on this presign (tronmpcarm)";
}
const tx: any = {network: p.network, to: p.to, address: p.address, amount: p.amount, raw_data_hex: raw, presign};
if (p.contractAddress) {
// The CVMs require the approved fee_limit as a number and compare the
// signed one for equality (mpc2/digest.ts assertTrc20Transfer).
const feeLimit = Number(p.feeLimit);
if (!Number.isSafeInteger(feeLimit) || feeLimit <= 0) {
throw "Signing Issue : mpc2 TRC20 feeLimit malformed";
}
tx.contractAddress = p.contractAddress;
tx.feeLimit = feeLimit;
}
return tx;
}
if (this.btcParams(code) !== null) {
// Bitcoin (plan Task 4.3): exactly the Standard signer's `{tx, inputs}`,
// which btcMpc2SignTx builds from ledger data. The CVMs parse `tx`
// themselves and sign every input whose `wallet` is the request's key;
// they refuse any other field (no index list can pick a subset).
if (!isObject || Object.keys(p).length !== 2 || p.tx === undefined || p.inputs === undefined) {
throw "Signing Issue : an mpc2 Bitcoin payload is exactly {tx, inputs}";
}
if (typeof p.tx !== "string" || !/^([0-9a-f]{2})+$/.test(p.tx)) {
throw "Signing Issue : an mpc2 Bitcoin tx is lowercase hex";
}
const okInput = (i: any) =>
!!i && typeof i === "object" && !Array.isArray(i) && Object.keys(i).length === 2 &&
typeof i.wallet === "string" && /^[0-9a-f]{64}$/.test(i.wallet) &&
typeof i.value === "string" && /^[1-9][0-9]{0,15}$/.test(i.value);
if (!Array.isArray(p.inputs) || p.inputs.length === 0 || !p.inputs.every(okInput)) {
throw "Signing Issue : an mpc2 Bitcoin payload has one {wallet, value} per input";
}
return {tx: p.tx, inputs: p.inputs.map((i: any) => ({wallet: i.wallet, value: i.value}))};
}
// Solana has no mpc2 key (Ed25519).
throw `Signing Issue : mpc2 cannot sign on ${network}`;
}/**
* Why the egress agent's `{a, b}` reply to mpc2/sign is not accepted, or
* null. `a` is CVM-A's answer `{status, umid, signature, ack, ackSig}`, `b`
* CVM-B's `{status, umid, ack, ackSig}` (apps/confidentialVM/src/mpc2
* README, "sign answer"). The agent verifies each `ackSig` (plan Task 2.8);
* this checks what the contract can without Ed25519.
*/ private mpc2SignReplyRefusal(both: any, keyId: string, network: string, q: string): string | null {
const isObject = (x: any) => !!x && typeof x === "object" && !Array.isArray(x);
if (!isObject(both)) {
return "no answer from the egress agent";
}
// The agent's own refusal (`{status: 'error', error}`), which names the
// CVM and its code, e.g. `cvm-a-boot-hold` for the 9 minutes after a CVM
// boots (PR #357). Kept in the refusal so the gateway can tell a wait it
// retries from a fault; only a short code, never free text.
if (both.status === "error") {
return `egress refused (${typeof both.error === "string" && /^[a-z0-9-]{1,64}$/.test(both.error) ? both.error : "unknown"})`;
}
const parties: [any, number, string][] = [[both.a, 0, "CVM-A"], [both.b, 1, "CVM-B"]];
for (const [answer, party, who] of parties) {
// Signing is all or nothing: both CVMs must have finished the session.
if (!isObject(answer) || answer.status !== "ok") {
return `${who} refused`;
}
// An answer for another umid is another approval's signature.
if (answer.umid !== this.umid) {
return `${who} answered for another umid`;
}
const a = answer.ack;
// Each CVM acknowledges what it signed. One filed under the wrong party,
// or naming another umid, key, network or Q, is not this request's.
if (!isObject(a) || a.party !== party || a.umid !== this.umid || a.keyId !== keyId ||
a.network !== network || a.publicKey !== q || !Array.isArray(a.signatures) || a.signatures.length === 0) {
return `${who}'s acknowledgement is not for this request`;
}
}
// Both CVMs signed the same (sid, digest, r, s) for every input, or one of
// them signed something the other did not agree to.
if (JSON.stringify(both.a.ack.signatures) !== JSON.stringify(both.b.ack.signatures)) {
return "CVM-A and CVM-B acknowledged different signatures";
}
// Only CVM-A returns the chain's signed output (Task 2.5).
if (both.a.signature === undefined || both.a.signature === null) {
return "CVM-A returned no signature";
}
return null;
}/**
* The mpc2 sign payload: `{publicKey, partHashes, tx}`, plus the key
* stream's `mpcFrozen` exactly as stored whenever it has one (PR #357, the
* memory-only CVM). signingRoute refuses a frozen key before any call, so
* today the field is never sent; it is there so that a later path that does
* reach the CVMs with a frozen key (a bug, or the reviewed sweep) meets a
* CVM that refuses it (`ledger-frozen`) even after a restart made it forget
* the freeze.
*/ private mpc2Payload(wallet: any, tables: string[][], tx: any, walletId?: string): any {
return {
publicKey: wallet.publicKey,
partHashes: tables,
tx,
...(wallet.mpcFrozen !== undefined ? {mpcFrozen: wallet.mpcFrozen} : {}),
// The ledger's sweep authorisation, for this key only: the CVMs refuse
// `mpcFrozen` without it (`ledger-frozen`) and check it under their
// sweep rule (apps/confidentialVM/src/mpc2 README, section 5a).
...(this.mpc2Sweep && walletId === this.mpc2Sweep.keyId ? {sweep: this.mpc2Sweep} : {}),
};
}/** * Throws for a retired wallet (KeyHealthFix `retire`, Task 3.3): it takes * no new payout. Its coins move out by consolidation (Varnir.Consolidation), * and its purge waits on the payouts bound before it retired. */
private refuseRetiredBinding(wallet: any): void {
if (wallet && typeof wallet === "object" && wallet.retired !== undefined) {
throw "Signing Issue : the wallet is retired and takes no new payout";
}
}/** * Why a wallet may not take new coins (assignment, or a consolidation into * it), or null. Retired, frozen and purged keys take no new deposits (spec * §5.2): a purged one has no parts left, a frozen one only an unbuilt sweep * to move them. An Advanced (mpc2) key is not known to rebuild shares * behind Q until its canary signed (PR #350 review M2), so coins sent there * could be lost for good. A signed DiffConsensus proof (`diffConfirmed.sig`, * decision 2026-10-10) is the same evidence: Q's signature, made from the * nodes' parts of both shares, that every node checked before it voted and * that only Varnir.DiffConsensus writes. Either one admits the key, unless * `requireSignedProof` (Varnir.CryptoTransfer's contract data * `mpc2RequireSignedProof`, owner `mod` only, read by the caller; missing, * malformed or unreadable is off): then an UNOWNED Advanced wallet needs * the signed proof, and an unsigned proof plus a canary is no longer * enough. Why: a proof from before 2026-10-10 checked only CVM-A's parts, * and a canary passes with three nodes' parts, so such a key may lack * CVM-B's part on a node. Once `diffcon-backfill --sign` has re-proven * the pool, the switch makes a key it dropped stay out everywhere (review * M3 of PR #430). Owned wallets are not affected: their deposits must * still resolve and their coins still move. */
private poolLifecycleRefusal(state: any, requireSignedProof: boolean): string | null {
if (!state || typeof state !== "object") return "the wallet has no state";
if (state.retired !== undefined) return "the wallet is retired";
if (state.mpcFrozen !== undefined) return "the wallet is frozen";
if (state.mpcPurged !== undefined) return "the wallet is purged";
if (state.mpcProtocol !== undefined && requireSignedProof === true && (state.owner === null || state.owner === undefined) &&
!(state.diffConfirmed && state.diffConfirmed.sig)) {
return "the Advanced wallet has no signed DiffConsensus proof (mpc2RequireSignedProof)";
}
if (state.mpcProtocol !== undefined && state.mpcCanary === undefined && !(state.diffConfirmed && state.diffConfirmed.sig)) {
return "the Advanced wallet has no canary signature or signed DiffConsensus proof yet";
}
return null;
}/** * The sweep a `presigned` round is, or null when its wallet is not frozen. * Throws for a frozen wallet unless the presign is exactly a sweep: a * Varnir.Consolidation presign (sender `consolidation`) of this wallet's * own coins (`stream` is the wallet) to `mpcSweep.toAddress`, that a * GATEWAY submitted (`sweepBy`, written by Varnir.Consolidation only after * proving its submitter is a gateway: PR #416 review H1, so nobody else * can spend the sweep's signings on dust). The destination wallet rides as * `$r.sweepto`, so its owner can be checked (review L3). */
private presignSweep(walletId: any, wallet: any): any {
if (!wallet || typeof wallet !== "object" || wallet.mpcFrozen === undefined) {
return null;
}
const p = this.preSignedData || {};
if (p.sender !== "consolidation" || p.stream !== walletId) {
throw "Signing Issue : the key is frozen";
}
if (typeof p.sweepBy !== "string" || p.sweepBy.length === 0) {
throw "Signing Issue : a frozen key's sweep must be a gateway's consolidation";
}
const to = p.payload && typeof p.payload.to === "string" ? p.payload.to : "";
const dest = this.transactions.$r && this.transactions.$r.sweepto ? this.getReadOnlyStream("sweepto") : null;
return this.mpc2SweepAuthorisation(walletId, wallet, to, dest, this.transactions.$r ? this.transactions.$r.sweepto : undefined);
}/** * The checks every sweep signing shares (signing and arming), or throws: * - an mpc2 key frozen for a STALL (`mpcFrozen.kind`, PR #416 review M3): * after a strike the peer sent the bad message, and the sweep waits for * it to be replaced; a record with no kind counts as a strike; * - `mpcSweep` present and well formed: the owner's and the quorum's * decision, the only thing that may move a frozen key's coins; * - fewer than `signings` recorded in `signed`; * - not purged; the ledger halt is checked by signingRoute as for any * mpc2 signing. * Returns the sweep record, `signed` and the next index. */
private mpc2SweepRecord(wallet: any): {sweep: any; signed: any[]; attempts: any[]; signings: number; index: number}/** * The authorisation for the next sweep signing of frozen key `walletId`, * paying `toAddress`, or throws. On top of mpc2SweepRecord: * - `toAddress` is `mpcSweep.toAddress`: the destination is fixed, so a * gateway cannot point the sweep anywhere else (the CVMs check the * transaction they build against it too); * - the destination wallet (`dest`, read by id) is `mpcSweep.to` and has * NO OWNER now (PR #416 review L3): a pool wallet assigned to a user * after the authorisation must not take the sweep; the owner tops up the * sweep with a new destination instead; * - an armed attempt for this index, unused, armed less than * MPC2_SWEEP_ARM_TTL_MS ago (review M2): every run of the frozen share is * on the ledger before it happens, and dies before a restarted CVM's boot * hold ends; * - the key stream is an output of this transaction (`$o[walletId]`), so * the commit can record the signing. */
private mpc2SweepAuthorisation(walletId: any, wallet: any, toAddress: string, dest: any, destId: any): any {
if (typeof walletId !== "string" || !/^[0-9a-f]{64}$/.test(walletId)) {
throw "Signing Issue : a sweep needs the key's stream id";
}
const {sweep, signed, attempts, signings, index} = this.mpc2SweepRecord(wallet);
if (typeof toAddress !== "string" || !this.sameL1Address(toAddress, sweep.toAddress)) {
throw "Signing Issue : a frozen key signs only its sweep, to mpcSweep.toAddress";
}
if (destId !== sweep.to || !dest || typeof dest !== "object") {
throw "Signing Issue : a sweep needs its destination wallet (mpcSweep.to) as a reference";
}
if (dest.owner !== null && dest.owner !== undefined) {
throw "Signing Issue : the sweep destination has been assigned to a user since; authorise a new destination";
}
const attempt = attempts.length ? attempts[attempts.length - 1] : null;
const age = attempt ? new Date(this.cDate).getTime() - new Date(attempt.at).getTime() : NaN;
if (!attempt || attempt.index !== index || typeof attempt.umid !== "string" ||
signed.some((x: any) => x && x.attempt === attempt.umid) ||
!Number.isFinite(age) || age < 0 || age > MPC2_SWEEP_ARM_TTL_MS) {
throw "Signing Issue : the sweep attempt is not armed, or has expired (sweeparm)";
}
// Never getActivityStreams(ref) for an unloaded ref: that creates a stream.
const loaded: any = (this as any).getActivityStreams() || {};
const stream = loaded[walletId];
if (!this.transactions.$o || this.transactions.$o[walletId] === undefined || !stream || typeof stream.getState !== "function") {
throw "Signing Issue : a sweep needs the key stream as an output ($o[wallet]) to record it";
}
return {v: 1, umid: sweep.umid, keyId: walletId, network: wallet.network, toAddress: sweep.toAddress, index, signings, attempt: attempt.umid};
}/** Commit of a sweep signing: `mpcSweep.signed` gains this index and attempt, and `signedStream` names the first (purge basis `swept`). */
private recordSweepSigned(signedId: string): void {
const s = this.mpc2Sweep;
const loaded: any = (this as any).getActivityStreams() || {};
const key = loaded[s.keyId];
const state = key.getState();
const sweep = state.mpcSweep;
const signed = Array.isArray(sweep.signed) ? sweep.signed : [];
signed.push({index: s.index, attempt: s.attempt, signedStream: signedId, umid: this.umid, at: this.cDate});
sweep.signed = signed;
if (typeof sweep.signedStream !== "string") {
sweep.signedStream = signedId;
}
state.mpcSweep = sweep;
key.setState(state);
}/** * `sweeparm` vote (gateway; PR #416 review M2): records the next attempt * of a frozen key's sweep on the ledger BEFORE any CVM runs it. `$o.key` is * the frozen key. Each check, and why: * - a gateway submits it (assertMinigateSigner): the gateway decides when * to sweep, nobody else; * - the key may still be swept (mpc2SweepRecord: stall freeze, signings * left, not purged); * - no live attempt: the last one is used (a committed signing names it) * or older than MPC2_SWEEP_ARM_TTL_MS, so at most one attempt is open; * - at most MPC2_SWEEP_ATTEMPTS_PER_SIGNING attempts per authorised * signing in all: failed runs (a stalling peer) cannot repeat for ever. */
private async voteSweepArm(): Promise<boolean> {
await this.assertMinigateSigner();
// Behind the freeze flag (Adam 2026-10-09): every sweep signing needs a
// live armed attempt, so no attempt means no frozen-key sweep at all.
if (!this.mpc2FreezeEnabled()) {
throw "sweeparm: the ledger freeze is off (mpc2FreezeEnabled)";
}
const ref = this.transactions.$o ? this.transactions.$o.key : undefined;
if (!ref) {
throw "sweeparm: needs $o.key";
}
const key = this.getActivityStreams(ref);
const wallet: any = key.getState();
if (!wallet || wallet.mpcFrozen === undefined) {
throw "sweeparm: the key is not frozen";
}
const {signed, attempts, signings, index} = this.mpc2SweepRecord(wallet);
if (attempts.length >= MPC2_SWEEP_ATTEMPTS_PER_SIGNING * signings) {
throw "sweeparm: the sweep's attempts are used; the owner may top it up (frozensweep)";
}
const last = attempts.length ? attempts[attempts.length - 1] : null;
if (last) {
const used = signed.some((x: any) => x && x.attempt === last.umid);
const age = new Date(this.cDate).getTime() - new Date(last.at).getTime();
if (!used && Number.isFinite(age) && age >= 0 && age <= MPC2_SWEEP_ARM_TTL_MS) {
throw "sweeparm: an attempt is armed and still live";
}
}
this.sweepArm = {id: key.getId(), index};
return true;
}/** `sweeparm` commit: the attempt, `{umid, index, at}`. */ private async commitSweepArm(): Promise<boolean> {
const key = this.getActivityStreams(this.transactions.$o.key);
const state: any = key.getState();
const sweep = state.mpcSweep;
sweep.attempts = Array.isArray(sweep.attempts) ? sweep.attempts : [];
sweep.attempts.push({umid: this.umid, index: this.sweepArm.index, at: this.cDate});
state.mpcSweep = sweep;
key.setState(state);
this.returnToRemote({attempt: this.umid, index: this.sweepArm.index});
return true;
}/**
* `mpchalt` vote (gateway only; Task 3.3, PR #357): holds every mpc2
* signing on the ledger for a CVM's peer lockout. A CVM that holds its
* peer suspect refuses to sign, but only until it restarts, since it keeps
* nothing on disk. This node asks its own CVMs (`mpc2/status` about
* `$r.wallet`, any mpc2 key, through its egress agent) and votes yes only
* if CVM-A's or CVM-B's signed report names a lockout with this sid.
* `$o.contract` is this contract's own stream (commit writes its data). A
* second halt while one stands is refused ("already halted").
*/ private async voteMpcHalt(): Promise<boolean> {
// Behind its own flag, before anything else (Adam 2026-10-09): off, a
// gateway's mpchalt is refused and minigate pages instead.
if (!this.mpc2LedgerHaltEnabled()) {
throw "mpc2 halt: the ledger halt is off (mpc2LedgerHaltEnabled)";
}
await this.assertMinigateSigner();
if (!this.transactions.$o || !this.transactions.$o.contract) {
throw "Missing Contract Output";
}
const contract = this.getActivityStreams(this.transactions.$o.contract);
// This contract's own data is written: the stream must be its own.
if (typeof this.transactions.$contract !== "string" || this.transactions.$contract.substring(0, 64) !== contract.getId()) {
throw "Contract Not Matching";
}
const stored = this.getContractDataHelper().mpc2Halt;
if (stored !== undefined && stored !== null) {
throw "mpc2 halt: MPC signing is already halted";
}
const sid = this.transactions.$i.admin ? this.transactions.$i.admin.sid : undefined;
// The CVM's own session id (a SHA-256), the value the owner later names to clear it.
if (typeof sid !== "string" || !/^[0-9a-f]{64}$/.test(sid)) {
throw "mpc2 halt: sid must be 64 lowercase hex";
}
const keyId = this.transactions.$r ? this.transactions.$r.wallet : undefined;
const wallet = this.getReadOnlyStream("wallet");
// The status request names a key; only an mpc2 key's network and id are
// ones the CVMs' schema takes.
if (typeof keyId !== "string" || !/^[0-9a-f]{64}$/.test(keyId) || !wallet || wallet.keyMethod !== "mpc-tss" ||
wallet.mpcProtocol !== MPC2_PROTOCOL || typeof wallet.network !== "string" || !/^[A-Za-z0-9-]{1,32}$/.test(wallet.network)) {
throw "mpc2 halt: the probe must be an mpc2 key";
}
let response: any;
try {
response = await HTTP.send(
`${MPC2_EGRESS_URL}/mpc2/status`,
"POST",
[],
{umid: this.umid, network: wallet.network, keyId, keyMethod: "mpc-tss", mpcProtocol: MPC2_PROTOCOL, payload: {}},
false,
MPC2_STATUS_HTTP_TIMEOUT_S
);
} catch (e) {
throw "mpc2 halt: the egress agent did not answer";
}
const both = response ? response.data : null;
let confirmed = false;
const why: string[] = [];
// Per CVM (PR #358 review H1): the CVM that holds its peer suspect proves
// the lockout with its own verified report. Requiring both would let the
// suspect peer keep its lockout off the ledger by refusing status, until
// a restart of the honest CVM (which keeps nothing on disk) ended it.
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;
// A refused side proves nothing either way.
if (!answer || typeof answer !== "object" || answer.status !== "ok") {
why.push(`${who} refused`);
continue;
}
const report = answer.report;
// Bound to this query and filed under its own role (the agent has
// checked reportSig against the CVM's pinned evidence).
if (!report || typeof report !== "object" || answer.umid !== this.umid || report.umid !== this.umid || report.party !== party) {
why.push(`${who}'s report is for another umid or party`);
continue;
}
if (report.peerSuspect && typeof report.peerSuspect === "object" && report.peerSuspect.sid === sid) {
confirmed = true;
}
}
// Never on the gateway's word: no verified report naming this lockout,
// no halt.
if (!confirmed) {
throw `mpc2 halt: not confirmed by this node's CVMs${why.length ? ` (${why.join("; ")})` : ""}`;
}
this.mpc2HaltSid = sid;
return true;
}/** `mpchalt` commit: the halt record in contract data, from the transaction's sid (the same on every node). */
private async commitMpcHalt(): Promise<boolean> {
const cd = this.getContractDataHelper();
if (cd.mpc2Halt === undefined || cd.mpc2Halt === null) {
cd.mpc2Halt = {at: this.cDate, sid: this.transactions.$i.admin.sid, umid: this.umid};
this.setContractData(cd);
}
return true;
}/** * Throws while `state` (a presign) carries an armed mpc2 Tron transaction * and no `l1.sign`: its bytes may be signed, or even on chain, so releasing * the funds any other way could pay the user and refund them too. The * only way out is `recordlanded` (or a `presigned` commit). */
private refuseArmedPresign(state: any): void {
// >>> tenant-pays
// Stage E (review N2): a tagged presign whose reserve is settled (expired) can no longer be cancelled: its amount
// is held or released only by tenantwdrelease, never refunded twice.
if (state && state.tenantReserve && state.tenantReserve.state !== "reserved") throw "Tenants - this withdrawal's tenant reserve is settled (expired): it cannot be cancelled";
// <<< tenant-pays
if (state && state.tronMpc !== undefined && !state.signedStream) {
throw "presign has an armed mpc2 Tron transaction; refund only through recordlanded";
}
}/** * The keyless public read backends for a Tron network code, or throws. * Two independent ones where they exist (PR #360 review L1): the four * nodes share one public IP on testnet, so a throttle on one backend must * not stall every node's vote. Mainnet: TronGrid and publicnode (as * Varnir.Broadcast uses it); Nile: TronGrid and the Nile foundation's own * full node. Shasta has one. No API key is ever added here. */
private tronHostsFor(network: string): string[] {
const code = String(network || "").toLowerCase();
if (code === "trx") return ["https://api.trongrid.io", "https://tron-rpc.publicnode.com"];
if (code === "niles" || code === "trx-nile") return ["https://nile.trongrid.io", "https://api.nileex.io"];
if (code === "shasta" || code === "trx-shasta") return ["https://api.shasta.trongrid.io"];
throw `mpc2 Tron: no chain host for ${network}`;
}/** The chain name the Tron payloads use ('main', 'niles', 'shasta'), as votePreSigned's Tron branch writes it. */ private tronChainName(network: string): string {
const code = String(network || "").toLowerCase();
if (code === "niles" || code === "trx-nile") return "niles";
if (code === "shasta" || code === "trx-shasta") return "shasta";
return "main";
}/** * One POST to every backend of the network: each one's JSON object, or * null for a failure (unreachable, not JSON, an `Error` body). Never throws. */
private async tronReadAll(network: string, route: string, body: any): Promise<any[]> {
const out: any[] = [];
for (const host of this.tronHostsFor(network)) {
try {
const response = await HTTP.send(`${host}${route}`, "POST", [], body, false, 10);
const data: any = response ? response.data : null;
out.push(data && typeof data === "object" && !Array.isArray(data) && data.Error === undefined ? data : null);
} catch (e) {
out.push(null);
}
}
return out;
}/** * The backends' answer to one read, as one: null when none answered; * otherwise the first answer, after checking every other answer agrees on * what `project` picks out (the fields the decision rests on). Two * backends that disagree throw: a node never votes on a contradiction. */
private async tronReadAgreed(network: string, route: string, body: any, project: (x: any) => any): Promise<any> {
const answers = (await this.tronReadAll(network, route, body)).filter((x) => x !== null);
if (answers.length === 0) return null;
// `{}` ("not found") from one backend while another returns the
// transaction is that backend not having indexed it yet, not a
// disagreement (PR #360 re-review Q2): it is no answer for presence.
// Every backend that does return the transaction must still agree.
const found = answers.filter((x) => Object.keys(x).length !== 0);
if (found.length === 0) return {};
const first = JSON.stringify(project(found[0]));
for (const a of found) {
if (JSON.stringify(project(a)) !== first) {
throw `mpc2 Tron: the chain backends disagree on ${route}`;
}
}
return found[0];
}/** * Loads `$o.presigned` for an arm or a record, and the pool wallet on * `$r.wallet`: it must be the one bound at presign, an mpc2 key on a Tron * network. Refuses a presign already signed or still held. */
private tronMpcPresignWallet(): any {
this.preSigned = this.getActivityStreams(this.transactions.$o.presigned);
this.preSignedData = this.preSigned.getState();
if (this.preSignedData.signedStream) {
throw "Already Signed";
}
// A held presign is not signed yet, and may still be cancelled; nothing
// is armed for it until the hold is released.
this.holdSignGate(this.preSignedData.hold);
// >>> tenant-pays
// Stage E: a tagged presign whose reserve was settled as never sent (expired) is never signed or armed afterwards.
if (this.preSignedData.tenantReserve && this.preSignedData.tenantReserve.state !== "reserved") throw "Tenants - this withdrawal's tenant reserve is settled (expired): it is never signed";
// <<< tenant-pays
this.layer2TDetails.network = this.preSignedData.network;
this.layer2TDetails.token = this.preSignedData.token;
if (this.preSignedData.stream && this.transactions.$r.wallet !== this.preSignedData.stream) {
throw `Wallet changed since presign: ${this.transactions.$r.wallet} is not ${this.preSignedData.stream}`;
}
const wallet = this.getReadOnlyStream("wallet");
// Only an Advanced key on Tron signs gateway-built bytes; a Standard Tron
// key has the CVM build them (PR #354's one-per-presign rule there).
if (!wallet || wallet.keyMethod !== "mpc-tss" || wallet.mpcProtocol !== MPC2_PROTOCOL ||
MPC2_TRON_CODES.indexOf(String(wallet.network || "").toLowerCase()) === -1 ||
typeof wallet.publicKey !== "string" || !/^0[23][0-9a-f]{64}$/.test(wallet.publicKey)) {
throw "mpc2 Tron: the presign's wallet is not an mpc2 Tron key";
}
if (MPC2_TRON_CODES.indexOf(String(this.preSignedData.network || "").toLowerCase()) === -1) {
throw "mpc2 Tron: the presign is not on a Tron network";
}
return wallet;
}/** * Decodes a Tron `Transaction.raw` (raw_data_hex) strictly: canonical * varints, known fields with their wire types, each once (contracts * repeated), nothing past the end, and inside each contract only what a * TransferContract or TriggerSmartContract carries (the CVM's * decodeTronRawData, apps/confidentialVM/src/mpc2/digest.ts, without its * TronWeb re-encode: nothing it accepts can mean something it does not * read). Returns the JSON TronWeb uses. Throws a string on anything else. */
private tronDecodeRaw(hex: string): any {
const bytes = utils.arrayify("0x" + hex);
const read = (b: Uint8Array, fields: {[n: number]: string}, repeated: number[]): {[n: number]: any[]} => {
let pos = 0;
const varint = (): bigint => {
let v = BigInt(0);
for (let i = 0; i < 10; i++) {
if (pos >= b.length) throw "Tron raw data truncated";
const byte = b[pos++];
v = v | (BigInt(byte & 0x7f) << BigInt(7 * i));
if (!(byte & 0x80)) {
if (i > 0 && byte === 0) throw "Tron raw data has a non-canonical varint";
return v;
}
}
throw "Tron raw data varint too long";
};
const out: {[n: number]: any[]} = {};
while (pos < b.length) {
const k = varint();
if (k > BigInt(0xffffffff)) throw "Tron raw data field key out of range";
const field = Number(k >> BigInt(3));
const wire = Number(k & BigInt(7));
const kind = fields[field];
if (!kind) throw `Tron raw data carries an unknown field ${field}`;
if ((kind === "varint" && wire !== 0) || (kind === "bytes" && wire !== 2)) {
throw `Tron raw data field ${field} has the wrong wire type`;
}
let value: any;
if (kind === "varint") {
value = varint();
} else {
const n = varint();
if (n > BigInt(b.length - pos)) throw "Tron raw data truncated";
value = b.slice(pos, pos + Number(n));
pos += Number(n);
}
if (out[field] && repeated.indexOf(field) === -1) throw `Tron raw data repeats field ${field}`;
(out[field] = out[field] || []).push(value);
}
return out;
};
const num = (v: any): number | undefined => {
if (v === undefined) return undefined;
if (typeof v !== "bigint" || v > BigInt(Number.MAX_SAFE_INTEGER)) throw "Tron number out of range";
return Number(v);
};
const hexOf = (v: any): string | undefined => (v === undefined ? undefined : utils.hexlify(v).slice(2));
const raw = read(bytes, {1: "bytes", 4: "bytes", 8: "varint", 10: "bytes", 11: "bytes", 14: "varint", 18: "varint"}, [11]);
const contracts = (raw[11] || []).map((c: Uint8Array) => {
const m = read(c, {1: "varint", 2: "bytes", 5: "varint"}, []);
const type = num(m[1] ? m[1][0] : undefined);
const names: {[n: number]: string} = {1: "TransferContract", 31: "TriggerSmartContract"};
if (type === undefined || !names[type]) throw "Tron contract type not allowed";
if (!m[2]) throw "Tron contract has no parameter";
const any = read(m[2][0], {1: "bytes", 2: "bytes"}, []);
const url = any[1] ? utils.toUtf8String(any[1][0]) : "";
if (url !== `type.googleapis.com/protocol.${names[type]}`) throw "Tron parameter type does not match the contract type";
const body = any[2] ? any[2][0] : new Uint8Array(0);
let value: any;
if (type === 1) {
const v = read(body, {1: "bytes", 2: "bytes", 3: "varint"}, []);
value = {owner_address: hexOf(v[1] && v[1][0]), to_address: hexOf(v[2] && v[2][0]), amount: v[3] ? v[3][0] : undefined};
} else {
const v = read(body, {1: "bytes", 2: "bytes", 3: "varint", 4: "bytes", 5: "varint", 6: "varint"}, []);
// A token transfer attaches no TRX and no TRC10 token, so these fields
// never appear in the bytes TronWeb builds (proto3 omits a zero). An
// explicit one, even 0, is refused outright (PR #360 review L3): the
// CVMs' re-encode check would refuse such bytes, so the ledger must
// not arm them.
for (const [field, name] of [[3, "call_value"], [5, "call_token_value"], [6, "token_id"]] as [number, string][]) {
if (v[field]) throw `TRC20 call carries ${name} (field ${field})`;
}
value = {
owner_address: hexOf(v[1] && v[1][0]),
contract_address: hexOf(v[2] && v[2][0]),
call_value: v[3] ? num(v[3][0]) : undefined,
data: hexOf(v[4] && v[4][0]),
call_token_value: v[5] ? num(v[5][0]) : undefined,
token_id: v[6] ? num(v[6][0]) : undefined,
};
}
return {type: names[type], parameter: {value, type_url: url}, Permission_id: m[5] ? num(m[5][0]) : undefined};
});
return {
contract: contracts,
ref_block_bytes: hexOf(raw[1] && raw[1][0]),
ref_block_hash: hexOf(raw[4] && raw[4][0]),
expiration: num(raw[8] ? raw[8][0] : undefined),
timestamp: num(raw[14] ? raw[14][0] : undefined),
data: hexOf(raw[10] && raw[10][0]),
fee_limit: num(raw[18] ? raw[18][0] : undefined),
};
}/** A base58check Tron address as its 21-byte hex (41 ‖ 20 bytes), lowercase, or throws. */
private tronHexOf(address: any): string {
let decoded: Uint8Array;
try {
decoded = utils.base58.decode(String(address));
} catch (e) {
throw "mpc2 Tron: a Tron address is malformed";
}
const hex = utils.hexlify(decoded).slice(2);
const body = hex.slice(0, 42);
// 21 bytes plus a 4-byte double-SHA-256 checksum, and the 0x41 prefix.
if (hex.length !== 50 || body.slice(0, 2) !== "41" || utils.sha256(utils.sha256("0x" + body)).slice(2, 10) !== hex.slice(42)) {
throw "mpc2 Tron: a Tron address is malformed";
}
return body;
}/** * Throws unless the decoded transaction is exactly this presign's payout * from its wallet: one TransferContract of the presign's amount to its * recipient, or for a token one TriggerSmartContract calling the debited * partition's token with exactly `transfer(recipient, amount)`, no value * attached and the approved fee_limit; no memo, no permission id, a * lifetime of at most 300 s (the CVMs' TRON_MAX_LIFETIME_MS). The same * rules as the CVMs' assertNativeTransfer / assertTrc20Transfer, so the * ledger arms nothing the CVMs would refuse, and records nothing that pays * anything else. */
private tronAssertPayout(raw: any, wallet: any): void {
const owner = "41" + utils.computeAddress("0x" + wallet.publicKey).slice(2).toLowerCase();
const to = this.tronHexOf(this.preSignedData.payload ? this.preSignedData.payload.to : undefined);
const amountRaw = this.preSignedData.transaction ? this.preSignedData.transaction.amount : undefined;
if (!/^\d{1,30}$/.test(String(amountRaw))) {
throw "mpc2 Tron: the presign amount is malformed";
}
const amount = BigInt(String(amountRaw));
if (!Array.isArray(raw.contract) || raw.contract.length !== 1) {
throw "Tron transaction is not one contract";
}
const c = raw.contract[0];
// A memo is something the payout never asked for.
if (raw.data !== undefined) {
throw "Tron transaction carries a memo (data)";
}
// A permission id would sign under another permission of the account.
if (c.Permission_id !== undefined) {
throw "Tron contract carries a Permission_id";
}
// A longer-lived transaction could land after a refund (B2).
if (typeof raw.timestamp !== "number" || typeof raw.expiration !== "number" ||
raw.expiration <= raw.timestamp || raw.expiration - raw.timestamp > 300000) {
throw "Tron expiration is outside the 300 s lifetime";
}
const fields = this.tronContractFields(String(this.preSignedData.network).toLowerCase());
const v = c.parameter ? c.parameter.value : null;
if (!v) {
throw "Tron contract has no value";
}
if (!fields.contractAddress) {
if (c.type !== "TransferContract") {
throw "Tron transaction is not one TransferContract";
}
if (raw.fee_limit !== undefined) {
throw "a native Tron transfer carries a fee_limit";
}
if (v.owner_address !== owner) {
throw "Tron owner is not the wallet";
}
if (v.to_address !== to) {
throw "Tron recipient is not the approved payout";
}
if (typeof v.amount !== "bigint" || v.amount !== amount) {
throw "Tron amount is not the approved payout";
}
return;
}
if (c.type !== "TriggerSmartContract") {
throw "TRC20 transaction is not one TriggerSmartContract";
}
if (v.owner_address !== owner) {
throw "TRC20 owner is not the wallet";
}
if (v.contract_address !== String(fields.contractAddress).toLowerCase()) {
throw "TRC20 contract is not the approved token";
}
for (const k of ["call_value", "call_token_value", "token_id"]) {
if (v[k] !== undefined && v[k] !== 0) {
throw `TRC20 call carries ${k}`;
}
}
const expected = "a9059cbb" + to.slice(2).padStart(64, "0") + amount.toString(16).padStart(64, "0");
const data = String(v.data || "");
if (data.length !== expected.length || data.slice(0, 8) !== "a9059cbb") {
throw "TRC20 calldata is not exactly transfer(address,uint256)";
}
if (data.slice(8, 72) !== expected.slice(8, 72)) {
throw "TRC20 calldata pays another recipient";
}
if (data.slice(72) !== expected.slice(72)) {
throw "TRC20 calldata pays another amount";
}
if (raw.fee_limit !== Number(fields.feeLimit)) {
throw "TRC20 fee_limit is not the approved feeLimit";
}
}/** * Throws unless every node can see on chain that the armed bytes `prior` * can no longer land: the head is past their expiration plus the margin * (60 s, minigate's TRON_EXPIRY_MARGIN_MS) and the chain does not have * their txID. If it has it, the payout belongs to `recordlanded`, for good. */
private async tronAssertDead(prior: any): Promise<number> {
const network = this.preSignedData.network;
// The lowest head any backend reports: dead only when every one agrees.
const heads = (await this.tronReadAll(network, "/wallet/getnowblock", {}))
.map((n) => (n && n.block_header && n.block_header.raw_data ? Number(n.block_header.raw_data.timestamp) : NaN))
.filter((h) => Number.isFinite(h));
if (heads.length === 0) {
throw "tronmpcarm: cannot read the chain head";
}
const head = Math.min(...heads);
if (!(typeof prior.expiration === "number") || head <= prior.expiration + 60000) {
throw "tronmpcarm: the armed transaction can still land";
}
const answers = await this.tronReadAll(network, "/wallet/gettransactionbyid", {value: prior.txID});
if (answers.every((a) => a === null)) {
throw "tronmpcarm: cannot read the chain";
}
// Present on any backend (or an answer that is not a clean "absent"):
// never armed again; the payout belongs to recordlanded.
if (answers.some((a) => a !== null && Object.keys(a).length !== 0)) {
throw "tronmpcarm: the armed transaction is on chain; record it with recordlanded";
}
// How many independent backends said "absent" in this look.
return answers.filter((a) => a !== null).length;
}/** `tronmpcarm` vote: see the block comment. */
private async voteTronMpcArm(): Promise<boolean> {
await this.assertMinigateSigner();
const wallet = this.tronMpcPresignWallet();
const t = this.transactions.$i.admin ? this.transactions.$i.admin.tron : undefined;
if (!t || typeof t !== "object" || Array.isArray(t)) {
throw "tronmpcarm: $i.admin.tron {txID, raw_data_hex, expiration} is required";
}
// A first look (PR #360 review L2): `{look: <armed txID>}` records that
// the armed bytes are dead and absent on chain, so a re-arm with a single
// backend can rest on two looks at least TRON_SECOND_LOOK_MS apart
// (minigate's tronMpcStep needs the same before it rebuilds).
if (t.look !== undefined) {
const prior = this.preSignedData.tronMpc;
if (!prior || typeof prior !== "object" || t.look !== prior.txID) {
throw "tronmpcarm: a look must name the armed txID";
}
await this.tronAssertDead(prior);
this.tronArm = {look: true};
return true;
}
const raw = t.raw_data_hex;
// Lowercase hex pairs, as mpc2ChainTx requires of the same bytes later.
if (typeof raw !== "string" || !/^([0-9a-f]{2}){1,4096}$/.test(raw)) {
throw "tronmpcarm: raw_data_hex must be lowercase hex";
}
const txID = utils.sha256("0x" + raw).slice(2);
if (t.txID !== txID) {
throw "tronmpcarm: txID is not SHA-256(raw_data_hex)";
}
const decoded = this.tronDecodeRaw(raw);
if (decoded.expiration !== t.expiration) {
throw "tronmpcarm: expiration is not the bytes' own";
}
this.tronAssertPayout(decoded, wallet);
const prior = this.preSignedData.tronMpc;
if (prior !== undefined) {
if (prior && prior.txID === txID) {
throw "tronmpcarm: these bytes are already armed";
}
// Two independent "absent" reads before new bytes (L2): both backends
// in this look, or one now and a recorded first look at least
// TRON_SECOND_LOOK_MS (consensus time) before.
const absent = await this.tronAssertDead(prior);
const firstLook = prior && prior.absentSeenAt !== undefined ? new Date(prior.absentSeenAt).getTime() : NaN;
const now = new Date(this.cDate).getTime();
if (absent < 2 && !(Number.isFinite(firstLook) && now - firstLook >= TRON_SECOND_LOOK_MS)) {
throw "tronmpcarm: re-arming needs a second look (two backends, or a recorded first look 2 min before)";
}
}
// The wallet is part of the arm (PR #360 review H1): the presign then
// signs only from this wallet, on the mpc2 path, until it is signed or
// re-armed. A re-arm may name another wallet.
this.tronArm = {txID, raw_data_hex: raw, timestamp: decoded.timestamp, expiration: decoded.expiration, wallet: this.transactions.$r.wallet};
return true;
}/** `tronmpcarm` commit: the arm (or a first look on it), as committed state on the presign. */
private async commitTronMpcArm(): Promise<boolean> {
if (this.tronArm && this.tronArm.look) {
// The earliest look stands: a later one must not restart the wait.
if (this.preSignedData.tronMpc.absentSeenAt === undefined) {
this.preSignedData.tronMpc = {...this.preSignedData.tronMpc, absentSeenAt: this.cDate};
this.preSigned.setState(this.preSignedData);
}
return true;
}
this.preSignedData.tronMpc = {...this.tronArm, armedAt: this.cDate};
this.preSigned.setState(this.preSignedData);
return true;
}/** `recordlanded` vote: see the block comment. */
private async voteRecordLanded(): Promise<boolean> {
await this.assertMinigateSigner();
const wallet = this.tronMpcPresignWallet();
const arm = this.preSignedData.tronMpc;
if (!arm || typeof arm !== "object") {
throw "recordlanded: the presign has no armed mpc2 Tron transaction";
}
const t = this.transactions.$i.admin ? this.transactions.$i.admin.tron : undefined;
// Only the armed txID: any other was never approved by the ledger.
if (!t || t.txID !== arm.txID) {
throw "recordlanded: only the armed txID can be recorded";
}
// From the armed wallet only (PR #360 review H1), whose key signed it.
if (this.transactions.$r.wallet !== arm.wallet) {
throw "recordlanded: the presign is armed for another wallet (tronmpcarm)";
}
const network = this.preSignedData.network;
// Every backend that answers must agree on what the decision rests on
// (PR #360 review L1); one clean answer is enough when the other is down.
const tx = await this.tronReadAgreed(network, "/wallet/gettransactionbyid", {value: arm.txID}, (x) => ({
raw: x.raw_data_hex, sig: x.signature, ret: Array.isArray(x.ret) && x.ret[0] ? x.ret[0].contractRet : undefined,
}));
const info = await this.tronReadAgreed(network, "/wallet/gettransactioninfobyid", {value: arm.txID}, (x) => ({
id: x.id, block: x.blockNumber, result: x.result, receipt: x.receipt && typeof x.receipt === "object" ? x.receipt.result : undefined,
}));
if (tx === null || info === null) {
throw "recordlanded: cannot read the chain";
}
if (Object.keys(tx).length === 0) {
throw "recordlanded: the transaction is not on chain";
}
const raw = typeof tx.raw_data_hex === "string" ? tx.raw_data_hex.toLowerCase() : "";
// The chain's own bytes must be the armed bytes: txID = SHA-256 of them.
if (!/^([0-9a-f]{2}){1,4096}$/.test(raw) || utils.sha256("0x" + raw).slice(2) !== arm.txID || String(tx.txID).toLowerCase() !== arm.txID) {
throw "recordlanded: the chain's transaction is not the armed txID";
}
// Signed by Q, as mpc2AssertSigned checks a fresh signature: only the
// wallet's key can have paid from it.
const sig = Array.isArray(tx.signature) && tx.signature.length === 1 ? String(tx.signature[0]).toLowerCase() : "";
if (!/^[0-9a-f]{128}(00|01|1b|1c)$/.test(sig)) {
throw "recordlanded: the chain's signature is malformed";
}
const v = parseInt(sig.slice(128), 16);
let recovered = "";
try {
recovered = utils.recoverAddress("0x" + arm.txID, "0x" + sig.slice(0, 128) + (v < 27 ? v + 27 : v).toString(16));
} catch (e) {
recovered = "";
}
if (recovered !== utils.computeAddress("0x" + wallet.publicKey)) {
throw "recordlanded: the chain's signature is not Q's";
}
this.tronAssertPayout(this.tronDecodeRaw(raw), wallet);
if (info.id !== arm.txID || !(Number(info.blockNumber) > 0)) {
throw "recordlanded: the transaction is not in a block";
}
// A definite outcome only, with the two reads agreeing (minigate's
// tronTxInfoState): SUCCESS, or FAILED. Either is recorded; the confirm
// path reads the chain again and settles it (paid, or refunded as
// 'reverted' with its fee). A contradictory answer is never recorded.
const contractRet = Array.isArray(tx.ret) && tx.ret[0] ? tx.ret[0].contractRet : undefined;
const failed = info.result === "FAILED";
const receipt = info.receipt && typeof info.receipt === "object" ? info.receipt.result : undefined;
const success = contractRet === "SUCCESS" && !failed && (receipt === undefined || receipt === "SUCCESS");
const failure = failed && contractRet !== "SUCCESS" && receipt !== "SUCCESS";
if (!success && !failure) {
throw "recordlanded: the chain's answers contradict each other";
}
const code = String(network).toLowerCase();
this.tronLanded = {
// Only the chain's fields, in the shape the CVM's signed object has.
signed: {raw_data: tx.raw_data ?? null, raw_data_hex: raw, txID: arm.txID, visible: false, signature: [sig]},
wallet,
// The Tron payload votePreSigned would have built and signed.
payload: {
network: this.tronChainName(code),
to: this.preSignedData.payload.to,
address: wallet.address,
amount: this.preSignedData.transaction.amount,
...this.tronContractFields(code),
...this.tronPresignFields(),
},
};
return true;
}/**
* `recordlanded` commit: the `l1.sign` a `presigned` commit would have
* written (commitPreSigned), carrying the chain's signed transaction, and
* `landed: {txID, recordedAt}`. postProcess then emits
* `signature-generated`, and the confirm path owns the payout.
*/ private async commitRecordLanded(): Promise<boolean> {
const pre = this.preSignedData;
const landed = this.tronLanded;
this.eventData.umid = pre.umid;
this.eventData.umidActual = this.umid;
this.eventData.sender = pre.sender;
this.eventData.network = pre.network;
this.eventData.token = pre.token;
this.eventData.amount = pre.amount;
this.eventData.toAddress = pre.payload.to || "NA";
this.eventData.stream = this.transactions.$r.wallet;
this.eventData.wallet = landed.wallet.address;
this.eventData.signed = landed.signed;
this.eventData.varnirFee = pre.varnirFee;
this.eventData.delegated = pre.delegated;
this.eventData.gasHold = pre.gasHold ?? null;
this.eventData.creditCharge = pre.creditCharge ?? null;
this.eventData.metadata = pre.metadata || null;
this.eventData.origin = (this.transactions as any).metadata?.origin || null;
this.eventData.secondaryKey = pre.secondaryKey;
this.eventData.nonce = null;
this.eventData.created = this.cDate;
this.eventData.preSignedStream = this.preSigned.getId();
this.eventData.preSignedUmid = pre.umid;
this.eventData.payload = landed.payload;
this.eventData.landed = {txID: landed.signed.txID, recordedAt: this.cDate};
const signed = this.newActivityStream("l1.sign");
signed.setState(this.eventData);
this.eventData.signedStream = signed.getId();
pre.signedStream = signed.getId();
this.preSigned.setState(pre);
// Proxy dbIndex through, as commitPreSigned does.
(this.transactions as any)._dbIndex = pre._dbIndex;
return true;
}/**
* Gateway-authorised cancel of a signed EVM payout that has not landed: signs
* a 0-value self-transfer from the payout's wallet at the payout's nonce, so
* that once either transaction mines the nonce is consumed and the payout
* can never land - only then may ConfirmWithdraw refund it ('cancelled').
*
* The replacement must outbid whatever was last signed at that nonce, so
* each fee is max(prev * 1.25 + 1, min(live, 4 x cap)): the bump always
* makes a valid replacement; the gateway's live price ($i.admin, part of
* the transaction, so every node computes the same payload) may raise it,
* but only up to CANCELCAPMULTIPLE x the network cap (owner override
* first). When bump(prev) itself exceeds that 4 x cap (the payout or the
* last cancel was already priced above it), the bump deliberately wins: a
* cancel that cannot replace what is pending is worthless, and the spend
* stays bounded because there are at most MAXCANCELS cancels, each at least
* CANCEL_MIN_INTERVAL_MS (consensus time) after the last. The gas is
* Varnir's cost, booked by ConfirmWithdraw from #cancelFee. No wall clock:
* `when` is this.cDate.
*
* The cancel is bound to what was signed: the :volatile address used as
* from/to must be the address recorded on l1.sign (`wallet`), and the
* original payload's nonce must be the recorded `nonce`.
*/ private async voteCancel(): Promise<boolean> {
await this.assertMinigateSigner();
this.signedL1 = this.getActivityStreams(this.transactions.$o.signed);
const s = (this.signedL1Data = this.signedL1.getState());
if (s.confirmed) throw "Already Confirmed";
const netCode = this.canonicalNetwork(String(s.network || ""));
const evmChain = this.evmNetworkData(netCode);
if (!evmChain) throw "Cancel is EVM only";
if (!s.stream || this.transactions.$r?.wallet !== s.stream) {
throw "Wallet mismatch";
}
if (s.nonce === undefined || s.nonce === null) throw "Nonce Undefined";
const cancels = s.cancels ?? [];
if (cancels.length >= MAXCANCELS) throw "Cancel limit reached";
const last = cancels.length ? cancels[cancels.length - 1] : null;
if (last) {
// Fails closed: a `when` that does not parse is treated as too recent.
const lastMs = new Date(last.when).getTime();
if (
!Number.isFinite(lastMs) ||
new Date(this.cDate).getTime() - lastMs < CANCEL_MIN_INTERVAL_MS
) {
throw "Cancel too soon";
}
}
if (!s.payload) throw "No signed payload to cancel";
if (Number(s.payload.nonce) !== Number(s.nonce)) throw "Nonce mismatch";
const prev = cancels.length ? last.payload : s.payload;
if (!prev) throw "Last cancel has no payload";
const cap = this.getBN(
this.getContractDataHelper().gasPriceCaps?.[netCode] ?? evmChain.gasPriceCap
).mul(CANCELCAPMULTIPLE);
const pick = (p: any, live: any) => {
const bumped = this.getBN(p).mul(5).div(4).add(1);
let l = this.getBN(live || 0);
if (l.gt(cap)) l = cap;
return l.gt(bumped) ? l : bumped;
};
const vol: any = await this.getAnyStreamReadOnly(`${s.stream}:volatile`);
if (!vol?.public?.address || !vol?.private) {
this.event.emit("key-health", { id: s.stream });
throw "Check Key Health";
}
const address = vol.public.address;
if (
typeof s.wallet !== "string" ||
s.wallet.toLowerCase() !== String(address).toLowerCase()
) {
throw "Wallet address mismatch";
}
const payload: any = {
from: address,
to: address,
value: "0x0",
nonce: s.nonce,
chainId: evmChain.chainId,
// A same-EOA no-op transfer: 21000 on the constant chains; an entry in
// contract data may set more (Arbitrum's intrinsic gas is higher).
gasLimit: evmChain.gasLimits.cancel,
};
const a = this.transactions.$i.admin || {};
if (prev.gasPrice) {
payload.gasPrice = pick(prev.gasPrice, a.gas).toHexString();
} else if (prev.maxFeePerGas) {
const maxFee = pick(prev.maxFeePerGas, a.maxFeePerGas);
const prio = pick(prev.maxPriorityFeePerGas, a.maxPriorityFeePerGas);
payload.maxFeePerGas = maxFee.toHexString();
payload.maxPriorityFeePerGas = (prio.gt(maxFee) ? maxFee : prio).toHexString();
} else {
throw "No Gas Set (Legacy or EIP1559)";
}
const walletData = this.getReadOnlyStream("wallet");
const sig = await this.signWithWallet(
{
part: vol.private.part,
part2: vol.private.part2,
keyMethod: walletData.keyMethod === 'mpc-tss' ? 'mpc-tss' : 'standard',
address,
network: netCode,
walletId: s.stream,
wallet: walletData,
},
walletData.symbol,
payload
);
this.cancelPayload = payload;
this.cancelSignature = sig.signature;
return true;
}/** Appends the cancel to the payout's l1.sign stream (`cancels[]`). */
private async commitCancel(): Promise<boolean> {
const s = this.signedL1Data;
s.cancels = [
...(s.cancels ?? []),
{
umid: this.umid,
when: this.cDate,
nonce: s.nonce,
payload: this.cancelPayload,
signed: this.cancelSignature,
},
];
this.signedL1.setState(s);
return true;
}/**
* `presigned` commit (Bitcoin: btcCommitPreSigned). When a signature was
* produced, writes the `l1.sign` stream (the presign's umid and this one,
* sender, network, token, amount, toAddress, wallet, signed transaction,
* nonce, gasHold, payload, created, presign id) and sets `signedStream` on
* the presign. When `$o` names the wallet, stamps `signed = {umid, nonce,
* when}` on it (the next sign's TIMEDIFF check reads `when`).
* postProcess() emits `signature-generated` for the gateway to broadcast.
*
* @returns {Promise<any>}
* @memberof VarnirCryptoTransfer
*/ public async commitPreSigned(): Promise<any> {
if (this.btcSign) {
return this.btcCommitPreSigned();
}
const walletkeys = Object.keys(this.walletOutputsCache);
// Loop the raw tx output
if (this.signatureHex) {
// Assuming only 1 $o for now at this point
//const eventData = {} as any;
// loop wallet cache again
// not optimal this solution but shoulkd be drop in replacement
for (let i = walletkeys.length; i--;) {
//const walletCache = this.walletOutputsCache[walletkeys[i]];
//const signature = rawTxHexOutput[i];
const streamId = walletkeys[i];
// Wallet Layer 2 Management (Pending Transactions)
const outputCache = this.walletOutputsCache[streamId];
// !Warning! Only works with 1 !Warning!
this.eventData.umid = this.preSignedData.umid;
this.eventData.umidActual = this.umid;
this.eventData.sender = this.preSignedData.sender;
// A consolidation's reason (Varnir.Consolidation: consolidation,
// ceiling or sweep) rides onto the l1.sign: an internal move.
if (typeof this.preSignedData.reason === "string") {
this.eventData.reason = this.preSignedData.reason;
}
this.eventData.network = this.layer2TDetails.network;
this.eventData.token = this.layer2TDetails.token;
this.eventData.amount = this.preSignedData.amount;
this.eventData.toAddress =
outputCache.payload.toAddress || outputCache.payload.to || this.preSignedData.payload.to || "NA";
this.eventData.stream = outputCache.streamId;
this.eventData.wallet = outputCache.address;
this.eventData.signed = outputCache.sigRequest.signature;
this.eventData.varnirFee = this.preSignedData.varnirFee;
this.eventData.delegated = this.preSignedData.delegated;
this.eventData.gasHold = this.preSignedData.gasHold ?? null;
this.eventData.creditCharge = this.preSignedData.creditCharge ?? null;
this.eventData.metadata = this.preSignedData.metadata || null;
this.eventData.origin = this.transactions.metadata?.origin || null;
this.eventData.secondaryKey = this.preSignedData.secondaryKey;
this.eventData.nonce = this.nonceResponse;
this.eventData.created = this.cDate;
// Used for L2TxKnown
this.eventData.preSignedStream = this.preSigned.getId();
this.eventData.preSignedUmid = this.preSignedData.umid;
// Some networks we need to add signature back in so lets include
//const networkNeedsPayload = ['sol', 'soldev']
// Testnet has !== -1 missing! which is why it worked.
//if (networkNeedsPayload.indexOf(this.layer2TDetails.network.toLowerCase()) !== -1) {
this.eventData.payload = outputCache.payload;
//}
// Now we need to push this data into its own stream to be "locked" on
const signed = this.newActivityStream("l1.sign");
signed.setState(this.eventData);
// Add to event data the stream to be locked on to.
this.eventData.signedStream = signed.getId();
// Add this to the presigned document
this.preSignedData.signedStream = signed.getId();
this.preSigned.setState(this.preSignedData);
// A frozen key's sweep: the ledger's once-only record of this signing.
if (this.mpc2Sweep) {
this.recordSweepSigned(signed.getId());
}
}
// Proxy dbIndex through
this.transactions._dbIndex = this.preSignedData._dbIndex;
// If $o[$r.wallet] lets add signature and nonce to it
if (
this.transactions.$o &&
this.transactions.$o[this.transactions.$r.wallet]
) {
const wallet = this.getActivityStreams(this.transactions.$r.wallet);
const walletData = wallet.getState();
walletData.signed = {
umid: this.umid,
nonce: this.nonceResponse,
when: this.cDate,
};
wallet.setState(walletData);
}
}
// We may still need to do the "change" as below if they don't have partitions
return true;
}/** * After commit: emits `signature-generated` when an `l1.sign` was written * (a sign, or a Bitcoin replacement), and `signature-presigned` when only * an `l1.presign` was. */
public postProcess(territoriality: boolean, who: string): Promise<any> {
return new Promise<any>(async (resolve) => {
// An internal move (a consolidation, a ceiling move, a frozen key's
// sweep: sender `consolidation`) never credits whoever its destination
// belongs to, including a wallet assigned to a user after the move was
// queued (Adam, 2026-10-09). Its chain transaction id is known the moment
// it is signed, before any broadcast, so this node marks it in its own
// deposit record now; Varnir.Deposit treats a marked id (or the bare
// hash of a token transfer's `<hash>_<log>` id) as already handled,
// whatever order the sighting and the confirm arrive in. Best effort, as
// every postProcess write: the gateways mark the same id on broadcast.
if (this.eventData.signedStream && this.eventData.sender === "consolidation") {
for (const id of this.internalMoveIds(this.eventData)) {
try {
await HTTP.send(`${INTERNAL_MOVE_STORE}/`, "POST", null, {_id: id, consolidation: true, signedStream: this.eventData.signedStream});
} catch (e) {
// Already recorded (the gateways' own mark), or the store is
// down: Varnir.Deposit still checks the gateways' record.
}
}
}
// L2 wont have signed stream
if (this.eventData.signedStream) {
this.event.emit("signature-generated", {
signature: this.eventData,
});
}
if (this.eventData.preSignedStream && !this.eventData.signed) {
this.event.emit("signature-presigned", {
signature: this.eventData,
});
}
return resolve(true);
});
}/** * The ids an internal move's chain transaction is seen under by deposit * detection: the EVM transaction hash (keccak256 of the signed bytes), the * Tron txID, the Bitcoin txid and its one output `<txid>_0`. Lower case, as * deposit ids are. Empty when the record is not a signed move. */
private internalMoveIds(e: any): string[] {
const out: string[] = [];
if (e && e.btc && typeof e.btc.txid === "string") {
out.push(e.btc.txid.toLowerCase(), `${e.btc.txid.toLowerCase()}_0`);
} else if (e && typeof e.signed === "string" && /^0x[0-9a-fA-F]+$/.test(e.signed)) {
out.push(utils.keccak256(e.signed).toLowerCase());
} else if (e && e.signed && typeof e.signed === "object" && typeof e.signed.txID === "string") {
out.push(e.signed.txID.toLowerCase());
}
return out;
}/** * The legacy nonce endpoint, for a presigned entry that carries no * `$i.admin.nonce`. Only the four constant chains ever had one; any other * chain must be given its nonce by the gateway, and throws here (reported * as "Nonce Fetch Failed") rather than fetching from a URL for another chain. */
private nonceUrlFromName(name: string): string {
switch (name) {
case "eth":
return "http://localhost:8080/ethereum/nonce/mainnet/";
case "bnb":
return "http://localhost:8080/binance/nonce/mainnet/";
case "sep":
return "http://localhost:8080/ethereum/nonce/testnet/";
case "tbnb":
return "http://localhost:8080/binance/nonce/testnet/";
}
throw `No nonce endpoint for ${name} - the gateway must send the nonce`;
}/** * Does this transfer need approving, per the identity's own threshold? * * `requiresTreasury` is either a single raw minimum or an object keyed * `<network>.<token>`; "-1" means never, "0" means everything. Shared by * both roles that can propose - a stake-0 key and a stake-80 one - so the * two cannot drift apart on what counts as over the line. */
private overTreasuryThreshold(ownerData: any): boolean {
let treasuryMinValue = "0";
if (typeof ownerData.requiresTreasury === "string") {
// Generic minimum value
treasuryMinValue = ownerData.requiresTreasury;
} else {
// Should be object created
const lookUp = `${this.transactions.$i.owner?.network ?? "unk"}.${this.transactions.$i.owner?.token ?? "#native"
}`;
treasuryMinValue = ownerData.requiresTreasury[lookUp] ?? 0;
}
if (treasuryMinValue === "-1") {
return false;
}
const treasuryMin = this.getBN(treasuryMinValue);
// If is 0 assume they need to check everything
return (
treasuryMin.lt(this.transactions.$i.owner.amount) || treasuryMin.isZero()
);
}/** * A summary's expiresAt in ms, NaN when absent or unparseable. A summary is * LIVE while cDate is before it, the test confirm applies to the stream; a * NaN reads as expired, as it does there. */
private pendingTreasuryUntil(entry: any): number {
return entry && entry.expiresAt ? new Date(entry.expiresAt).getTime() : NaN;
}/** * The refusal for raising a new proposal, or null: a summary field * ($i.owner.to, network, token, amount) that is present but not a string or * number, or longer than TREASURYFIELDMAX; MAXLIVETREASURYPROPOSALS live * summaries on the identity; or MAXLIVETREASURYPROPOSALSPERKEY live ones * raised by `keyHash`. */
private pendingTreasuryFullRefusal(ownerData: any, keyHash: string | null): string | null {
const request = this.transactions.$i.owner;
for (const field of ["to", "network", "token", "amount"]) {
const value = request[field];
if (value === undefined || value === null) continue;
if ((typeof value !== "string" && typeof value !== "number") || String(value).length > TREASURYFIELDMAX) {
return `Treasury proposal field too long (max ${TREASURYFIELDMAX} characters)`;
}
}
const pending = ownerData && ownerData.pendingTreasury;
if (!pending || typeof pending !== "object") return null;
// Consensus clock only (this.cDate); never the node's wall clock.
const nowMs = new Date(this.cDate).getTime();
let live = 0;
let liveForKey = 0;
for (const id of Object.keys(pending)) {
const until = this.pendingTreasuryUntil(pending[id]);
if (Number.isNaN(until) || !(nowMs < until)) continue;
live++;
if (keyHash && pending[id].proposedBy === keyHash) liveForKey++;
}
if (live >= MAXLIVETREASURYPROPOSALS) {
return `Treasury proposal limit reached: ${MAXLIVETREASURYPROPOSALS} open proposals on this identity; confirm or void some, or let them expire`;
}
if (liveForKey >= MAXLIVETREASURYPROPOSALSPERKEY) {
return `Treasury proposal limit reached for this key: ${MAXLIVETREASURYPROPOSALSPERKEY} open proposals; confirm or void some, or let them expire`;
}
return null;
}/** * Drops the summaries whose expiresAt is PENDINGTREASURYGRACEMS or more in * the past, or that have none. Live summaries are never touched, and no * vote or commit reads a summary to decide anything, so this cannot change * what any later confirm, void or raise does. */
private prunePendingTreasury(state: any): void {
const pending = state && state.pendingTreasury;
if (!pending || typeof pending !== "object") return;
const nowMs = new Date(this.cDate).getTime();
for (const id of Object.keys(pending)) {
const until = this.pendingTreasuryUntil(pending[id]);
if (Number.isNaN(until) || until + PENDINGTREASURYGRACEMS <= nowMs) delete pending[id];
}
}/** * The payment's identity, as the contract itself resolves it - never as the * caller describes it. `to` is the credited stream for a transfer and the * L1 address for a withdrawal (EVM lower-cased, as sameL1Address compares). */
private repeatPaymentDetails(owner: any): {
from: string; network: string; token: string; amount: string; to: string; ref: string | null;
}/** * Well-formed entries still inside the window, newest REPEATCAP kept. * An entry stamped later than nowMs is kept: cDate is per-transaction and * need not be monotonic across origin nodes, and dropping it would open * the very gap this guard closes. */
private pruneRecentPayments(list: any, nowMs: number): Array<{fp: string; umid: string; at: number}/** The newest live entry in `list` with fingerprint `fp`, or null. */
private findRecentRepeat(list: any, fp: string, nowMs: number): {fp: string; umid: string; at: number}/** * The guard's vote-phase decision: a refusal string, or null to let the * payment through (staging this.repeatRecord for commit). Owner-only * override is checked BEFORE the match, so a delegated key learns its * repeat:true had no effect even when nothing matched. */
private repeatGuardVote(owner: any, ownerData: any): string | null {
const input = this.transactions.$i.owner;
if (input.repeat !== undefined && typeof input.repeat !== "boolean") {
return "Invalid repeat flag";
}
if (
input.ref !== undefined &&
input.ref !== null &&
(typeof input.ref !== "string" || input.ref.length === 0 || input.ref.length > REPEATREFMAX)
) {
return "Invalid payment ref";
}
// >>> owner-gate
if (input.repeat === true && !this.isSingleOwnerKey(owner)) {
return "Repeat override needs the owner key";
}
// <<< owner-gate
if (input.repeat === true && !this.hasAuthorityStake(100, owner)) {
return "Repeat override needs the owner key";
}
const nowMs = new Date(this.cDate).getTime();
const fp = this.repeatFingerprint(this.repeatPaymentDetails(owner));
if (input.repeat !== true) {
const prior = this.findRecentRepeat(ownerData.recentPayments, fp, nowMs);
if (prior) return this.repeatRefusal(prior);
}
this.repeatRecord = {fp, umid: this.umid, at: nowMs};
return null;
}/** Writes the staged record onto `state`, pruned against the record's own instant. */
private withRecentPayment(state: any): void {
if (!this.repeatRecord || !state) return;
const next = this.pruneRecentPayments(state.recentPayments, this.repeatRecord.at);
next.push(this.repeatRecord);
state.recentPayments = next.slice(-REPEATCAP);
}/** * Refuses to HOLD an on-ledger transfer that does not name its recipient * as a bare identity stream id on $o.to. The proposal stores that exact * value and the confirm must name it again, character for character, so a * proposal must never be raised from anything else - otherwise it is stored * with no recipient (or one no confirm can match) and can never execute. * Null for anything that is not a transfer. */
private heldTransferRecipientRefusal(): string | null {
if (this.transactions.$entry !== "transfer") {
return null;
}
const to = this.transactions.$o?.to;
const stream = to && typeof to === "object" ? to.$stream : to;
if (typeof stream !== "string" || !/^[0-9a-f]{64}$/.test(stream)) {
return "Held transfer needs its recipient on $o.to as a bare identity stream id";
}
return null;
}/** * The label on the authority that signed this transaction - "treasury", * "verifier", "secondary", "read" - or null if it cannot be matched. * * Stake alone cannot separate a dual-status key from a verify-only one: * both hold 80, because both have to clear the same gate to confirm. The * label is what distinguishes them, and Varnir.Keys writes it. */
private signingKeyLabel(owner: any): string | null {
const hash = this.signingKeyHash(owner);
if (!hash) {
return null;
}
const authority = owner
.getAuthorities()
.find((candidate: any) => candidate.hash === hash);
const label = authority?.label;
return label ? String(label).toLowerCase().trim() : null;
}/** * The hash of the key that signed for this identity, as Varnir.Keys reads * it - `sigs` is keyed by stream id, and a Varnir transaction carries one * signature per input. * * This is what makes "cannot verify your own" enforceable at all: the * identity is the same on both halves of a propose/confirm pair, so only * the KEY tells them apart. */
private signingKeyHash(owner: any): string | null {
const currentAuth = (this as any).sigs?.[owner.getId()];
if (!currentAuth) {
return null;
}
const keys = Object.keys(currentAuth);
return keys.length ? keys[0] : null;
}/** * Exactly one key signed for `activity` in this transaction, and it is a live owner key: stake exactly 100, not * expired, not labelled read, offledger or verifier. The owner-only gates test this as well as hasAuthorityStake(100), * because that SUMS the stake of every key that signed, and Activeledger accepts several signatures for one input * (permissionsChecker checkMultiSignature): two stake-80 co-sign keys signing together reach 160 * (docs/tenancy/legacy-read-key-audit.md). Reads only this.sigs and the authorities already loaded: no stream read. */
private isSingleOwnerKey(activity: any): boolean {
const signed = (this as any).sigs && (this as any).sigs[activity.getId()];
const hashes = signed ? Object.keys(signed) : [];
if (hashes.length !== 1) return false;
const a = (activity.getAuthorities() || []).find((x: any) => x.hash === hashes[0]);
if (!a || a.stake !== 100) return false;
// As the engine's isAuthorityExpired and Swap's liveAuthority: `expire: null` (read as the epoch) is expired.
if (a.expire !== undefined) {
const t = new Date(a.expire).getTime();
if (Number.isNaN(t) || !(t > new Date(this.cDate).getTime())) return false;
}
const label = a.label ? String(a.label).toLowerCase().trim() : null;
return label !== "read" && label !== "offledger" && label !== "verifier";
}/** * Increment the per-asset spend counter for a governed (agent) signing key, * written onto this.ownerState so it rides the balance-debit setState in the * calling commit path - no extra stream write, no extra consensus round * (design §4.4). * * The tumbling-window roll uses this.cDate, the per-transaction CONSENSUS * timestamp (identical on every node), so it computes the same window on the * whole cluster and cannot desync consensus. It recomputes the same roll * vote() used to CHECK the cap; the check is point-in-time only and this is * what persists it. NEVER Date.now()/new Date(). * * A key with no policy, or an asset with no periodCap rule, is a no-op, so * ungoverned keys are left completely untouched. * * A co-signed confirm counts against the key that PROPOSED the spend * (the proposal's proposedBy), not the key confirming it: the co-signer is * approving that agent's own request, so it is the agent's allowance being * spent. Counting it against the confirmer meant co-signed spends never * reached the proposing agent's periodCap. */
private bumpAgentUsage(): void {
const proposedBy = this.approved ? this.approved.getState()?.proposedBy : null;
const usageKeyHash =
proposedBy ||
this.signingKeyHash(this.getActivityStreams(this.transactions.$i.owner));
if (!usageKeyHash || !this.ownerState) {
return;
}
const usagePolicy =
this.ownerState.restrictions?.[usageKeyHash]?.policy ?? null;
if (!usagePolicy || !usagePolicy.rules) {
return;
}
const usageNet = this.transactions.$i.owner.network;
const usageTok = this.transactions.$i.owner.token || "#native";
let usageRule: any = null;
for (const ruleKey of Object.keys(usagePolicy.rules)) {
const sep = ruleKey.indexOf(":");
if (
ruleKey.slice(0, sep).toLowerCase() ===
String(usageNet).toLowerCase() &&
ruleKey.slice(sep + 1).toLowerCase() === String(usageTok).toLowerCase()
) {
usageRule = usagePolicy.rules[ruleKey];
break;
}
}
if (
!usageRule ||
usageRule.periodCap == null ||
usageRule.windowMs == null
) {
return;
}
const usageAssetKey = `${String(usageNet).toLowerCase()}:${String(
usageTok
).toLowerCase()}`;
const usageTxTime = new Date(this.cDate).getTime();
if (!this.ownerState.agentUsage) {
this.ownerState.agentUsage = {};
}
if (!this.ownerState.agentUsage[usageKeyHash]) {
this.ownerState.agentUsage[usageKeyHash] = {};
}
const prior = this.ownerState.agentUsage[usageKeyHash][usageAssetKey] ?? {
windowStart: usageTxTime,
spent: "0",
};
let windowStart = prior.windowStart;
let spent = this.getBN(prior.spent);
if (usageTxTime - windowStart >= Number(usageRule.windowMs)) {
windowStart = usageTxTime;
spent = this.getBN(0);
}
this.ownerState.agentUsage[usageKeyHash][usageAssetKey] = {
windowStart,
spent: spent.add(this.transactions.$i.owner.amount).toString(),
};
}/** * The presign half of a Standard Tron sign payload. Tron has no nonce, and * each gateway retry of a presign is a new umid: the confidentialVM used to * build a new transaction for every umid, so a round that failed after * signing left a valid signed transaction that could land beside the * retry's. With the presign id the CVM keeps one transaction per presign * and re-signs those bytes until they expire (confidentialVM * src/tron-presign-cache.ts). The id is the same on every node, as the * CVM's payload match requires. */
private tronPresignFields(): {presign: string}/** * The contract half of a Tron sign payload: the TRC20 address derived from * the debited partition (never the caller's), and for a token its fee_limit - * the chain-enforced ceiling on TRX burned for energy, i.e. the figure the * presign hold was sized with. A native send has neither. */
private tronContractFields(networkType: string): {contractAddress: string | null; feeLimit?: string}/** * The native gas a withdrawal holds from its sender at presign, from trusted * inputs only: the per-network constants above, or the owner's own `mod` * overrides (gasPriceCaps / tronFeeLimits in contract data). Never a caller * field. Throws for a network with no hold defined - fails closed. */
private computeGasHold(network: string, token: string): {amount: string; gasLimit?: number; maxFeePerGas?: string; l1FeeCap?: string; feeLimit?: string}/**
* One spelling per network, for comparing two that came from different
* places. The ledger's own code ("TRX-NILE") and the pregen pool's
* ("niles") both name Tron Nile; neither is more correct, they just have to
* be comparable. Lower-cases, and folds the Tron Nile and Shasta spellings.
*/ private canonicalNetwork(network: string): string {
switch (network.toLowerCase()) {
case 'trx-nile':
case 'niles':
return 'niles';
case 'trx-shasta':
case 'shasta':
return 'shasta';
default:
return network.toLowerCase();
}
}/** * The L1 contract for an L2 token partition, derived from the partition * key alone: null for `#native`; on `sol` a fixed USDC / USDT mint (other * tokens, and every `soldev` token, are refused); elsewhere the key must be * 40-64 hex characters and comes back as `0x<hex>` (EVM) or `41<hex>` * (Tron). `defaultValue` - the caller's own contract address - is never * used. Throws for anything else. */
private networkTokenToContract(network: string, token: string, defaultValue: string | null): string | null {
// A native transfer moves the chain's OWN asset, so there is no contract -
// null, never the caller's value.
//
// This returned `defaultValue` until 2026-09-05, and that was a theft
// primitive: `defaultValue` is the caller's own `$i.owner.contractAddress`,
// and `token` defaults to '#native' when the caller simply omits it. So a
// user with a small native balance could name any ERC20/TRC20 contract,
// have the pooled wallet sign `transfer(attacker, amount)` against it, and
// be debited only their native partition. 0.02 ETH debited, 2e16 base
// units of any token sent. The comment below about not trusting
// defaultValue was true of the token path and false of this one.
if (token === '#native') {
return null;
}
const key = token.trim();
const chain = network.toLowerCase();
// Solana is the one chain the token registry cannot serve. SPL mints are
// base58 - case-significant, and not hex - while the registry only accepts
// lowercase hex (Varnir.TokenRegistry's ADDRESS_PATTERN). An SPL mint
// therefore cannot round-trip through a partition key: lowercasing one
// does not fail, it silently yields a DIFFERENT but entirely valid mint,
// which is the worst possible outcome here. So Solana keeps exactly the
// behaviour it had before address keys, and gains nothing until the
// registry can store a case-preserving address.
if (chain === 'sol') {
switch (key.toLowerCase()) {
case 'usdc':
return 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
case 'usdt':
return 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB';
}
throw `Unknown token ${token} on ${network} network`;
}
if (chain === 'soldev') {
// Same reasoning as the symbol-keyed case below: this used to return the
// caller's own mint, so a devnet caller could debit one SPL partition and
// have the wallet sign a transfer of a different mint entirely. There is
// no safe source for it - the registry cannot hold a base58 mint - so it
// fails loudly rather than trusting the request.
throw `Unsupported SPL token ${token} on ${network} - Solana tokens cannot be added through the token registry yet`;
}
// Everywhere else the partition key IS the L1 contract address, normalised
// to lowercase hex with no prefix, so the chain's own spelling is derived
// from the key rather than looked up in a table of the two tokens someone
// happened to hardcode. A token added through the registry after this code
// shipped just works.
//
// defaultValue - the address the CALLER supplied - is deliberately not
// consulted. Trusting it would let a caller debit one token's balance
// while moving a different asset out of the pooled wallet, which is a real
// theft primitive and was the behaviour on every testnet before this.
const bare = key.toLowerCase().startsWith('0x') ? key.slice(2) : key;
if (!/^[0-9a-f]{40,64}$/.test(bare.toLowerCase())) {
// A symbol-keyed partition predates address keys. It cannot be resolved
// to a contract safely - there is no longer a table to look it up in,
// and guessing would move the wrong asset - so it fails loudly. A
// stranded balance can be migrated; a wrong transfer cannot be undone.
throw `Token partition ${token} on ${network} is not a contract address`;
}
switch (chain) {
case 'trx':
case 'trx-nile':
case 'niles':
case 'trx-shasta':
case 'shasta':
// TronWeb accepts the 41-prefixed hex form as well as base58, and the
// rest of this repo already handles Tron addresses that way - l1-relay
// matches the Nile TestUSDT in exactly this form.
return '41' + bare.toLowerCase();
default:
return '0x' + bare.toLowerCase();
}
}/** * True when the key that signed for the owner is not the stake-100 key. * Recorded on the presign as `secondaryKey`. Throws "No Owner Found" when * the owner is not loaded. */
private isSecondary(): boolean {
if (this.owner) {
const currentAuth = (this as any).sigs[this.owner.getId()];
// We will only have 1 signature
const currentAuthKeys = Object.keys(currentAuth);
const authority = this.owner.getAuthorities().find((authority) => {
return authority.hash === currentAuthKeys[0];
});
if (authority.stake !== 100) {
return true;
} else {
return false;
}
}
throw "No Owner Found";
}/** This contract's own data (`getContractData().data`), or {} when unset. */ private getContractDataHelper() {
return this.getContractData().data ?? {};
}/** The chains known before contract data existed. Returned fresh, never shared. */
private evmConstants(): {[code: string]: any}/** Codes of the non-EVM chains, in every spelling a contract sees. Never an `evmNetworks` key. */
private evmNonEvmCodes(): string[] {
return ["trx", "trx-nile", "niles", "trx-shasta", "shasta", "sol", "soldev"];
}/** This contract's stored `evmNetworks` map ({} when unset). Throws when it is not an object. */ private evmStoredNetworks(): {[code: string]: any}/** * The chain facts for `code` (any casing of the canonical or ledger code), * with `code` set to the lower-case key; null when `code` is not an EVM chain * this contract knows. Throws when the stored entry for it is malformed. */
private evmNetworkData(code: string): any | null {
const raw = String(code === undefined || code === null ? "" : code);
// ASCII only, checked BEFORE lower-casing: toLowerCase folds some non-ASCII
// letters onto ASCII ones (the Kelvin sign U+212A becomes "k"), which would
// let a look-alike spelling reach a real chain's entry.
if (!/^[A-Za-z0-9-]+$/.test(raw)) {
return null;
}
const key = raw.toLowerCase();
if (this.evmNonEvmCodes().indexOf(key) !== -1) {
return null;
}
const stored = this.evmStoredNetworks();
if (Object.keys(stored).indexOf(key) !== -1) {
this.assertEvmNetworkEntry(key, stored[key]);
if (stored[key].enabled === true) {
return {...stored[key], code: key};
}
}
const constants = this.evmConstants();
if (Object.keys(constants).indexOf(key) !== -1) {
return {...constants[key], code: key};
}
return null;
}/** evmNetworkData, failing closed. */
private requireEvmNetwork(code: string): any {
const found = this.evmNetworkData(code);
if (!found) {
throw `Unknown EVM network ${code}`;
}
return found;
}/** * The `mod` validator for a whole `evmNetworks` map. Absent (undefined/null) * leaves the stored map alone. One bad field refuses the whole write. */
private assertEvmNetworks(value: any): void {
if (value === undefined || value === null) {
return;
}
if (typeof value !== "object" || Array.isArray(value)) {
throw "evmNetworks must be an object keyed by canonical network code";
}
const byChainId: {[chainId: string]: string} = {};
for (const code of Object.keys(value)) {
this.assertEvmNetworkEntry(code, value[code]);
const chainId = String(value[code].chainId);
if (Object.keys(byChainId).indexOf(chainId) !== -1) {
throw `evmNetworks: chain id ${chainId} is used by both ${byChainId[chainId]} and ${code}`;
}
byChainId[chainId] = code;
}
const constants = this.evmConstants();
for (const code of Object.keys(constants)) {
const chainId = String(constants[code].chainId);
if (Object.keys(byChainId).indexOf(chainId) !== -1 && byChainId[chainId] !== code) {
throw `evmNetworks.${byChainId[chainId]}: chain id ${chainId} belongs to ${code}`;
}
}
}/** One `evmNetworks` entry, against this contract's evmFieldSpec. */
private assertEvmNetworkEntry(code: string, entry: any): void {
if (typeof code !== "string" || !/^[a-z][a-z0-9-]{1,15}$/.test(code)) {
throw `evmNetworks: ${code} is not a canonical network code`;
}
if (this.evmNonEvmCodes().indexOf(code) !== -1) {
throw `evmNetworks: ${code} is not an EVM network`;
}
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
throw `evmNetworks.${code} must be an object`;
}
const spec = this.evmFieldSpec();
const fields = Object.keys(entry);
for (const field of fields) {
if (spec.required.indexOf(field) === -1 && spec.optional.indexOf(field) === -1) {
throw `evmNetworks.${code}.${field} is not a field this contract uses`;
}
}
for (const field of spec.required) {
if (fields.indexOf(field) === -1) {
throw `evmNetworks.${code}.${field} is required`;
}
}
if (typeof entry.ledger !== "string" || !/^[A-Za-z][A-Za-z0-9-]{1,15}$/.test(entry.ledger) || entry.ledger.toLowerCase() !== code) {
throw `evmNetworks.${code}.ledger must spell ${code} in the ledger's own casing`;
}
if (typeof entry.chainId !== "number" || !Number.isSafeInteger(entry.chainId) || entry.chainId <= 0) {
throw `evmNetworks.${code}.chainId must be a positive integer`;
}
if (typeof entry.enabled !== "boolean") {
throw `evmNetworks.${code}.enabled must be true or false`;
}
const constants = this.evmConstants();
if (Object.keys(constants).indexOf(code) !== -1 &&
(entry.ledger !== constants[code].ledger || entry.chainId !== constants[code].chainId)) {
throw `evmNetworks.${code} must keep ledger code ${constants[code].ledger} and chain id ${constants[code].chainId}`;
}
if (fields.indexOf("rpc") !== -1) {
const rpc = entry.rpc;
if (!Array.isArray(rpc) || rpc.length < 1 || rpc.length > 4) {
throw `evmNetworks.${code}.rpc must list 1 to 4 URLs`;
}
for (const url of rpc) {
if (
typeof url !== "string" ||
url.length > 200 ||
!/^https:\/\/[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+(:[0-9]{1,5})?(\/[A-Za-z0-9._~-]+)*\/?$/.test(url)
) {
throw `evmNetworks.${code}.rpc: ${url} is not a plain https URL`;
}
// Contract data is public: a keyed provider URL (Alchemy /v2/<key>,
// Infura /v3/<key>, QuickNode /<token>/) must never land here.
const urlPath = url.slice(8).indexOf("/") === -1 ? "" : url.slice(8 + url.slice(8).indexOf("/"));
if (/[A-Za-z0-9_-]{24,}/.test(urlPath)) {
throw `evmNetworks.${code}.rpc: ${url} looks like it carries an API key`;
}
}
}
if (fields.indexOf("gasLimits") !== -1) {
const limits = entry.gasLimits;
if (!limits || typeof limits !== "object" || Array.isArray(limits)) {
throw `evmNetworks.${code}.gasLimits must be {native, token, cancel}`;
}
const names = Object.keys(limits);
if (names.length !== 3 || names.indexOf("native") === -1 || names.indexOf("token") === -1 || names.indexOf("cancel") === -1) {
throw `evmNetworks.${code}.gasLimits must be {native, token, cancel}`;
}
for (const name of names) {
const units = limits[name];
if (typeof units !== "number" || !Number.isSafeInteger(units) || units < 21000 || units > 5000000) {
throw `evmNetworks.${code}.gasLimits.${name} must be an integer from 21000 to 5000000`;
}
}
}
for (const field of ["gasPriceCap", "l1FeeCap"]) {
if (fields.indexOf(field) !== -1 && (typeof entry[field] !== "string" || !/^[1-9][0-9]{0,29}$/.test(entry[field]))) {
throw `evmNetworks.${code}.${field} must be a positive integer string (wei)`;
}
}
}/** * presign, Bitcoin: intent only (no wallet is bound; the gateway picks * inputs at signing time). The recipient is decoded for this network and * normalised in place, so the hold, the repeat key and the presign record * all see one spelling. The hold is the speed's fee-rate cap times the * reference payout size for this recipient type, from contract data only. */
private btcPreSignHold(): {amount: string; speed: string; feeRateCap: number; referenceVbytes: number; recipientType: string}/** A Bitcoin wallet named in $r (label = its id), on this network, with its key. */
private btcReadWallet(id: any, code: string): any {
if (typeof id !== "string" || !/^[0-9a-f]{64}$/.test(id) || !this.transactions.$r || this.transactions.$r[id] !== id) {
throw "Bitcoin: every wallet must be a read-only reference";
}
const w = this.getReadOnlyStream(id);
if (!w || w.network !== code || typeof w.utxoBook !== "string" || typeof w.pubkey !== "string" || typeof w.address !== "string") {
throw `Bitcoin: ${id} is not a Bitcoin wallet on ${code}`;
}
// Advanced Bitcoin wallets (plan Task 4.3) sign through mpc2 only. The
// route comes from the key's own state (signingRoute), which also refuses
// an mpcProtocol on a Standard key (its part must never reach `/sign` as a
// whole key), a frozen or purged key, the ledger's mpc2 halt and, in
// production, mpc-tss while mpc2 is off. An old #200 key ("legacy-mpc")
// has no Bitcoin signer at all.
if (w.keyMethod === "mpc-tss" || w.mpcProtocol !== undefined) {
if (this.signingRoute(w, id) !== "mpc2") {
throw "Bitcoin: only mpc2 (cggmp24) Advanced wallets can sign Bitcoin";
}
// The Bitcoin code reads Q as `pubkey` (witnesses, the book address);
// mpc2Sign sends `publicKey`. Create stores both, equal: two values mean
// nobody can say which key the coins are locked to.
if (w.pubkey !== w.publicKey) {
throw "Bitcoin: an Advanced wallet's pubkey must equal its publicKey";
}
// Create makes Advanced Bitcoin wallets as deposit wallets only: change
// must stay spendable by any payout, and a payout may spend inputs of
// at most one Advanced wallet (btcSignTx).
if (w.role !== "deposit") {
throw "Bitcoin: an Advanced wallet is a deposit wallet, never a change wallet";
}
}
return w;
}/** The UTXO book `id` of `walletId`, loaded (writable) by this transaction. */
private btcLoadBook(id: any, walletId: string, wallet: any, code: string): {stream: any; state: any}/**
* presigned, Bitcoin (spec §8.2): the gateway names the inputs, the change
* wallet and a fee rate in `$i.admin.btc = {covers, inputs: [{wallet, book,
* outpoint}], change?: {wallet, book}, feeRate}`; everything else comes from
* the ledger. Each input must be `spendable` in its wallet's book (never
* locked, pending or uncredited). The transaction is rebuilt here, its fee
* worked out from book values, the rate held to the speed's cap, and the
* VM's signed result checked against what was built.
*/ private async btcVotePreSigned(): Promise<boolean> {
const btcNet = this.requireBtcNetwork(this.layer2TDetails.network);
const code = btcNet.code;
const presign = this.preSignedData;
const hold = presign.gasHold;
if (presign.token !== "#native" || !hold || typeof hold.speed !== "string" || typeof hold.referenceVbytes !== "number") {
throw "Bitcoin: the presign carries no Bitcoin hold";
}
const req = this.transactions.$i.admin ? this.transactions.$i.admin.btc : undefined;
if (!req || typeof req !== "object") {
throw "Bitcoin: presigned needs $i.admin.btc";
}
// One payout per transaction until batching (spec §5.6) is built.
if (!Array.isArray(req.covers) || req.covers.length !== 1 || req.covers[0] !== this.preSigned.getId()) {
throw "Bitcoin: covers must name exactly this presign";
}
if (!Array.isArray(req.inputs) || req.inputs.length < 1 || req.inputs.length > btcNet.maxInputs) {
throw `Bitcoin: a payout spends 1 to ${btcNet.maxInputs} inputs`;
}
const cap = btcNet.feeRateCapSatVb[hold.speed];
if (typeof req.feeRate !== "number" || !Number.isInteger(req.feeRate) || req.feeRate < 1 || req.feeRate > cap) {
throw `Bitcoin: feeRate must be a whole sat/vB from 1 to ${cap}`;
}
const wallets: {[id: string]: any} = {};
const books: {[id: string]: any} = {};
const inputs: {outpoint: string; wallet: string; book: string; value: string}[] = [];
let sumIn = 0n;
for (const i of req.inputs) {
if (!i || typeof i !== "object") {
throw "Bitcoin: bad input";
}
this.btcParseOutpoint(i.outpoint);
const wallet = wallets[i.wallet] || this.btcReadWallet(i.wallet, code);
wallets[i.wallet] = wallet;
const book = books[i.book] || this.btcLoadBook(i.book, i.wallet, wallet, code);
books[i.book] = book;
const entry = book.state.entries ? book.state.entries[i.outpoint] : undefined;
if (!entry || entry.state !== "spendable") {
throw `Bitcoin: input ${i.outpoint} is not spendable`;
}
if (typeof entry.value !== "string" || !/^[1-9][0-9]{0,15}$/.test(entry.value)) {
throw "Bitcoin: UTXO book is malformed";
}
sumIn += BigInt(entry.value);
inputs.push({outpoint: i.outpoint, wallet: i.wallet, book: i.book, value: entry.value});
}
// The recipient and amount come from the presign, never from $i.
const recipient = this.btcDecodeAddress(code, presign.payload ? presign.payload.to : undefined);
if (typeof presign.amount !== "string" || !/^[1-9][0-9]{0,15}$/.test(presign.amount)) {
throw "Bitcoin: presign amount is malformed";
}
const amount = BigInt(presign.amount);
const rate = BigInt(req.feeRate);
const withChange = this.btcEstimateVsize(inputs.length, [recipient.type, "p2wpkh"]);
const changeValue = sumIn - amount - rate * BigInt(withChange);
let change: {address: string; value: string} | null = null;
let changeWallet: any = null;
if (changeValue >= this.btcDustThreshold("p2wpkh")) {
const c = req.change;
if (!c || typeof c !== "object") {
throw "Bitcoin: this payout needs a change wallet";
}
const w = wallets[c.wallet] || this.btcReadWallet(c.wallet, code);
if (w.role !== "change") {
throw "Bitcoin: change must go to a change wallet";
}
// This node must hold the change wallet's key, or the change is
// unspendable (security review H2).
await this.btcKeyPart(c.wallet, w);
const book = books[c.book] || this.btcLoadBook(c.book, c.wallet, w, code);
books[c.book] = book;
change = {address: w.address, value: changeValue.toString()};
changeWallet = {wallet: c.wallet, book: c.book};
}
const built = this.btcBuildPayoutTx(code, inputs.map((i) => i.outpoint), [{address: recipient.address, value: presign.amount}], change);
const fee = sumIn - built.totalOut;
const vsize = BigInt(built.estimatedVsize);
if (fee < rate * vsize) {
throw "Bitcoin: inputs do not cover the payout and its fee";
}
// Dust change rounded into the fee must not push the rate over the cap.
const paidRate = (fee + vsize - 1n) / vsize;
if (paidRate > BigInt(cap)) {
throw `Bitcoin: fee rate ${paidRate} sat/vB is over the ${hold.speed} cap ${cap}`;
}
const assembled = await this.btcSignTx(code, built, inputs, wallets);
const outputs: any[] = [{vout: 0, address: recipient.address, type: recipient.type, value: presign.amount, role: "recipient", covers: req.covers[0]}];
if (change) {
outputs.push({vout: 1, address: change.address, type: "p2wpkh", value: change.value, role: "change", wallet: changeWallet.wallet, book: changeWallet.book});
}
const refFee = rate * BigInt(hold.referenceVbytes);
const holdAmount = BigInt(hold.amount);
// Never above the hold, nor above the real fee (security review L2).
let userFee = refFee < holdAmount ? refFee : holdAmount;
if (fee < userFee) {
userFee = fee;
}
this.btcSign = {
txid: built.txid,
hex: assembled.hex,
unsignedHex: built.unsignedHex,
covers: req.covers.slice(),
inputs,
outputs,
books,
vsize: built.estimatedVsize,
fee: fee.toString(),
feeRate: req.feeRate,
// The user's share at this rate (spec §5.2), never above the hold;
// ConfirmWithdraw settles it from the rate that actually confirms.
userFees: {[req.covers[0]]: userFee.toString()},
speed: hold.speed,
address: wallets[inputs[0].wallet].address,
};
this.signatureHex = assembled.hex;
return true;
}/** * presigned commit, Bitcoin: the l1.sign record, every input `locked` to it * and the change output `pending` in the change book (spec §8.2 step 7). */
private btcCommitPreSigned(): boolean {
const s = this.btcSign;
const signed = this.newActivityStream("l1.sign");
const signedId = signed.getId();
this.eventData = {
umid: this.preSignedData.umid,
umidActual: this.umid,
sender: this.preSignedData.sender,
network: this.layer2TDetails.network,
token: this.layer2TDetails.token,
amount: this.preSignedData.amount,
toAddress: s.outputs[0].address,
stream: s.inputs[0].wallet,
wallet: s.address,
signed: s.hex,
varnirFee: this.preSignedData.varnirFee,
delegated: false,
gasHold: this.preSignedData.gasHold ?? null,
creditCharge: this.preSignedData.creditCharge ?? null,
metadata: this.preSignedData.metadata || null,
origin: (this.transactions as any).metadata?.origin || null,
secondaryKey: this.preSignedData.secondaryKey,
created: this.cDate,
preSignedStream: this.preSigned.getId(),
preSignedUmid: this.preSignedData.umid,
payload: {tx: s.unsignedHex, inputs: s.inputs.map((i: any) => ({wallet: i.wallet, value: i.value}))},
btc: {
txid: s.txid,
covers: s.covers,
inputs: s.inputs,
outputs: s.outputs,
vsize: s.vsize,
fee: s.fee,
feeRate: s.feeRate,
userFees: s.userFees,
speed: s.speed,
kind: "payout",
created: this.cDate,
// Earlier versions after a bump or cancel (btcCommitReplace).
history: [],
cancels: [],
},
};
signed.setState(this.eventData);
this.eventData.signedStream = signedId;
for (const i of s.inputs) {
const entry = s.books[i.book].state.entries[i.outpoint];
entry.state = "locked";
entry.lockedBy = signedId;
}
for (const o of s.outputs) {
if (o.role === "change") {
const book = s.books[o.book].state;
book.entries = book.entries || {};
book.entries[`${s.txid}_${o.vout}`] = {
value: o.value,
scriptType: "p2wpkh",
source: "change",
state: "pending",
spentFrom: signedId,
created: this.cDate,
};
}
}
for (const id of Object.keys(s.books)) {
s.books[id].stream.setState(s.books[id].state);
}
this.preSignedData.signedStream = signedId;
this.preSigned.setState(this.preSignedData);
(this.transactions as any)._dbIndex = this.preSignedData._dbIndex;
return true;
}/** This node's key part for Bitcoin wallet `id`; its volatile must carry the wallet's own pubkey. */
private async btcKeyPart(id: string, wallet: any): Promise<string> {
const v: any = await this.getAnyStreamReadOnly(`${id}:volatile`);
if (!v || !v.private || typeof v.private.part !== "string" || !v.public || v.public.pubkey !== wallet.pubkey) {
this.event.emit("key-health", {id});
throw "Check Key Health";
}
return v.private.part;
}/** The reasons a `btcmove` may give, and the fee cap each may use. */
private btcMoveCap(btcNet: any, reason: string): number {
if (reason === "frozen-sweep") {
return btcNet.feeRateCapSatVb.instant;
}
if (reason === "ceiling") {
return btcNet.sweepFeeRateCap;
}
throw "Bitcoin: btcmove reason must be frozen-sweep or ceiling";
}/** * The inputs a frozen-sweep must spend (PR #416 review L2): the book's * spendable and held entries (a held deposit is credited once a sweep * moved it, PR #417 review H1), largest value first, ties by outpoint, at * most min(maxMpcInputs, BTC_MPC2_MAX_INPUTS). */
private btcSweepInputs(book: any, code: string): string[] {
const fromData = this.requireBtcNetworkInFlight(code).maxMpcInputs;
const cap = typeof fromData === "number" && fromData < BTC_MPC2_MAX_INPUTS ? fromData : BTC_MPC2_MAX_INPUTS;
const entries: [string, any][] = Object.keys(book.entries || {}).map((o: string) => [o, book.entries[o]] as [string, any]);
return entries
.filter(([, e]) => e && (e.state === "spendable" || e.state === "held") && typeof e.value === "string" && /^[1-9][0-9]{0,15}$/.test(e.value))
.sort((a, b) => {
const va = BigInt(a[1].value);
const vb = BigInt(b[1].value);
return va > vb ? -1 : va < vb ? 1 : a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0;
})
.slice(0, Math.max(0, cap))
.map(([o]) => o);
}/** * The ledger's own reasons for a ceiling move (PR #417 review M1), so one * gateway cannot move Advanced coins at will: to the Standard class, round * and round between pool wallets paying fees, or locked up at a low rate. * Each check, and why: * - the ceiling is the ledger's (`btcNetworks[n].mpcCeilingSats`, an owner * `mod`), else the compiled MPC_CEILING_SATS_DEFAULT (21M BTC: essentially * off for now, Adam 2026-10-09); * - the source's confirmed (spendable) balance is over it: a move only * when the wallet holds more than one key should risk; * - an Advanced destination stays within it after the move: a move never * pushes another wallet over and so triggers the next one; * - at least MPC2_CEILING_MOVE_GAP_MS since the source's last ceiling move * (recorded on its book in consensus time): no back-to-back moves. */
private btcCeilingMoveCheck(btcNet: any, src: any, dst: any, dstWallet: any, value: bigint, sumIn: bigint, inputCount: number): void {
// The ledger figure when the owner set one, else the compiled default.
// The btc block validator only lets a positive integer string through, so
// anything else here is a missing figure.
const figure = typeof btcNet.mpcCeilingSats === "string" && /^[1-9][0-9]{0,15}$/.test(btcNet.mpcCeilingSats)
? btcNet.mpcCeilingSats
: MPC_CEILING_SATS_DEFAULT;
const ceiling = BigInt(figure);
const sum = (book: any, states: string[]): bigint => Object.keys(book.entries || {})
.map((o: string) => book.entries[o])
.filter((e: any) => e && states.indexOf(e.state) !== -1 && typeof e.value === "string" && /^[0-9]{1,16}$/.test(e.value))
.reduce((a: bigint, e: any) => a + BigInt(e.value), 0n);
const before = sum(src, ["spendable"]);
if (before <= ceiling) {
throw "Bitcoin: the source is not over its ceiling";
}
// No tiny moves (PR #417 re-review N5): a ceiling move takes enough to
// bring the source to or below its ceiling, or as many inputs as one
// signing may spend (min(maxMpcInputs, 5)). Otherwise each move pays a
// fee and a signing of the key for little, and the source stays over
// its ceiling for longer (one move per 30 minutes).
const fromData = btcNet.maxMpcInputs;
const inputCap = typeof fromData === "number" && fromData < BTC_MPC2_MAX_INPUTS ? fromData : BTC_MPC2_MAX_INPUTS;
if (before - sumIn > ceiling && inputCount < inputCap) {
throw "Bitcoin: a ceiling move must bring the source to its ceiling, or spend as many inputs as one signing may";
}
if (dstWallet.keyMethod === "mpc-tss" && sum(dst, ["spendable", "pending", "locked", "held"]) + value > ceiling) {
throw "Bitcoin: the move would put the destination over its ceiling";
}
if (src.lastCeilingMoveAt !== undefined) {
const since = new Date(this.cDate).getTime() - new Date(src.lastCeilingMoveAt).getTime();
if (!Number.isFinite(since) || since < MPC2_CEILING_MOVE_GAP_MS) {
throw "Bitcoin: the source moved for its ceiling less than 30 minutes ago";
}
}
}/** `btcmove` vote: see the block comment. */
private async btcVoteMove(): Promise<boolean> {
await this.assertMinigateSigner();
const req = this.transactions.$i.admin ? this.transactions.$i.admin.btc : undefined;
if (!req || typeof req !== "object") {
throw "Bitcoin: btcmove needs $i.admin.btc";
}
const btcNet = this.requireBtcNetwork(typeof req.network === "string" ? req.network : "");
const code = btcNet.code;
this.layer2TDetails.network = code;
this.layer2TDetails.token = "«redacted»";
const cap = this.btcMoveCap(btcNet, req.reason);
const from = req.from;
const to = req.to;
if (!from || !to || typeof from !== "object" || typeof to !== "object" || typeof from.wallet !== "string" ||
typeof to.wallet !== "string" || from.wallet === to.wallet) {
throw "Bitcoin: btcmove needs a source wallet and another destination wallet";
}
const readOnly = (id: string): any => {
if (!/^[0-9a-f]{64}$/.test(id) || !this.transactions.$r || this.transactions.$r[id] !== id) {
throw "Bitcoin: every wallet must be a read-only reference";
}
return this.getReadOnlyStream(id);
};
const srcState = readOnly(from.wallet);
const dstState = readOnly(to.wallet);
if (req.reason === "frozen-sweep") {
// Only the frozen key's own authorisation, to its own destination.
if (!srcState || srcState.mpcFrozen === undefined) {
throw "Bitcoin: a frozen-sweep moves a frozen key";
}
if (!srcState.mpcSweep || srcState.mpcSweep.to !== to.wallet) {
throw "Bitcoin: a frozen key moves only to its sweep destination (mpcSweep.to)";
}
this.mpc2Sweep = this.mpc2SweepAuthorisation(from.wallet, srcState, dstState ? dstState.address : "", dstState, to.wallet);
}
// btcReadWallet routes by signingRoute: the frozen source passes only
// under the authorisation just checked, for that wallet alone.
const src = this.btcReadWallet(from.wallet, code);
if (src.keyMethod !== "mpc-tss") {
throw "Bitcoin: btcmove moves an Advanced wallet's coins";
}
const dst = this.btcReadWallet(to.wallet, code);
// Coins must never be moved into a wallet that may not take them.
// This contract's own data holds the signed-proof switch (owner `mod`).
const lifecycle = this.poolLifecycleRefusal(dst, this.getContractDataHelper().mpc2RequireSignedProof === true);
if (lifecycle) {
throw `Bitcoin: btcmove destination refused: ${lifecycle}`;
}
if (req.reason === "ceiling") {
// A ceiling move bounds what one Advanced key can lose, so the coins go
// to a pool wallet nobody owns: a fresh Advanced deposit wallet with
// another key, or a Standard change wallet, which no user is shown.
if (dst.keyMethod === "mpc-tss") {
if (dst.owner !== null && dst.owner !== undefined) {
throw "Bitcoin: a ceiling move goes to an unassigned pool wallet";
}
if (dst.publicKey === src.publicKey) {
throw "Bitcoin: a ceiling move goes to another key";
}
} else if (dst.role !== "change") {
throw "Bitcoin: a ceiling move goes to a fresh Advanced wallet or a Standard change wallet";
}
}
// This node must hold the destination's key, or the coins moved there are
// unspendable (as a payout's change, security review H2).
const dv: any = await this.getAnyStreamReadOnly(`${to.wallet}:volatile`);
const dstHasKey = dst.keyMethod === "mpc-tss"
? !!dv && !!dv.private && typeof dv.private.part === "string" && typeof dv.private.part2 === "string" && !!dv.public && dv.public.pubkey === dst.pubkey
: !!dv && !!dv.private && typeof dv.private.part === "string" && !!dv.public && dv.public.pubkey === dst.pubkey;
if (!dstHasKey) {
this.event.emit("key-health", {id: to.wallet});
throw "Check Key Health";
}
const srcBook = this.btcLoadBook(from.book, from.wallet, src, code);
const dstBook = this.btcLoadBook(to.book, to.wallet, dst, code);
if (!Array.isArray(req.inputs) || req.inputs.length < 1 || req.inputs.length > BTC_MPC2_MAX_INPUTS) {
throw `Bitcoin: a move spends 1 to ${BTC_MPC2_MAX_INPUTS} inputs`;
}
const inputs: {outpoint: string; wallet: string; book: string; value: string}[] = [];
let sumIn = 0n;
for (const outpoint of req.inputs) {
this.btcParseOutpoint(outpoint);
if (inputs.some((i) => i.outpoint === outpoint)) {
throw "Bitcoin: duplicate input";
}
const entry = srcBook.state.entries ? srcBook.state.entries[outpoint] : undefined;
// Only spendable (credited, unlocked) UTXOs: never one a payout holds,
// nor one not yet credited (spec §4.4). A frozen key's sweep also takes
// a `held` deposit (PR #417 review H1): moving it is what lets its owner
// be credited (ConfirmWithdraw, on the move's confirmation).
const sweepable = entry && (entry.state === "spendable" || (req.reason === "frozen-sweep" && entry.state === "held"));
if (!sweepable) {
throw `Bitcoin: input ${outpoint} is not spendable`;
}
if (typeof entry.value !== "string" || !/^[1-9][0-9]{0,15}$/.test(entry.value)) {
throw "Bitcoin: UTXO book is malformed";
}
sumIn += BigInt(entry.value);
inputs.push({outpoint, wallet: from.wallet, book: from.book, value: entry.value, ...(entry.state === "held" && typeof entry.heldFor === "string" ? {heldFor: entry.heldFor} : {})});
}
if (req.reason === "frozen-sweep") {
// The contract picks a sweep's inputs, not the gateway (PR #416 review
// L2): the largest spendable UTXOs first (ties by outpoint), as many as
// one signing may spend. Otherwise one gateway could spend the sweep's
// signings on its smallest UTXOs and leave the bulk behind the key.
const want = this.btcSweepInputs(srcBook.state, code);
if (req.inputs.length !== want.length || req.inputs.some((o: string, k: number) => o !== want[k])) {
throw "Bitcoin: a frozen-sweep spends the largest spendable UTXOs, in that order";
}
}
if (typeof req.feeRate !== "number" || !Number.isInteger(req.feeRate) || req.feeRate < 1 || req.feeRate > cap) {
throw `Bitcoin: feeRate must be a whole sat/vB from 1 to ${cap}`;
}
const rate = BigInt(req.feeRate);
const d = this.btcDecodeAddress(code, dst.address);
// Every pool wallet is P2WPKH, and the book entry the commit writes says
// so (review L4): anything else is not a pool wallet's address.
if (d.type !== "p2wpkh") {
throw "Bitcoin: a move pays a P2WPKH pool wallet";
}
const value = sumIn - rate * BigInt(this.btcEstimateVsize(inputs.length, [d.type]));
if (value < this.btcDustThreshold(d.type)) {
throw "Bitcoin: the inputs do not cover the move and its fee";
}
if (req.reason === "ceiling") {
this.btcCeilingMoveCheck(btcNet, srcBook.state, dstBook.state, dst, value, sumIn, inputs.length);
}
const built = this.btcBuildPayoutTx(code, inputs.map((i) => i.outpoint), [{address: dst.address, value: value.toString()}], null);
const fee = sumIn - built.totalOut;
// btcSignTx: one Advanced wallet, at most min(maxMpcInputs, 5) inputs,
// one mpc2 signing; its payload carries the sweep for a frozen source.
const assembled = await this.btcSignTx(code, built, inputs, {[from.wallet]: src});
this.btcMoveData = {
code,
reason: req.reason,
txid: built.txid,
hex: assembled.hex,
unsignedHex: built.unsignedHex,
inputs,
output: {vout: 0, address: dst.address, type: d.type, value: built.totalOut.toString(), role: "move", wallet: to.wallet, book: to.book},
books: {[from.book]: srcBook, [to.book]: dstBook},
vsize: built.estimatedVsize,
fee: fee.toString(),
feeRate: req.feeRate,
address: src.address,
};
this.signatureHex = assembled.hex;
return true;
}/** * `btcmove` commit: the l1.sign record (sender `consolidation`, so the * gateways treat it as internal; `btc.kind` `move`), every input `locked` * to it and the output `pending` in the destination's book, and for a * frozen sweep the ledger's record of the signing. */
private btcCommitMove(): boolean {
const m = this.btcMoveData;
const signed = this.newActivityStream("l1.sign");
const signedId = signed.getId();
this.eventData = {
umid: this.umid,
umidActual: this.umid,
sender: "consolidation",
network: m.code,
token: "«redacted»",
amount: m.output.value,
toAddress: m.output.address,
stream: m.inputs[0].wallet,
wallet: m.address,
signed: m.hex,
varnirFee: "0",
delegated: false,
gasHold: null,
// An internal move, classified as consolidations are (Adam
// 2026-10-09): never credited to the destination's owner.
reason: m.reason === "ceiling" ? "ceiling" : "sweep",
metadata: {reason: m.reason, ...(this.mpc2Sweep ? {mpcSweep: {umid: this.mpc2Sweep.umid, index: this.mpc2Sweep.index}} : {})},
origin: (this.transactions as any).metadata?.origin || null,
created: this.cDate,
payload: {tx: m.unsignedHex, inputs: m.inputs.map((i: any) => ({wallet: i.wallet, value: i.value}))},
btc: {
txid: m.txid,
kind: "move",
// Why it happened, at decision time (consolidation-sightings).
reason: {kind: m.reason, utxos: m.inputs.length, rate: m.feeRate},
covers: [],
inputs: m.inputs,
outputs: [m.output],
vsize: m.vsize,
fee: m.fee,
feeRate: m.feeRate,
userFees: {},
speed: "move",
created: this.cDate,
history: [],
cancels: [],
},
};
signed.setState(this.eventData);
this.eventData.signedStream = signedId;
for (const i of m.inputs) {
const entry = m.books[i.book].state.entries[i.outpoint];
entry.state = "locked";
entry.lockedBy = signedId;
}
if (m.reason === "ceiling") {
// The ceiling's gap is measured from here (btcCeilingMoveCheck).
m.books[m.inputs[0].book].state.lastCeilingMoveAt = this.cDate;
}
const dst = m.books[m.output.book].state;
dst.entries = dst.entries || {};
dst.entries[`${m.txid}_0`] = {
value: m.output.value,
scriptType: "p2wpkh",
source: "sweep",
state: "pending",
spentFrom: signedId,
created: this.cDate,
};
for (const id of Object.keys(m.books)) {
m.books[id].stream.setState(m.books[id].state);
}
if (this.mpc2Sweep) {
this.recordSweepSigned(signedId);
}
return true;
}/** * btcbump / btccancel (spec §5.4): replace a signed, unconfirmed Bitcoin * payout by fee (BIP125). Both are gateway entries on `$o.signed`, the * payout's l1.sign stream, and both are recorded on that SAME stream as a * new version (the old one moves to `btc.history`), the way EVM cancels * are, so the inputs stay locked to one stream and ConfirmWithdraw settles * whichever version confirms. * * - btcbump: the same recipient outputs, the same inputs plus any extra * spendable ones (`$i.admin.btc.inputs`), change recomputed at the new * rate. Held to the payout's speed cap. * - btccancel: the same inputs, one output paying everything back to a * change wallet. Its fee is Varnir's; held to the instant cap. Once it * confirms at depth the payout can never land, which is the refund proof * ConfirmWithdraw accepts (`btc.cancels`). * Either way the new fee must beat the old by at least 1 sat/vB of the new * size (BIP125 rule 4) at a higher rate (rule 6). */
private async btcVoteReplace(kind: "bump" | "cancel"): Promise<boolean> {
await this.assertMinigateSigner();
const signed = this.getActivityStreams(this.transactions.$o.signed);
const st = signed.getState();
const signedId = signed.getId();
// A disabled entry stops new payouts, never a bump or cancel of a signed
// one (security review M1).
const btcNet = this.requireBtcNetworkInFlight(st.network);
const code = btcNet.code;
const cur = st.btc;
// A move (btcmove) is never replaced: a bump or cancel re-signs, and a
// frozen key's sweep signs once.
if (cur && cur.kind === "move") {
throw "Bitcoin: a move is never bumped or cancelled";
}
// At least one input, each checked below to be locked to this stream:
// only this contract's own commits lock to a stream, so that is what
// proves `$o.signed` is a payout it signed (security review H2).
if (!cur || typeof cur.txid !== "string" || !Array.isArray(cur.inputs) || cur.inputs.length < 1 || !Array.isArray(cur.outputs) || !st.gasHold) {
throw "Bitcoin: not a signed Bitcoin payout";
}
if (st.confirmed) {
throw "Bitcoin: already confirmed";
}
if (kind === "bump" && cur.kind === "cancel") {
throw "Bitcoin: a cancelled payout cannot be bumped";
}
const replacements = Array.isArray(cur.history) ? cur.history.length : 0;
if (replacements >= 10) {
throw "Bitcoin: too many replacements";
}
// The last slot is a cancel's, so a payout can always be withdrawn
// (security review M2).
if (kind === "bump" && replacements >= 9) {
throw "Bitcoin: the last replacement is kept for a cancel";
}
const req = this.transactions.$i.admin ? this.transactions.$i.admin.btc : undefined;
if (!req || typeof req !== "object") {
throw "Bitcoin: a replacement needs $i.admin.btc";
}
const wallets: {[id: string]: any} = {};
const books: {[id: string]: any} = {};
const inputs: {outpoint: string; wallet: string; book: string; value: string}[] = [];
const added: string[] = [];
let sumIn = 0n;
const take = (i: any, mustBe: string): void => {
if (!i || typeof i !== "object") {
throw "Bitcoin: bad input";
}
this.btcParseOutpoint(i.outpoint);
const wallet = wallets[i.wallet] || this.btcReadWallet(i.wallet, code);
wallets[i.wallet] = wallet;
const book = books[i.book] || this.btcLoadBook(i.book, i.wallet, wallet, code);
books[i.book] = book;
const entry = book.state.entries ? book.state.entries[i.outpoint] : undefined;
const ok = mustBe === "locked"
? entry && entry.state === "locked" && entry.lockedBy === signedId
: entry && entry.state === "spendable";
if (!ok || typeof entry.value !== "string" || !/^[1-9][0-9]{0,15}$/.test(entry.value)) {
throw `Bitcoin: input ${i.outpoint} is not ${mustBe === "locked" ? "locked to this payout" : "spendable"}`;
}
sumIn += BigInt(entry.value);
inputs.push({outpoint: i.outpoint, wallet: i.wallet, book: i.book, value: entry.value});
};
for (const i of cur.inputs) {
take(i, "locked");
}
const extra = req.inputs === undefined ? [] : req.inputs;
if (!Array.isArray(extra) || (kind === "cancel" && extra.length > 0)) {
throw "Bitcoin: only a bump may add inputs";
}
// A disabled network finishes what is signed from the inputs already
// locked to it; it never pulls more pool coins in (review follow-up).
if (btcNet.enabled !== true && extra.length > 0) {
throw "Bitcoin: a disabled network takes no new inputs";
}
for (const i of extra) {
take(i, "spendable");
added.push(i.outpoint);
}
if (inputs.length > btcNet.maxInputs) {
throw `Bitcoin: a payout spends 1 to ${btcNet.maxInputs} inputs`;
}
let cap: number = kind === "bump" ? btcNet.feeRateCapSatVb[cur.speed] : btcNet.feeRateCapSatVb.instant;
if (kind === "cancel") {
// A cancel must always be able to replace (security review M2): when
// the instant cap can't pay the current fee plus 1 sat/vB of the
// cancel's size (BIP125 rule 4), the least rate that does is allowed,
// and nothing above it.
const v = BigInt(this.btcEstimateVsize(inputs.length, ["p2wpkh"]));
const least = (BigInt(cur.fee) + v + v - 1n) / v;
if (least > BigInt(cap)) {
cap = Number(least);
}
}
if (typeof req.feeRate !== "number" || !Number.isInteger(req.feeRate) || req.feeRate <= cur.feeRate || req.feeRate > cap) {
throw `Bitcoin: feeRate must be a whole sat/vB above ${cur.feeRate} and at most ${cap}`;
}
// The change wallet: the payout's own, else one named now.
const oldChange = cur.outputs.filter((o: any) => o.role === "change")[0];
const changeRef = oldChange ? {wallet: oldChange.wallet, book: oldChange.book} : req.change;
let changeWallet: any = null;
let changeDoc: any = null;
const useChange = (): any => {
if (!changeRef || typeof changeRef !== "object") {
throw "Bitcoin: this replacement needs a change wallet";
}
const w = wallets[changeRef.wallet] || this.btcReadWallet(changeRef.wallet, code);
if (w.role !== "change") {
throw "Bitcoin: change must go to a change wallet";
}
books[changeRef.book] = books[changeRef.book] || this.btcLoadBook(changeRef.book, changeRef.wallet, w, code);
changeDoc = w;
changeWallet = {wallet: changeRef.wallet, book: changeRef.book, address: w.address};
return changeWallet;
};
// The old change entry leaves its book, so that book is written either way.
if (oldChange) {
useChange();
}
const rate = BigInt(req.feeRate);
let built: any;
let outputs: any[];
if (kind === "bump") {
// The recipient outputs, exactly as signed before.
const recipients = cur.outputs.filter((o: any) => o.role === "recipient");
const types = recipients.map((o: any) => o.type).concat(["p2wpkh"]);
const totalTo = recipients.reduce((t: bigint, o: any) => t + BigInt(o.value), 0n);
const changeValue = sumIn - totalTo - rate * BigInt(this.btcEstimateVsize(inputs.length, types));
const change = changeValue >= this.btcDustThreshold("p2wpkh") ? useChange() : null;
built = this.btcBuildPayoutTx(code, inputs.map((i) => i.outpoint),
recipients.map((o: any) => ({address: o.address, value: o.value})),
change ? {address: change.address, value: changeValue.toString()} : null);
outputs = recipients.map((o: any) => ({...o}));
if (change) {
outputs.push({vout: recipients.length, address: change.address, type: "p2wpkh", value: changeValue.toString(), role: "change", wallet: change.wallet, book: change.book});
}
} else {
const back = useChange();
const value = sumIn - rate * BigInt(this.btcEstimateVsize(inputs.length, ["p2wpkh"]));
if (value < this.btcDustThreshold("p2wpkh")) {
throw "Bitcoin: nothing would be left to pay back";
}
built = this.btcBuildPayoutTx(code, inputs.map((i) => i.outpoint), [{address: back.address, value: value.toString()}], null);
outputs = [{vout: 0, address: back.address, type: "p2wpkh", value: value.toString(), role: "change", wallet: back.wallet, book: back.book}];
}
const fee = sumIn - built.totalOut;
const vsize = BigInt(built.estimatedVsize);
if (fee < rate * vsize) {
throw "Bitcoin: inputs do not cover the payout and its fee";
}
if (fee < BigInt(cur.fee) + vsize) {
throw "Bitcoin: a replacement must pay the old fee plus 1 sat/vB of its own size";
}
const paidRate = (fee + vsize - 1n) / vsize;
if (paidRate > BigInt(cap)) {
throw `Bitcoin: fee rate ${paidRate} sat/vB is over the cap ${cap}`;
}
// This node must hold the key of any change wallet paid (security review H2).
if (outputs.some((o: any) => o.role === "change")) {
await this.btcKeyPart(changeWallet.wallet, changeDoc);
}
const assembled = await this.btcSignTx(code, built, inputs, wallets);
const hold = st.gasHold;
const refFee = rate * BigInt(hold.referenceVbytes);
const holdAmount = BigInt(hold.amount);
// Never above the hold, nor above the real fee (security review L2).
let userFee = refFee < holdAmount ? refFee : holdAmount;
if (fee < userFee) {
userFee = fee;
}
this.btcReplace = {
signed,
st,
signedId,
kind,
books,
added,
hex: assembled.hex,
unsignedHex: built.unsignedHex,
version: {
kind: kind === "bump" ? "payout" : "cancel",
txid: built.txid,
inputs,
outputs,
vsize: built.estimatedVsize,
fee: fee.toString(),
feeRate: req.feeRate,
// A cancel moves nothing for the user; its fee is all Varnir's.
userFees: kind === "bump" ? {[cur.covers[0]]: userFee.toString()} : {},
created: this.cDate,
},
};
this.signatureHex = assembled.hex;
return true;
}/** * Record the replacement on the payout's l1.sign: the old version to * `history`, the new one current; extra inputs locked to the stream; the * old version's pending change out of its book and the new one's in; the * broadcast flag cleared so the new bytes are broadcast. */
private async btcCommitReplace(): Promise<boolean> {
const r = this.btcReplace;
const st = r.st;
const cur = st.btc;
const previous: any = {
kind: cur.kind || "payout", txid: cur.txid, inputs: cur.inputs, outputs: cur.outputs, vsize: cur.vsize,
fee: cur.fee, feeRate: cur.feeRate, userFees: cur.userFees, created: cur.created ?? null,
};
for (const o of cur.outputs) {
if (o.role === "change" && r.books[o.book]) {
delete r.books[o.book].state.entries[`${cur.txid}_${o.vout}`];
}
}
for (const i of r.version.inputs) {
if (r.added.indexOf(i.outpoint) !== -1) {
const entry = r.books[i.book].state.entries[i.outpoint];
entry.state = "locked";
entry.lockedBy = r.signedId;
}
}
for (const o of r.version.outputs) {
if (o.role === "change") {
const book = r.books[o.book].state;
book.entries = book.entries || {};
book.entries[`${r.version.txid}_${o.vout}`] = {
value: o.value,
scriptType: "p2wpkh",
source: "change",
state: "pending",
spentFrom: r.signedId,
created: this.cDate,
};
}
}
for (const id of Object.keys(r.books)) {
r.books[id].stream.setState(r.books[id].state);
}
st.btc = {
...cur,
...r.version,
history: (Array.isArray(cur.history) ? cur.history : []).concat([previous]),
cancels: (Array.isArray(cur.cancels) ? cur.cancels : []).concat(r.kind === "cancel" ? [{txid: r.version.txid, fee: r.version.fee}] : []),
};
st.signed = r.hex;
st.payload = {tx: r.unsignedHex, inputs: r.version.inputs.map((i: any) => ({wallet: i.wallet, value: i.value}))};
st.receipt = {txid: r.version.txid};
r.signed.setState(st);
const volatile: any = (await r.signed.getVolatile()) || {};
volatile.broadcasted = false;
r.signed.setVolatile(volatile);
this.eventData = {...st, signedStream: r.signedId, replacement: r.kind};
return true;
}/** Address parameters per code. Returned fresh, never shared. */
private btcParams(code: string): {hrp: string; p2pkh: number; p2sh: number}/** This contract's stored `btcNetworks` map ({} when unset). Throws when it is not an object. */ private btcStoredNetworks(): {[code: string]: any}/** The `btcNetworks` entry for `code`, enabled or not, with `code` set, or null. Throws when it is malformed. */
private btcAnyNetworkData(code: string): any | null {
const key = typeof code === "string" ? code : "";
if (this.btcParams(key) === null) {
return null;
}
const stored = this.btcStoredNetworks();
if (Object.keys(stored).indexOf(key) === -1) {
return null;
}
this.assertBtcNetworkEntry(key, stored[key]);
return {...stored[key], code: key};
}/** The enabled `btcNetworks` entry for `code` with `code` set, or null. Throws when it is malformed. */
private btcNetworkData(code: string): any | null {
const found = this.btcAnyNetworkData(code);
return found && found.enabled === true ? found : null;
}/** btcNetworkData, failing closed. For new Bitcoin work: wallets, deposits, payouts. */
private requireBtcNetwork(code: string): any {
const found = this.btcNetworkData(code);
if (!found) {
throw `Unknown Bitcoin network ${code}`;
}
return found;
}/** * btcAnyNetworkData, failing closed. For finishing what is already signed * (broadcast, bump, cancel, confirm, refund): `enabled: false` stops new * Bitcoin work, never the way out of a payout in flight. */
private requireBtcNetworkInFlight(code: string): any {
const found = this.btcAnyNetworkData(code);
if (!found) {
throw `Unknown Bitcoin network ${code}`;
}
return found;
}/** The `mod` validator for a whole `btcNetworks` map. Absent leaves the stored map alone. */
private assertBtcNetworks(value: any): void {
if (value === undefined || value === null) {
return;
}
if (typeof value !== "object" || Array.isArray(value)) {
throw "btcNetworks must be an object keyed by network code";
}
for (const code of Object.keys(value)) {
this.assertBtcNetworkEntry(code, value[code]);
}
}/** * One `btcNetworks` entry (spec §8.1). Every field is required but the * optional `mpcCeilingSats` (PR #417 review M1); no others are allowed. */
private assertBtcNetworkEntry(code: string, entry: any): void {
const params = this.btcParams(code);
if (params === null) {
throw `btcNetworks: ${code} is not a Bitcoin network`;
}
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
throw `btcNetworks.${code} must be an object`;
}
const fields = ["ledger", "hrp", "enabled", "confirmations", "conflictDepth", "feeRateCapSatVb",
"sweepFeeRateCap", "referenceVbytes", "dustSats", "minCreditSats", "maxInputs", "maxMpcInputs",
"maxSweepInputs", "maxBatchOutputs", "broadcast"];
// The Advanced (mpc2) wallet ceiling, in sats (PR #417 review M1):
// Varnir.CryptoTransfer's `btcmove` reason `ceiling` checks a move
// against it, so a gateway cannot move Advanced coins on its own word.
// Optional: absent, no ceiling move is accepted on the network.
const optional = ["mpcCeilingSats"];
for (const field of Object.keys(entry)) {
if (fields.indexOf(field) === -1 && optional.indexOf(field) === -1) {
throw `btcNetworks.${code}.${field} is not a Bitcoin network field`;
}
}
if (entry.mpcCeilingSats !== undefined && (typeof entry.mpcCeilingSats !== "string" || !/^[1-9][0-9]{0,15}$/.test(entry.mpcCeilingSats))) {
throw `btcNetworks.${code}.mpcCeilingSats must be a positive integer string of sats`;
}
for (const field of fields) {
if (Object.keys(entry).indexOf(field) === -1) {
throw `btcNetworks.${code}.${field} is required`;
}
}
if (entry.ledger !== code) {
throw `btcNetworks.${code}.ledger must be ${code}`;
}
if (entry.hrp !== params.hrp) {
throw `btcNetworks.${code}.hrp must be ${params.hrp}`;
}
if (typeof entry.enabled !== "boolean") {
throw `btcNetworks.${code}.enabled must be true or false`;
}
const int = (name: string, min: number, max: number) => {
const v = entry[name];
if (typeof v !== "number" || !Number.isSafeInteger(v) || v < min || v > max) {
throw `btcNetworks.${code}.${name} must be an integer from ${min} to ${max}`;
}
};
int("confirmations", 1, 100);
int("conflictDepth", 1, 100);
if (entry.conflictDepth < entry.confirmations) {
throw `btcNetworks.${code}.conflictDepth must be at least confirmations`;
}
int("sweepFeeRateCap", 1, 10000);
int("referenceVbytes", 100, 1000);
int("maxInputs", 1, 100);
int("maxMpcInputs", 0, 100);
int("maxSweepInputs", 1, 100);
int("maxBatchOutputs", 1, 100);
if (entry.maxMpcInputs > entry.maxInputs) {
throw `btcNetworks.${code}.maxMpcInputs must not exceed maxInputs`;
}
const caps = entry.feeRateCapSatVb;
if (!caps || typeof caps !== "object" || Array.isArray(caps) || Object.keys(caps).length !== 3) {
throw `btcNetworks.${code}.feeRateCapSatVb must be {instant, standard, economy}`;
}
for (const speed of ["instant", "standard", "economy"]) {
const v = caps[speed];
if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 1 || v > 10000) {
throw `btcNetworks.${code}.feeRateCapSatVb.${speed} must be an integer from 1 to 10000`;
}
}
for (const name of ["dustSats", "minCreditSats"]) {
if (typeof entry[name] !== "string" || !/^[1-9][0-9]{0,15}$/.test(entry[name])) {
throw `btcNetworks.${code}.${name} must be a positive integer string of sats`;
}
}
if (BigInt(entry.dustSats) < this.btcDustThreshold("p2wpkh")) {
throw `btcNetworks.${code}.dustSats must be at least the P2WPKH relay dust (294)`;
}
const urls = entry.broadcast;
if (!Array.isArray(urls) || urls.length < 1 || urls.length > 4) {
throw `btcNetworks.${code}.broadcast must list 1 to 4 URLs`;
}
for (const u of urls) {
// Keyless endpoints only: no credentials or query strings in contract data.
if (typeof u !== "string" || !/^https:\/\/[a-z0-9.-]+(:[0-9]{1,5})?(\/[A-Za-z0-9._~\/-]*)?$/.test(u)) {
throw `btcNetworks.${code}.broadcast entries must be plain https URLs`;
}
}
} private btcHexToBytes(hex: string): Uint8Array {
if (typeof hex !== "string" || hex.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(hex)) {
throw "Bitcoin: invalid hex";
}
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return out;
} private btcBytesToHex(bytes: Uint8Array): string {
let s = "";
for (let i = 0; i < bytes.length; i++) {
s += (bytes[i] < 16 ? "0" : "") + bytes[i].toString(16);
}
return s;
} private btcConcat(parts: Uint8Array[]): Uint8Array {
let len = 0;
for (const p of parts) {
len += p.length;
}
const out = new Uint8Array(len);
let off = 0;
for (const p of parts) {
out.set(p, off);
off += p.length;
}
return out;
} private btcReverse(bytes: Uint8Array): Uint8Array {
const out = new Uint8Array(bytes.length);
for (let i = 0; i < bytes.length; i++) {
out[i] = bytes[bytes.length - 1 - i];
}
return out;
} private btcSha256d(data: Uint8Array): Uint8Array {
return utils.arrayify(utils.sha256(utils.sha256(data)));
} private btcHash160(data: Uint8Array): Uint8Array {
return utils.arrayify(utils.ripemd160(utils.sha256(data)));
} private btcU32(n: number): Uint8Array {
if (typeof n !== "number" || !Number.isInteger(n) || n < 0 || n > 4294967295) {
throw "Bitcoin: u32 out of range";
}
return Uint8Array.from([n & 255, (n >>> 8) & 255, (n >>> 16) & 255, (n >>> 24) & 255]);
} private btcU64(n: bigint): Uint8Array {
if (typeof n !== "bigint" || n < 0n || n > 2100000000000000n) {
throw "Bitcoin: amount out of range";
}
const out = new Uint8Array(8);
let v = n;
for (let i = 0; i < 8; i++) {
out[i] = Number(v & 255n);
v = v >> 8n;
}
return out;
} private btcVarint(n: number): Uint8Array {
if (n < 253) {
return Uint8Array.from([n]);
}
if (n <= 65535) {
return Uint8Array.from([253, n & 255, n >>> 8]);
}
throw "Bitcoin: varint too large";
} private btcVarbytes(b: Uint8Array): Uint8Array {
return this.btcConcat([this.btcVarint(b.length), b]);
} private btcPolymod(values: number[]): number {
const gen = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
let chk = 1;
for (const v of values) {
const hi = chk >>> 25;
chk = (((chk & 0x1ffffff) << 5) ^ v) >>> 0;
for (let i = 0; i < 5; i++) {
if ((hi >>> i) & 1) {
chk = (chk ^ gen[i]) >>> 0;
}
}
}
return chk;
} private btcHrpExpand(hrp: string): number[] {
const out: number[] = [];
for (let i = 0; i < hrp.length; i++) {
out.push(hrp.charCodeAt(i) >>> 5);
}
out.push(0);
for (let i = 0; i < hrp.length; i++) {
out.push(hrp.charCodeAt(i) & 31);
}
return out;
} private btcConvertBits(data: number[], from: number, to: number, pad: boolean): number[] {
let acc = 0;
let bits = 0;
const out: number[] = [];
const maxv = (1 << to) - 1;
for (const value of data) {
acc = (acc << from) | value;
bits += from;
while (bits >= to) {
bits -= to;
out.push((acc >> bits) & maxv);
}
}
if (pad) {
if (bits > 0) {
out.push((acc << (to - bits)) & maxv);
}
} else if (bits >= from || ((acc << (to - bits)) & maxv) !== 0) {
throw "Bitcoin: invalid address padding";
}
return out;
}/** A segwit address for `hrp` (BIP173 + BIP350): {version, program}. Throws on any rule break. */ private btcDecodeSegwit(hrp: string, s: string): {version: number; program: Uint8Array} private btcBase58checkDecode(s: string): Uint8Array {
const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
if (s.length < 1 || s.length > 64) {
throw "Bitcoin: malformed base58 address";
}
let n = 0n;
for (let i = 0; i < s.length; i++) {
const d = alphabet.indexOf(s.charAt(i));
if (d === -1) {
throw "Bitcoin: invalid base58 character";
}
n = n * 58n + BigInt(d);
}
const body: number[] = [];
while (n > 0n) {
body.unshift(Number(n & 255n));
n = n >> 8n;
}
let zeros = 0;
while (zeros < s.length && s.charAt(zeros) === "1") {
zeros++;
}
const raw = new Uint8Array(zeros + body.length);
raw.set(Uint8Array.from(body), zeros);
if (raw.length < 5) {
throw "Bitcoin: base58 address too short";
}
const payload = raw.slice(0, raw.length - 4);
const check = this.btcSha256d(payload);
for (let i = 0; i < 4; i++) {
if (raw[raw.length - 4 + i] !== check[i]) {
throw "Bitcoin: invalid base58 checksum";
}
}
return payload;
}/**
* Decode an address for one network: {type, hash, address} with `address`
* the normalised form (bech32 lower-case, base58 as given). Refuses another
* network's address, mixed case, whitespace, and witness versions nobody can
* spend yet (v2-16, and v1 programs that are not 32 bytes).
*/ private btcDecodeAddress(code: string, s: string): {type: string; hash: Uint8Array; address: string}/** * A key the confidential VM made for a pool wallet (spec §8.4): `pubkey` * must be a 33-byte compressed key and `address` exactly the lower-case * P2WPKH address of its HASH160 on this network. Returns the pubkey hex. */
private btcAssertP2wpkhKey(code: string, address: string, pubkey: string): string {
if (typeof pubkey !== "string" || !/^0[23][0-9a-f]{64}$/.test(pubkey)) {
throw "Bitcoin: key must come with its 33-byte compressed public key";
}
const d = this.btcDecodeAddress(code, address);
if (d.type !== "p2wpkh" || d.address !== address) {
throw "Bitcoin: a pool wallet must have a lower-case P2WPKH address";
}
if (this.btcBytesToHex(this.btcHash160(this.btcHexToBytes(pubkey))) !== this.btcBytesToHex(d.hash)) {
throw "Bitcoin: address does not match the public key";
}
return pubkey;
}/** The one normaliser (spec §9). */
private btcNormaliseAddress(code: string, s: string): string {
return this.btcDecodeAddress(code, s).address;
}/** Serialised output size per address type. */
private btcOutputBytes(type: string): number {
const sizes: {[type: string]: number} = {p2pkh: 34, p2sh: 32, p2wpkh: 31, p2wsh: 43, p2tr: 43};
if (Object.keys(sizes).indexOf(type) === -1) {
throw "Bitcoin: unknown output type";
}
return sizes[type];
}/** * Worst-case vsize of a transaction spending `inputs` P2WPKH inputs (each * with a 72-byte signature, 272 weight units) to these output types. Never * below the signed transaction's real vsize, so fee checks use it. */
private btcEstimateVsize(inputs: number, outputTypes: string[]): number {
if (!Number.isInteger(inputs) || inputs < 1 || inputs > 252 || outputTypes.length < 1 || outputTypes.length > 252) {
throw "Bitcoin: bad transaction shape";
}
let base = 4 + 1 + 1 + 4;
for (const t of outputTypes) {
base += this.btcOutputBytes(t);
}
return Math.ceil((base * 4 + 2 + inputs * 272) / 4);
}/** Bitcoin Core's relay dust threshold at 3 sat/vB: 294 P2WPKH, 330 P2WSH/P2TR, 546 P2PKH, 540 P2SH. */
private btcDustThreshold(type: string): bigint {
const segwit = type === "p2wpkh" || type === "p2wsh" || type === "p2tr";
const spend = segwit ? 67 : 148;
return BigInt(Math.floor((this.btcOutputBytes(type) + spend) * 3));
}/** * `<txid>_<vout>` to its parts. Strict: lower-case hex, canonical vout. * Split by hand: the engine's deploy scan refuses `.exec`. */
private btcParseOutpoint(key: string): {txid: string; vout: number}/**
* Serialise {version, locktime, inputs: [{txid, vout, sequence, witness?}],
* outputs: [{value, script}]}. Inputs have empty scriptSigs (Varnir spends
* P2WPKH only). With `withWitness`, every input must carry its witness.
*/ private btcSerialize(tx: any, withWitness: boolean): Uint8Array {
const parts: Uint8Array[] = [this.btcU32(tx.version)];
if (withWitness) {
parts.push(Uint8Array.from([0, 1]));
}
parts.push(this.btcVarint(tx.inputs.length));
for (const i of tx.inputs) {
parts.push(this.btcReverse(this.btcHexToBytes(i.txid)), this.btcU32(i.vout), Uint8Array.from([0]), this.btcU32(i.sequence));
}
parts.push(this.btcVarint(tx.outputs.length));
for (const o of tx.outputs) {
parts.push(this.btcU64(o.value), this.btcVarbytes(o.script));
}
if (withWitness) {
for (const i of tx.inputs) {
if (!Array.isArray(i.witness) || i.witness.length < 1) {
throw "Bitcoin: every input needs a witness";
}
parts.push(this.btcVarint(i.witness.length));
for (const item of i.witness) {
parts.push(this.btcVarbytes(item));
}
}
}
parts.push(this.btcU32(tx.locktime));
return this.btcConcat(parts);
}/** The txid: double-SHA256 of the non-witness serialisation, display order. */
private btcTxid(tx: any): string {
return this.btcBytesToHex(this.btcReverse(this.btcSha256d(this.btcSerialize(tx, false))));
}/** * Put the VM's witnesses (hex items, one stack per input) on the unsigned * transaction this contract built. Returns the signed hex and the txid, * which witnesses don't change. Each P2WPKH witness must be exactly * <signature> <33-byte compressed key>. */
private btcAssembleSigned(unsignedHex: string, witnesses: string[][]): {hex: string; txid: string}/** Parse an unsigned transaction this block serialised (empty scriptSigs, no witness). */
private btcParseUnsigned(hex: string): any {
const b = this.btcHexToBytes(hex);
let off = 0;
const take = (n: number): Uint8Array => {
if (off + n > b.length) {
throw "Bitcoin: truncated transaction";
}
const out = b.slice(off, off + n);
off += n;
return out;
};
const u32 = (): number => {
const x = take(4);
return (x[0] | (x[1] << 8) | (x[2] << 16) | (x[3] << 24)) >>> 0;
};
const varint = (): number => {
const first = take(1)[0];
if (first < 253) {
return first;
}
if (first === 253) {
const x = take(2);
const v = x[0] | (x[1] << 8);
if (v < 253) {
throw "Bitcoin: non-canonical varint";
}
return v;
}
throw "Bitcoin: varint too large";
};
const version = u32();
const nIn = varint();
const inputs: any[] = [];
for (let k = 0; k < nIn; k++) {
const txid = this.btcBytesToHex(this.btcReverse(take(32)));
const vout = u32();
if (varint() !== 0) {
throw "Bitcoin: unsigned inputs have empty scriptSigs";
}
inputs.push({txid, vout, sequence: u32()});
}
const nOut = varint();
const outputs: any[] = [];
for (let k = 0; k < nOut; k++) {
const v = take(8);
let value = 0n;
for (let i = 7; i >= 0; i--) {
value = (value << 8n) | BigInt(v[i]);
}
outputs.push({value, script: take(varint())});
}
const locktime = u32();
if (off !== b.length || nIn < 1 || nOut < 1) {
throw "Bitcoin: malformed unsigned transaction";
}
return {version, locktime, inputs, outputs};
}/** * True when one of the contract stream's authorities has `public` equal to * `identity` (voteMod passes the signing identity's stream id). */
private hasContractOwnership(contract: Activity, identity: string): boolean {
return contract.getAuthorities().some((v) => v.public === identity);
}/**
* `mod` vote: `$o.contract` must be this contract's own stream, and
* `$i.owner` its owner (hasContractOwnership) or ALLOWEDMOD. Only the owner
* may write `evmNetworks` or `btcNetworks`. Validates, on `$i.owner`: the
* EVM and Bitcoin network tables, `gasPriceCaps` (the EVM constant chains
* plus the table's), `tronFeeLimits` (the Tron networks, at most
* TRONFEELIMITMAX), `newAddressHold` (`{enabled: boolean}`) and
* `mpc2Enabled` (a boolean, owner only).
*/ private async voteMod(): Promise<boolean> {
if (this.transactions.$o.contract) {
const contract = this.getActivityStreams(this.transactions.$o.contract);
if (this.transactions.$contract.substring(0, 64) !== contract.getId()) {
throw "Contract Not Matching";
}
const modId = this.getActivityStreams(this.transactions.$i.owner).getId();
if (
this.hasContractOwnership(contract, modId) ||
modId === ALLOWEDMOD // Maybe specific id's are allowed
) {
// The EVM chain table decides which chains are signed for: only the
// contract OWNER may add or alter it, never ALLOWEDMOD.
if (
this.transactions.$i.owner.evmNetworks !== undefined &&
this.transactions.$i.owner.evmNetworks !== null &&
!this.hasContractOwnership(contract, modId)
) {
throw "evmNetworks may only be written by the contract owner";
}
// These size every withdrawal's gas hold and cap the price signed,
// so a malformed value must never reach contract data: a positive
// integer string per known canonical network, nothing else.
// The EVM chain table first: a gasPriceCaps key may name a chain this
// same transaction adds.
this.assertEvmNetworks(this.transactions.$i.owner.evmNetworks);
// The Bitcoin network table (btc block): owner only, validated whole.
if (
this.transactions.$i.owner.btcNetworks !== undefined &&
this.transactions.$i.owner.btcNetworks !== null &&
!this.hasContractOwnership(contract, modId)
) {
throw "btcNetworks may only be written by the contract owner";
}
this.assertBtcNetworks(this.transactions.$i.owner.btcNetworks);
// The mpc2 switch decides which keys may sign and how (signingRoute):
// the contract owner only, as for the network tables, and exactly a
// boolean.
if (
this.transactions.$i.owner.mpc2Enabled !== undefined &&
this.transactions.$i.owner.mpc2Enabled !== null &&
!this.hasContractOwnership(contract, modId)
) {
throw "mpc2Enabled may only be written by the contract owner";
}
this.assertMpc2Enabled(this.transactions.$i.owner.mpc2Enabled);
// The ledger freeze switch: the contract owner only, exactly a
// boolean (turning it on needs Adam's yes and the drills first).
const freezeFlag = this.transactions.$i.owner.mpc2FreezeEnabled;
if (freezeFlag !== undefined && freezeFlag !== null) {
if (!this.hasContractOwnership(contract, modId)) {
throw "mpc2FreezeEnabled may only be written by the contract owner";
}
if (typeof freezeFlag !== "boolean") {
throw "mpc2FreezeEnabled must be true or false";
}
}
// The ledger halt switch: the same rules as the freeze switch.
const haltFlag = this.transactions.$i.owner.mpc2LedgerHaltEnabled;
if (haltFlag !== undefined && haltFlag !== null) {
if (!this.hasContractOwnership(contract, modId)) {
throw "mpc2LedgerHaltEnabled may only be written by the contract owner";
}
if (typeof haltFlag !== "boolean") {
throw "mpc2LedgerHaltEnabled must be true or false";
}
}
// The signed-proof switch (decision 2026-10-10, PR #430 review M3):
// the contract owner only, exactly a boolean. Turning it on is a
// gated step (Adam's yes, after the `--sign` backfill is clean).
const proofFlag = this.transactions.$i.owner.mpc2RequireSignedProof;
if (proofFlag !== undefined && proofFlag !== null) {
if (!this.hasContractOwnership(contract, modId)) {
throw "mpc2RequireSignedProof may only be written by the contract owner";
}
if (typeof proofFlag !== "boolean") {
throw "mpc2RequireSignedProof must be true or false";
}
}
// Clearing the peer-lockout halt (`mpchalt`, Task 3.3) turns mpc2
// signing back on: the contract owner only, after review, by naming
// the halted lockout's sid, so a stale or mistyped clear does nothing.
const haltClear = this.transactions.$i.owner.mpc2HaltClear;
if (haltClear !== undefined && haltClear !== null) {
if (!this.hasContractOwnership(contract, modId)) {
throw "mpc2HaltClear may only be written by the contract owner";
}
const halt = this.getContractDataHelper().mpc2Halt;
if (!halt || typeof halt !== "object" || halt.sid !== haltClear) {
throw "mpc2HaltClear does not name the stored halt";
}
}
this.assertGasOverrides("gasPriceCaps", this.transactions.$i.owner.gasPriceCaps, this.gasCapNetworks(this.transactions.$i.owner.evmNetworks));
this.assertGasOverrides("tronFeeLimits", this.transactions.$i.owner.tronFeeLimits, TRONFEELIMITS);
// The new-recipient hold's kill switch: {enabled: boolean} only.
const holdSwitch = this.transactions.$i.owner.newAddressHold;
if (
holdSwitch !== undefined &&
holdSwitch !== null &&
(typeof holdSwitch !== "object" || Array.isArray(holdSwitch) || typeof holdSwitch.enabled !== "boolean")
) {
throw "newAddressHold must be {enabled: true|false}";
}
return true;
}
throw "No Contract Authority";
} else {
throw "Missing Contract Output";
}
}/** * The networks a gasPriceCaps override may name: the constant EVM chains * plus every `evmNetworks` entry - the one this `mod` writes, else the * stored one. */
private gasCapNetworks(incoming: any): {[netCode: string]: boolean}/** The `evmNetworks` fields this contract stores and reads (evm-registry block). */
private evmFieldSpec(): {required: string[]; optional: string[]}/**
* `mod` commit: writes contract data. Each field takes the value on
* `$i.owner`, else keeps the stored one: the legacy fee fields (stored,
* never read), `gasPriceCaps`, `tronFeeLimits`, `evmNetworks` and
* `btcNetworks` (each replaced whole), `mpc2Enabled` and `newAddressHold`
* (`{enabled, updated}`). Stamps `umid` and `updated`.
*/ private async commitMod(): Promise<boolean> {
const cd = this.getContractDataHelper();
const inputs = this.transactions.$i.owner;
// The fee fields below are still accepted and stored so existing owner
// transactions keep working, but nothing reads them any more: Varnir takes
// no on-ledger fee (credit-only model, RV6). Only gasPriceCaps and
// tronFeeLimits drive behaviour.
cd.minFee = inputs.minFee ?? cd.minFee ?? null;
cd.l2USDTFee = inputs.l2USDTFee ?? cd.l2USDTFee ?? null;
cd.ethUSDTFee = inputs.ethUSDTFee ?? cd.ethUSDTFee ?? null;
cd.bscUSDTFee = inputs.bscUSDTFee ?? cd.bscUSDTFee ?? null;
cd.tronUSDTFee = inputs.tronUSDTFee ?? cd.tronUSDTFee ?? null;
cd.solUSDTFee = inputs.solUSDTFee ?? cd.solUSDTFee ?? null;
cd.baseDepositUSDTFee =
inputs.baseDepositUSDTFee ?? cd.baseDepositUSDTFee ?? null;
cd.baseDepositBSCUSDTFee =
inputs.baseDepositBSCUSDTFee ?? cd.baseDepositBSCUSDTFee ?? null;
cd.gasPriceCaps = inputs.gasPriceCaps ?? cd.gasPriceCaps ?? null;
cd.tronFeeLimits = inputs.tronFeeLimits ?? cd.tronFeeLimits ?? null;
// The EVM chain table (evm-registry block). Replaced whole, never merged
// here: the write script merges with what is stored before it sends.
cd.evmNetworks = inputs.evmNetworks ?? cd.evmNetworks ?? null;
// The Bitcoin network table (btc block), replaced whole the same way.
cd.btcNetworks = inputs.btcNetworks ?? cd.btcNetworks ?? null;
// The mpc2 switch (mpc2 block), exactly true or false; absent keeps it.
cd.mpc2Enabled = inputs.mpc2Enabled ?? cd.mpc2Enabled ?? null;
// The ledger freeze switch, exactly true or false; absent keeps it.
cd.mpc2FreezeEnabled = inputs.mpc2FreezeEnabled ?? cd.mpc2FreezeEnabled ?? null;
// The ledger halt switch, exactly true or false; absent keeps it.
cd.mpc2LedgerHaltEnabled = inputs.mpc2LedgerHaltEnabled ?? cd.mpc2LedgerHaltEnabled ?? null;
// The signed-proof switch, exactly true or false; absent keeps it.
cd.mpc2RequireSignedProof = inputs.mpc2RequireSignedProof ?? cd.mpc2RequireSignedProof ?? null;
// The peer-lockout halt: cleared only by an owner mod naming it (voteMod).
if (inputs.mpc2HaltClear !== undefined && inputs.mpc2HaltClear !== null) {
cd.mpc2Halt = null;
}
// New-recipient hold kill switch. Absent / not exactly true = inert.
cd.newAddressHold = inputs.newAddressHold
? {enabled: inputs.newAddressHold.enabled === true, updated: this.cDate}
: cd.newAddressHold ?? null;
cd.umid = this.umid;
cd.updated = this.cDate;
this.setContractData(cd);
return true;
}/** * Retire a held proposal without executing it. * * A proposal could previously leave `pendingTreasury` only by being * EXECUTED - the single delete sits in commit()'s confirm path - so one * raised by mistake, raised by a key since compromised, or simply no longer * wanted stayed on the identity for ever, and the only way to remove it was * to make the very payment nobody wanted. A real identity accumulated six * of them in a day. * * The proposal is named on `$o.proposal`, NOT on `$o.approved`. A separate * slot is the point: `$o.approved` is what the confirm machinery reads (the * policy-skip gate and the confirm branch both key on it), and keeping a * void's reference out of it means no path can read one operation as the * other. * * Throws a string on refusal; vote() turns that into the transaction's * rejection message, the same way voteMod's throws are handled. */
private async voteVoid(owner: any): Promise<boolean> {
const reference = this.transactions.$o?.proposal;
if (!reference) {
throw "Missing proposal to void";
}
const proposal = this.getActivityStreams(reference);
const proposalData = proposal && proposal.getState();
// $o.proposal is caller-controlled, so prove the named stream really is a
// held proposal before treating it as one - otherwise "void" becomes a
// way to stamp `voided` onto an arbitrary stream this identity can write.
if (
!proposalData ||
!proposalData.requiresTreasury ||
!proposalData.request ||
typeof proposalData.request.$stream !== "string"
) {
throw "Not a proposal";
}
// Same identity test the confirm branch makes: a proposal is answerable
// only by the identity it was raised against, never across identities.
if (proposalData.request.$stream.slice(-64) !== owner.getId()) {
throw "Proposal Mismatched";
}
// Already finished, either way. Voiding an executed proposal would
// rewrite the record of a payment that has happened; voiding a voided one
// does nothing while reading as though it did.
if (proposalData.approved) {
throw "Approved Already";
}
if (proposalData.voided) {
throw "Voided Already";
}
// Who may void. A `read` or `offledger` key never gets here - both are
// refused above, before this branch - so what remains is: the key that
// RAISED it (retracting your own request needs no second party; the
// alternative is simply never confirming, which is the stranded state
// this exists to remove), or any key that could have CONFIRMED it. The
// owner needs no separate test: hasAuthorityStake totals the signing
// authorities' stakes and compares >=, so a stake-100 owner clears 80.
//
// Deliberately NOT gated on expiry. An expired proposal is the one that
// most needs clearing, and refusing to void it would strand exactly the
// records this work exists to retire.
const voidingKey = this.signingKeyHash(owner);
const mayVoid =
this.hasAuthorityStake(80, owner) ||
(proposalData.proposedBy &&
voidingKey &&
proposalData.proposedBy === voidingKey);
if (!mayVoid) {
throw "No authority to void this proposal";
}
this.voided = proposal;
return true;
}/** * Write the terminal record for a voided proposal. * * Moves no money, and cannot. It writes two streams - the proposal and the * identity's pending list - and calls nothing else. The money movers * (commitPreSign, commitGasFree, commitPreSigned) are reachable only * through their own `$entry` values in commit()'s switch, this path never * sets `requiresTreasury`, and vote() returns on a void before the * sign->presign rewrite, so a void cannot become another entry. It also * never touches `this.approved`, which is what commit() keys the * "mark approved and clear the pending entry" block on. */
private async commitVoid(): Promise<boolean> {
const voidOwner = this.getActivityStreams(this.transactions.$i.owner);
const proposalData = this.voided.getState();
// Modelled on the approved/approvedAt pair the confirm path writes, so a
// voided proposal is as unambiguously finished as a confirmed one and a
// later confirm reads it back as terminal rather than as still pending.
// voidedBy records the KEY, for the same reason proposedBy does: both
// halves are signed for the same identity, so only the key says who.
proposalData.voided = this.umid;
proposalData.voidedAt = this.cDate;
proposalData.voidedBy = this.signingKeyHash(voidOwner);
this.voided.setState(proposalData);
// And drop it from the identity's pending list. Reading the owner back
// here is safe, unlike on the confirm path: nothing in this commit has
// written the owner stream, because there is no balance debit on this
// path at all, so this is not the stale pre-commit state that would undo
// one.
const voidOwnerState = voidOwner.getState();
if (voidOwnerState.pendingTreasury) {
delete voidOwnerState.pendingTreasury[this.voided.getId()];
this.prunePendingTreasury(voidOwnerState);
voidOwner.setState(voidOwnerState);
}
// Matches treasury-pending, so whatever transport eventually forwards one
// can forward the other and a subscriber sees a proposal's whole life.
this.event.emit("treasury-voided", {
identity: voidOwner.getId(),
proposal: this.voided.getId(),
umid: this.umid,
voidedBy: proposalData.voidedBy,
when: this.cDate,
});
// A response a caller can tell apart from a confirmation without guessing
// - a confirm returns balance partitions, this returns the proposal it
// retired. The lesson from send(): an operation whose success looks
// identical to a different outcome is how a caller reports the wrong
// thing to a user.
this.returnToRemote({
voided: this.voided.getId(),
umid: this.umid,
when: this.cDate,
});
return true;
}/** The hold's only clock: this.cDate, in milliseconds. */
private holdNowMs(): number {
return new Date(this.cDate).getTime();
}/** A millisecond instant as ISO-8601. */
private holdIso(ms: number): string {
return new Date(ms).toISOString();
}/** sha256 hex of `value` (ActiveCrypto). */
private holdHash(value: string): string {
return (this as any).ActiveCrypto.Hash.getHash(value, "sha256");
}/** The kill switch: contract data newAddressHold.enabled, off unless exactly true. */
private holdSwitchOn(): boolean {
// Read defensively: a missing contract-data wrapper is simply "off".
const wrapper: any = this.getContractData();
const cfg = wrapper && wrapper.data ? wrapper.data.newAddressHold : null;
return !!cfg && typeof cfg === "object" && cfg.enabled === true;
}/**
* Is the identity's own protection on at nowMs? Off until the owner turns
* it on (design §2c): absent, or a block without enabled:true (holdlearn
* alone writes one), reads as off. A turn-off is stored as
* {enabled:false, disableAt} and applies only once cDate reaches
* disableAt; an unparsable disableAt fails safe (on).
*/ private holdProtectionOn(state: any, nowMs: number): boolean {
const wh = state && state.withdrawHold;
if (!wh || typeof wh !== "object") return false;
if (typeof wh.disableAt === "string") {
const at = new Date(wh.disableAt).getTime();
return !Number.isFinite(at) || nowMs < at;
}
return wh.enabled === true;
}/** `${canonicalNetwork}:${address}`; EVM lower-cased only for 0x+40 hex, base58 exact. */ private holdL1Key(network: string, address: string): string {
const addr = String(address ?? "").trim();
const norm = /^0x[0-9a-fA-F]{40}$/.test(addr) ? addr.toLowerCase() : addr;
return `${this.canonicalNetwork(String(network ?? ""))}:${norm}`;
}/** The known-recipient key for a ledger identity: `ledger:<id, lower-cased>`. */
private holdLedgerKey(identity: string): string {
return `ledger:${String(identity).toLowerCase()}`;
}/** Known and settled: present, and either never pending or its own hold has run out. */
private holdKnownSettled(state: any, key: string, nowMs: number): boolean {
const entry = state && state.withdrawHold && state.withdrawHold.known
? state.withdrawHold.known[key]
: undefined;
if (!entry || typeof entry !== "object") return false;
if (entry.until === undefined || entry.until === null) return true;
const until = new Date(entry.until).getTime();
return Number.isFinite(until) && nowMs >= until;
}/** state.withdrawHold.known, created if absent (a fresh object is written back). */
private holdKnownOf(state: any): any {
const wh = state.withdrawHold && typeof state.withdrawHold === "object" ? {...state.withdrawHold} : {};
wh.known = wh.known && typeof wh.known === "object" ? {...wh.known} : {};
state.withdrawHold = wh;
return wh.known;
}/** Evicts the oldest `at` until the known map is within HOLDKNOWNCAP. */
private holdCapKnown(known: any): void {
const keys = Object.keys(known);
if (keys.length <= HOLDKNOWNCAP) return;
const at = (k: string) => {
const t = new Date(known[k] && known[k].at).getTime();
return Number.isFinite(t) ? t : 0;
};
keys.sort((a, b) => at(a) - at(b));
for (let i = 0; i < keys.length - HOLDKNOWNCAP; i++) {
delete known[keys[i]];
}
}/** The recipient is the sender's own wallet, proved from $r.toWallet (design §3 seeding 2). */
private holdIsOwnWallet(to: string): boolean {
if (!this.transactions.$r || !this.transactions.$r.toWallet) return false;
const wallet: any = this.getReadOnlyStream("toWallet");
return (
!!wallet &&
typeof wallet.owner === "string" &&
wallet.owner === this.owner.getId() &&
this.sameL1Address(to, String(wallet.address ?? "")) &&
this.canonicalNetwork(String(wallet.network ?? "")) === this.canonicalNetwork(String(this.layer2TDetails.network))
);
}/** votePreSign: hold an L1 withdrawal to an address this identity has not paid. */
private holdDecideL1(): void {
this.holdPending = null;
if (!this.holdSwitchOn()) return;
const nowMs = this.holdNowMs();
if (!this.holdProtectionOn(this.ownerState, nowMs)) return;
// The destination that will actually be signed (votePreSigned builds
// from this payload), not a field beside it.
const input = this.transactions.$i.owner;
const payload = input.signtx ? input.signtx : input;
const to = payload && typeof payload.to === "string" ? payload.to : "";
if (to && this.holdIsOwnWallet(to)) return;
const key = this.holdL1Key(this.layer2TDetails.network, to);
// An unreadable destination is held (fail-safe), never exempted.
if (to && this.holdKnownSettled(this.ownerState, key, nowMs)) return;
this.holdPending = {key, until: this.holdIso(nowMs + HOLDMS)};
}/** Which shard a sender uses: the first 8 hex chars of sha256(sender stream id), mod the shard count. */
private tenantShardIndex(senderStreamId: string, shards: number): number {
if (!Number.isInteger(shards) || shards < 1) throw "Tenants - shards must be a positive whole number";
const hash: string = this.ActiveCrypto.Hash.getHash(String(senderStreamId), "sha256");
return parseInt(hash.slice(0, 8), 16) % shards;
}/** * Which shard a sender uses under fee config `config`: its reserved shard when `config.priority` names it (a * priority sharded account, set by Varnir with setPriority), otherwise tenantShardIndex. Reserved shards are * indexes 256 to 263 (RESERVED_BASE and PRIORITY_SHARDS_MAX in Varnir.Tenants, written out here because the block * carries no module constants), past every hashed range, so a reshard never maps a hashed sender onto one. */
private tenantShardFor(senderStreamId: string, config: any): number {
const p = config && config.priority;
if (p && typeof p === "object" && Object.keys(p).indexOf(String(senderStreamId)) >= 0) {
const index = p[senderStreamId];
if (!Number.isInteger(index) || index < 256 || index >= 264) throw "Tenants - the tenant's priority shard map is malformed";
return index;
}
return this.tenantShardIndex(senderStreamId, config.shards);
}/** The id of a tenant's shard stream: sha256(tenantId + "tenant.shard." + index), as createShards derives it. */
private tenantShardStreamId(tenantId: string, index: number): string {
return this.ActiveCrypto.Hash.getHash(tenantId + "tenant.shard." + index, "sha256");
}/** The fee for `amount` (a whole-number string) under `op`: bps of the amount rounded down, plus the flat part. An op with no rate costs nothing. */
private tenantComputeFee(config: any, op: string, amount: string): string {
if (typeof amount !== "string" || !/^[0-9]{1,40}$/.test(amount)) throw "Tenants - amount must be a whole-number string";
const rate = config && config.rates && config.rates[op];
if (!rate) return "0";
// Re-checked here as well as in setFeeConfig, so a corrupted config can never give a negative or malformed fee.
if (!Number.isInteger(rate.bps) || rate.bps < 0 || rate.bps > 10000 || typeof rate.flat !== "string" || !/^[0-9]{1,30}$/.test(rate.flat)) throw "Tenants - the tenant's rate is malformed";
return ((BigInt(amount) * BigInt(rate.bps)) / BigInt(10000) + BigInt(rate.flat)).toString();
}/** * A parent's rate for `op`, adjusted for one sub-tenant (sub-tenancy spec §4.2): bps' = floor(bps × (10000 + adjust) * / 10000) and the same for the flat part, the factor never below 0 and bps' never above 10000. `adjust` is the * sub's `terms.baseAdjustBps`, -10000 (free) to +10000 (double). Returns a config tenantComputeFee prices from. */
private tenantAdjustedBase(rates: any, op: string, adjust: any): any {
if (!Number.isInteger(adjust) || adjust < -10000 || adjust > 10000) throw "Tenants - the sub-tenant's baseAdjustBps is malformed";
const rate = rates && rates[op];
const adjusted: any = {};
if (!rate) return { rates: adjusted };
if (!Number.isInteger(rate.bps) || rate.bps < 0 || rate.bps > 10000 || typeof rate.flat !== "string" || !/^[0-9]{1,30}$/.test(rate.flat)) throw "Tenants - the parent's rate is malformed";
const factor = BigInt(Math.max(0, 10000 + adjust));
const bps = (BigInt(rate.bps) * factor) / BigInt(10000);
adjusted[op] = { bps: Number(bps > BigInt(10000) ? BigInt(10000) : bps), flat: ((BigInt(rate.flat) * factor) / BigInt(10000)).toString() };
return { rates: adjusted };
}/** * Refuses an overlay rate above the parent's caps (`terms.overlayCapBps`, `terms.overlayCapFlat`; absent means no * cap) for `op`, or for every op when `op` is null. Checked when the sub sets its rates, when the parent sets new * terms, and again when a fee is worked out, so a corrupted config can never charge past a cap. */
private tenantAssertOverlayCap(rates: any, terms: any, op: string | null): void {
const t: any = terms && typeof terms === "object" ? terms : {};
const capBps = t.overlayCapBps;
const capFlat = t.overlayCapFlat;
if (capBps !== undefined && capBps !== null && !Number.isInteger(capBps)) throw "Tenants - the sub-tenant's overlayCapBps is malformed";
if (capFlat !== undefined && capFlat !== null && (typeof capFlat !== "string" || !/^[0-9]{1,30}$/.test(capFlat))) throw "Tenants - the sub-tenant's overlayCapFlat is malformed";
const ops = op === null ? Object.keys(rates || {}) : [op];
for (const name of ops) {
const r = rates && rates[name];
if (!r) continue;
if (!Number.isInteger(r.bps) || typeof r.flat !== "string" || !/^[0-9]{1,30}$/.test(r.flat)) throw "Tenants - the tenant's rate is malformed";
if ((capBps !== undefined && capBps !== null && r.bps > capBps) || (capFlat !== undefined && capFlat !== null && BigInt(r.flat) > BigInt(capFlat))) {
throw `Tenants - the overlay for ${name} is above the parent's cap (${capBps === undefined || capBps === null ? "no" : capBps} bps, flat ${capFlat === undefined || capFlat === null ? "uncapped" : capFlat}): lower the overlay first`;
}
}
}/** * The membership record's hash for `senderId` under a tenant master (or its copy) (spec §4.5): * sha256(tenantId|subId|senderId|"varnir.tenant.member"), where a sub names its parent and itself and a tenant with no * parent names itself and "". The one derivation: join and revoke write and match with it, a transfer checks with it. */
private tenantMemberHashFor(master: any, senderId: string): string {
const sub = typeof master.parentId === "string";
const tenantId = sub ? master.parentId : master.tenantId;
const subId = sub ? master.tenantId : "";
return this.ActiveCrypto.Hash.getHash(tenantId + "|" + subId + "|" + senderId + "|varnir.tenant.member", "sha256");
}/** * The signing modes that exist (spec §4.5), the one list both Varnir.Tenants (when a mode is set) and a transfer * check (tenantSigningOf) use. `open` and `ticket` are not built: `open` needs a per-sender cap first. */
private tenantSigningModes(): string[] {
return ["live", "membership"];
}/** * How a tenant proves a sender belongs to it (spec §4.5), from its master or its shard copy: absent is "live" (every * tenant from before the modes signs each transfer), anything else outside tenantSigningModes (such as `open`) is * refused rather than guessed at. */
private tenantSigningOf(master: any): any {
const s = master ? master.signing : undefined;
if (s === undefined || s === null) return { mode: "live" };
if (typeof s !== "object" || this.tenantSigningModes().indexOf(s.mode) < 0) throw "Tenants - the tenant's signing mode is malformed";
return s;
}/**
* In `membership` mode the sender's own stream must hold the record `join` wrote (`tm = {h, issued, expires}`):
* `h` recomputed from this tenant (for a sub: its parent and itself) and the sender, unexpired, and issued after the
* tenant's `revokedBefore`. Only Varnir.Tenants `join` writes `tm`, with the user's and the tenant key's signatures.
*/ private tenantAssertMember(master: any, senderStreamId: string, senderState: any, now: number): void {
const h = this.tenantMemberHashFor(master, senderStreamId);
const tm = senderState && senderState.tm;
if (!tm || typeof tm !== "object" || tm.h !== h) throw "Tenants - the sender is not a member of this tenant: join it first";
if (!Number.isSafeInteger(tm.expires) || !(now < tm.expires)) throw "Tenants - the sender's membership has expired: renew it (join)";
const before = Number.isSafeInteger(master.revokedBefore) ? master.revokedBefore : 0;
if (!Number.isSafeInteger(tm.issued) || !(tm.issued > before)) throw "Tenants - the sender's membership was revoked: join again";
}/**
* Refuses a tenant-tagged transaction unless: `master` (the `$r` tenant
* stream's plain state, which the caller may have pointed at any stream, or
* the shard's copy shaped as one by tenantCopyAsMaster) is
* a tenant whose state names the very stream it was read from
* (`masterStreamId`), and not suspended; `shard` (the `$i.tenant` activity) is a shard
* of that tenant at the index and id this sender maps to under the declared
* fee-config version; and the shard's own `tenant` authority signed it (the
* sweeper authority alone does not tag a transaction). The shard is the
* sender's reserved one when that version's `priority` names it
* (tenantShardFor). Returns the fee config in effect for the declared
* version (`{version, shards, rates, priority?, terms?}`):
* the fee must be worked out from that one, never from a newer config.
* The tenant key's signature on the shard is what proves membership in
* `live` signing (absent counts as live), so there the shard must be a
* signed input (`shardSigned`); in `membership` signing the shard may be
* an unsigned `$o` and membership is proved by the sender's record (`open`
* is not available yet and is refused by tenantSigningOf). `signing` is
* tenantSigningOf(master), read once by the caller
* (tenantPrepare), but it is still checked to be the right shard.
*/ private tenantAssertTag(master: any, masterStreamId: string, shard: any, senderStreamId: string, declaredVersion: number, now: number, shardSigned: boolean, signing: any): any {
if (!master || master.kind !== "varnir.tenant" || typeof master.tenantId !== "string") throw "Tenants - the tenant stream is not a tenant";
if (master.tenantId !== masterStreamId) throw "Tenants - the tenant stream is not the tenant it claims to be";
if (master.suspended) throw "Tenants - this tenant is suspended";
const state = shard.getState();
if (!state || state.kind !== "varnir.tenant.shard" || state.tenantId !== master.tenantId) throw "Tenants - the tenant stream is not a shard of this tenant";
let chosen: any;
if (declaredVersion === master.feeConfig.version) {
chosen = master.feeConfig;
} else if (master.previousFeeConfig && master.previousFeeConfig.rates && declaredVersion === master.previousFeeConfig.version && now <= master.previousFeeConfig.until) {
chosen = master.previousFeeConfig;
} else {
throw "Tenants - the fee config version is not current";
}
const inEffect: any = { version: chosen.version, shards: chosen.shards, rates: chosen.rates };
if (chosen.priority !== undefined) inEffect.priority = chosen.priority;
if (chosen.terms !== undefined) inEffect.terms = chosen.terms;
const index = this.tenantShardFor(senderStreamId, inEffect);
if (state.index !== index || shard.getId() !== this.tenantShardStreamId(master.tenantId, index)) throw "Tenants - wrong shard for this sender";
if (signing.mode === "live") {
// Only an input's signature is verified by the engine: a signature claimed for an output proves nothing.
if (!shardSigned) throw "Tenants - this tenant signs every transfer (signing live): name its shard in $i.tenant, signed by the tenant key";
const signed = (this as any).sigs && (this as any).sigs[shard.getId()];
const hashes = signed ? Object.keys(signed) : [];
const ok = (shard.getAuthorities() || []).some((a: any) => a.label === "tenant" && hashes.indexOf(a.hash) !== -1);
if (!ok) throw "Tenants - the tenant key must sign the shard";
}
return inEffect;
}/** * The shard-copy epoch. A copy carries the epoch it was written in, and only a copy of the current epoch is * trusted. Bump it (here, so every contract carrying this block agrees) in the roll-forward after any rollback of * these contracts: copies the older code wrote or left behind are then refused until `syncShards` rewrites them, and * running `syncShards` for every tenant is the first step of that roll-forward (spec §7). */
private tenantCopyEpoch(): number {
return 1;
}/** * The shard's own copy of what a tagged transfer checks (written only by Varnir.Tenants: when the shard is created, * by syncShards and by sweep, always from the master's state), shaped as the master state tenantAssertTag reads. * Used when a tagged transaction carries no `$r.tenant`. Refuses a shard of another tenant, a shard with no copy * (a tenant created before copies existed, until the backfill), a malformed copy, and a copy older than the version * the sender declared. Every entry that changes the master's checks rewrites every shard's copy in the same * transaction, so a copy is never behind its master; the last refusal is a guard, so a fee is never worked out from * a config the shard does not hold. A `suspended` that is anything but `false` counts as suspended. * Two more bounds (spec §5.3): a copy from another contract epoch (tenantCopyEpoch: written before a rollback) is * refused, and so is a copy past its lease (`validUntil`, renewed by every all-shard write), so a copy can never * outlive a master change by more than the lease even when no all-shard write lands (a master-only suspendNow). */
private tenantCopyAsMaster(shard: any, tenantId: string, declaredVersion: number, now: number): any {
const st = shard.getState();
if (!st || st.kind !== "varnir.tenant.shard" || st.tenantId !== tenantId) throw "Tenants - the tenant stream is not a shard of this tenant";
const copy = st.copy;
if (!copy || typeof copy !== "object") throw "Tenants - this shard holds no copy of the tenant's fee config yet: include the tenant master as $r.tenant";
if (copy.epoch !== this.tenantCopyEpoch()) throw "Tenants - this shard's fee config copy is from another contract epoch: include the tenant master as $r.tenant";
if (!Number.isSafeInteger(copy.validUntil) || !Number.isFinite(now) || !(now <= copy.validUntil)) throw `Tenants - this shard's fee config copy has lapsed (valid until ${copy.validUntil}): include the tenant master as $r.tenant`;
const fc = copy.feeConfig;
if (copy.tenantId !== tenantId || !Number.isSafeInteger(copy.seq) || !fc || typeof fc !== "object" || !Number.isInteger(fc.version)) {
throw "Tenants - this shard's fee config copy is malformed: include the tenant master as $r.tenant";
}
if (declaredVersion > fc.version) {
throw `Tenants - this shard has not caught up with fee config version ${declaredVersion} yet (it holds ${fc.version}): retry shortly, or include the tenant master as $r.tenant`;
}
const prices = copy.creditPrices && typeof copy.creditPrices === "object" ? copy.creditPrices : {};
const out: any = { kind: "varnir.tenant", tenantId, suspended: copy.suspended !== false, feeConfig: fc, previousFeeConfig: copy.previousFeeConfig || null, creditPrices: prices };
// Sub-tenancy (spec 2026-10-29-sub-tenancy.md): the parent, the signing mode and revokedBefore, copied only when
// the master has them; tenantPrepare refuses a malformed one rather than reading it as absent.
if (copy.parentId !== undefined) out.parentId = copy.parentId;
if (copy.signing !== undefined) out.signing = copy.signing;
if (copy.revokedBefore !== undefined) out.revokedBefore = copy.revokedBefore;
return out;
}/**
* Called by a contract's vote round. Untagged (no `$i.owner.tenant`) is the
* hub: returns null and changes nothing. Tagged `{id, version}` needs
* `$i.tenant` = this sender's shard. With `$r.tenant` (the tenant master; its
* stream id must be the tagged id) the master is read and is the authority,
* as before shards carried copies. Without it the shard's copy is the
* authority (tenantCopyAsMaster), so the master is not read at all. Runs
* tenantAssertTag and returns
* `{tenantId, shard, fee, usage, op}` for tenantApply (`usage` = the operation's credit price for the tenant, default 1; `op` the operation, which the tenant-charged event names). The fee is in the transfer's own
* asset, worked out from the fee config of the version the sender declared,
* and refused when above the `maxFee` the sender signed in the tag.
*/ private tenantPrepare(op: string, senderStreamId: string, amount: string): any {
const tx: any = this.transactions;
const tag = tx.$i && tx.$i.owner && tx.$i.owner.tenant;
if (!tag) return null;
if (typeof tag.id !== "string" || !/^[0-9a-f]{64}$/.test(tag.id) || !Number.isInteger(tag.version) || typeof tag.maxFee !== "string" || !/^[0-9]{1,40}$/.test(tag.maxFee)) throw "Tenants - the tenant tag must be {id, version, maxFee} with maxFee a whole-number string";
// The shard is a signed input in `live` signing, and may be an unsigned output in `membership` (spec
// 2026-10-29-sub-tenancy.md §4.5; `open` is not available yet); tenantAssertTag decides which the mode allows.
// Named once, never both.
const shardInInputs = !!tx.$i.tenant;
const shardInOutputs = !!(tx.$o && tx.$o.tenant);
if (!shardInInputs && !shardInOutputs) throw "Tenants - a tenant-tagged transaction must name its shard in $i.tenant";
if (shardInInputs && shardInOutputs) throw "Tenants - name the tenant's shard once, in $i.tenant or in $o.tenant";
const ref = tx.$r && tx.$r.tenant;
const readMaster = ref !== undefined && ref !== null;
const refId = readMaster ? (typeof ref === "object" ? ref.$stream : ref) : tag.id;
// Exactly the tagged id: a suffixed id ("<id>:volatile", "<id>:stream") is a different, node-local document.
if (refId !== tag.id) throw "Tenants - $r.tenant must be the tagged tenant stream";
// The tenant key is a tag, never spending authority: the sender must have signed for itself.
const sender = this.getActivityStreams(tx.$i.owner);
if (!sender.hasSignature()) throw "Tenants - the sender must sign a tenant-tagged transaction itself";
const shard = this.getActivityStreams(shardInInputs ? tx.$i.tenant : tx.$o.tenant);
const now = new Date(this.cDate).getTime();
const master: any = readMaster ? this.getReadOnlyStream("tenant") : this.tenantCopyAsMaster(shard, tag.id, tag.version, now);
const signing = this.tenantSigningOf(master);
const inEffect = this.tenantAssertTag(master, refId, shard, senderStreamId, tag.version, now, shardInInputs, signing);
if (master.tenantId !== tag.id) throw "Tenants - the tenant stream is not the tagged tenant";
if (signing.mode === "membership") this.tenantAssertMember(master, senderStreamId, sender.getState(), now);
let price = master.creditPrices && Number.isInteger(master.creditPrices[op]) ? master.creditPrices[op] : 1;
if (master.parentId !== undefined && master.parentId !== null && typeof master.parentId !== "string") throw "Tenants - the tenant's parentId is malformed";
if (typeof master.parentId !== "string") {
// A tenant with no parent: exactly the path from before sub-tenancy.
if (tag.parentVersion !== undefined || (tx.$r && tx.$r.parent !== undefined)) throw "Tenants - this tenant has no parent: its tag carries no parentVersion and no $r.parent";
const fee = this.tenantComputeFee(inEffect, op, amount);
if (BigInt(fee) > BigInt(tag.maxFee)) throw `Tenants - the tenant fee ${fee} is above the maximum ${tag.maxFee} the sender signed`;
return { tenantId: tag.id, shard, fee, usage: price, op };
}
// A sub-tenant (spec §4): base = the parent's rate adjusted by the sub's terms, overlay = the sub's own rate, each
// rounded down on its own; the parent master is read, exactly the stream the sub names, and must be a top-level
// tenant (one level), not suspended, at the version the sender's tag priced the base from.
if (!Number.isInteger(tag.parentVersion)) throw "Tenants - a sub-tenant's tag must carry the parentVersion its base was priced from";
const pref = tx.$r && tx.$r.parent;
const parentRefId = pref !== null && typeof pref === "object" ? pref.$stream : pref;
if (parentRefId !== master.parentId) throw "Tenants - $r.parent must be the sub-tenant's parent master";
const parent: any = this.getReadOnlyStream("parent");
if (!parent || parent.kind !== "varnir.tenant" || parent.tenantId !== parentRefId || !parent.feeConfig) throw "Tenants - $r.parent is not the sub-tenant's parent";
if (parent.parentId !== undefined && parent.parentId !== null) throw "Tenants - a sub-tenant's parent cannot itself be a sub-tenant";
if (parent.suspended !== false) throw "Tenants - this sub-tenant's parent is suspended";
let base: any;
if (tag.parentVersion === parent.feeConfig.version) {
base = parent.feeConfig;
} else if (parent.previousFeeConfig && parent.previousFeeConfig.rates && tag.parentVersion === parent.previousFeeConfig.version && now <= parent.previousFeeConfig.until) {
base = parent.previousFeeConfig;
} else {
throw "Tenants - the parent's fee config version is not current";
}
const terms: any = inEffect.terms && typeof inEffect.terms === "object" ? inEffect.terms : {};
this.tenantAssertOverlayCap(inEffect.rates, terms, op);
const baseFee = this.tenantComputeFee(this.tenantAdjustedBase(base.rates, op, terms.baseAdjustBps === undefined ? 0 : terms.baseAdjustBps), op, amount);
const overlay = this.tenantComputeFee(inEffect, op, amount);
const fee = (BigInt(baseFee) + BigInt(overlay)).toString();
if (BigInt(fee) > BigInt(tag.maxFee)) throw `Tenants - the tenant fee ${fee} is above the maximum ${tag.maxFee} the sender signed`;
// Credits are the parent's: its price for the op (the sub holds none).
price = parent.creditPrices && Number.isInteger(parent.creditPrices[op]) ? parent.creditPrices[op] : 1;
return { tenantId: tag.id, shard, fee, base: baseFee, overlay, usage: price, op };
}/**
* Called by the commit round with what tenantPrepare returned: adds the fee to the shard's `fees` under `assetKey`
* ("network:token") and the operation's credit price to its usage counter. For a sub-tenant the overlay goes to
* `fees` and the base to `upstream` (swept to the parent); an ordinary tenant's shard is written exactly as before.
*/ private tenantApply(prep: any, assetKey: string): void {
const st: any = prep.shard.getState();
const fees: any = st.fees || {};
const sub = prep.base !== undefined;
fees[assetKey] = (BigInt(fees[assetKey] || "0") + BigInt(sub ? prep.overlay : prep.fee)).toString();
const upstream: any = st.upstream || {};
if (sub) upstream[assetKey] = (BigInt(upstream[assetKey] || "0") + BigInt(prep.base)).toString();
prep.shard.setState({ ...st, fees, usage: (BigInt(st.usage || "0") + BigInt(prep.usage)).toString(), ...(sub ? { upstream } : {}) });
}/** * Adds `amount` credits to a tenant master's state (grantCredits, and a credits payout settled by * CryptoTransfer `tenantsettle`): what the tenant owes from an overrun is paid first, only the rest becomes * balance, and any grace is cleared. Mutates `state`. */
private tenantAddCredits(state: any, amount: bigint): void {
const owed = BigInt(state.owed || "0");
const paid = owed < amount ? owed : amount;
state.owed = (owed - paid).toString();
state.credits = (BigInt(state.credits || "0") + amount - paid).toString();
state.graceUntil = null;
// The part of owed that came from a parent's sub draws this interval (Varnir.Tenants sweep) is never more than what
// is still owed: a paid-off debt must not count again at the parent's next sweep (sub-tenancy spec §11).
if (state.subOwed !== undefined && state.subOwed !== null && BigInt(state.subOwed) > BigInt(state.owed)) state.subOwed = state.owed;
}/** A tenant's payout list with every open request kept and only the newest 100 closed ones (settled, rejected, cancelled); the order is kept. */
private tenantTrimPayouts(list: any[]): any[] {
let closed = 0;
const out: any[] = [];
for (let i = list.length - 1; i >= 0; i--) {
if (list[i].status !== "requested") {
closed++;
if (closed > 100) continue;
}
out.unshift(list[i]);
}
return out;
}/**
* Vote round, with what tenantPrepare / marketsShardPrep returned: what the op takes from its shard's credit FLOAT.
* Returns null when the shard holds no float: a tenant not yet switched over by Varnir.Tenants `enableFloat` (the OLD
* PATH: the op's price is only counted in `usage` and drawn from the master at the sweep, exactly as before stage D).
* NEW PATH, the shard has a float (whole credits, may be negative):
* - O1, a normal op (`exit` false: transfer, market.mint, market.fill): needs `float >= price`, else REFUSED (the
* hard stop); nothing is written, because the refusal is the vote's.
* - O2, an exit op (`exit` true: market.propose, market.dispute): NEVER refused. It is charged while the float stays
* at or above `-floatOverdraft` (the shard's overdraft, set by Varnir.Tenants); the part of the price that would
* take it lower runs uncharged (recorded, so Varnir carries at most that). A malformed float never blocks an exit
* op either: it runs uncharged.
* Returns `{next, charged, uncharged}` (BigInt) for tenantFloatApply.
*/ private tenantFloatPlan(prep: any, exit: boolean): any {
const st: any = prep.shard.getState();
if (st.float === undefined || st.float === null) return null;
const price = BigInt(prep.usage);
const wellFormed = typeof st.float === "string" && /^-?[0-9]{1,30}$/.test(st.float) && Number.isSafeInteger(st.floatOverdraft) && st.floatOverdraft >= 0;
if (!wellFormed) {
if (exit) return { next: null, charged: BigInt(0), uncharged: price };
throw "Tenants - this tenant's shard float is malformed: the operation is refused";
}
const float = BigInt(st.float);
if (!exit) {
if (float < price) throw `Tenants - this tenant is out of credits (shard float ${float}, this operation costs ${price}): its operations stop until it is topped up; try again in a few minutes`;
return { next: float - price, charged: price, uncharged: BigInt(0) };
}
const floor = BigInt(0) - BigInt(st.floatOverdraft);
let charged = price;
if (float - price < floor) charged = float > floor ? float - floor : BigInt(0);
return { next: float - charged, charged, uncharged: price - charged };
}/**
* Commit round, AFTER tenantApply (which writes the shard's fees and usage): debits the float by `plan.charged` in the
* same transaction as the op, keeps the running total of what exit ops ran uncharged (`floatUncharged`), and records
* that this op's usage was settled by the float (`floatPaid` += its price, charged or not). The float sweep draws
* from the master any usage NOT settled here (usage - floatPaid): an op that reached a contract version without this
* block (callable until the version locks hold) is still billed. Emits `tenant-float-low` when the float can no
* longer pay this op's price again or is below a tenth of its target (`floatTarget`), so the sweeper funds the shard
* on demand (Varnir.Tenants `fundShards`). No float plan (the old path) writes nothing; a shard that holds a float
* with no plan (a caller that skipped tenantFloatPlan) is refused rather than left unbilled.
* Stage F1c: every metered op is itemised for the tenant's charge history with a `tenant-charged` event
* `{tenantId, shard, op, price, charged, uncharged, float}` (only when the prep names its `op`, so the stage E
* settle refund, which passes none, emits none). On the old path (no float) `charged` is the price the sweep draws
* from the master later and `float` is false; on the float, what this op took from it now.
*/ private tenantFloatApply(plan: any, prep: any): void {
const st: any = prep.shard.getState();
if (!plan) {
if (st.float !== undefined && st.float !== null) throw "Tenants - this shard runs on the credit float but the operation was not planned against it";
if (typeof prep.op === "string") this.event.emit("tenant-charged", { tenantId: prep.tenantId, shard: st.index, op: prep.op, price: String(prep.usage), charged: String(prep.usage), uncharged: "0", float: false, umid: this.umid });
return;
}
const whole = (v: any) => BigInt(typeof v === "string" && /^[0-9]{1,30}$/.test(v) ? v : "0");
const price = plan.charged + plan.uncharged;
const uncharged = (whole(st.floatUncharged) + plan.uncharged).toString();
const paid = (whole(st.floatPaid) + price).toString();
const float = plan.next === null ? st.float : plan.next.toString();
prep.shard.setState({ ...st, float, floatUncharged: uncharged, floatPaid: paid });
if (typeof prep.op === "string") this.event.emit("tenant-charged", { tenantId: prep.tenantId, shard: st.index, op: prep.op, price: price.toString(), charged: plan.charged.toString(), uncharged: plan.uncharged.toString(), float: true, umid: this.umid });
const target = whole(st.floatTarget);
if (plan.next === null || plan.next < price || plan.next * BigInt(10) < target) {
this.event.emit("tenant-float-low", { tenantId: prep.tenantId, shard: st.index, float, target: target.toString(), charged: plan.charged.toString(), uncharged: plan.uncharged.toString() });
}
}/** * Credits paid IN to a tenant master that runs on the float (Varnir.Tenants grantCredits and the float sweep, * Varnir.CryptoTransfer's credits payout): what it owes is paid first, and grace ends only when nothing is owed any * more (a part payment never restarts the grace clock, unlike the old path's tenantAddCredits). Mutates `fm`. */
private floatCredit(fm: any, amount: bigint): void {
if (amount <= BigInt(0)) return;
const owed = BigInt(fm.owed || "0");
const paid = owed < amount ? owed : amount;
fm.owed = (owed - paid).toString();
fm.credits = (BigInt(fm.credits || "0") + amount - paid).toString();
if (owed - paid === BigInt(0)) fm.graceUntil = null;
if (fm.subOwed !== undefined && fm.subOwed !== null && BigInt(fm.subOwed) > BigInt(fm.owed)) fm.subOwed = fm.owed;
if (fm.priceOwed !== undefined && fm.priceOwed !== null && BigInt(fm.priceOwed) > BigInt(fm.owed)) fm.priceOwed = fm.owed;
}/** * Varnir's price for a tenant-tagged withdrawal (D4): the network's Instant weight for the asset class (creditsWeight, * live-priced where the weights say so) plus `varnirPrices.withdrawal[network][class]`, the fixed surcharge that prices * in consolidation, gas and energy top-ups and Tron activation (Varnir.Plans validates it). Refused, never priced at * 0: no price table on the config (varnirPrices off), no weight for the network, or no surcharge listed for it. */
private tenantWithdrawPrice(cfg: any, canonicalNet: string, assetClass: string): number {
const vp = cfg ? cfg.varnirPrices : null;
if (!vp || typeof vp !== "object" || !vp.withdrawal || typeof vp.withdrawal !== "object") {
throw "Tenants - Varnir's price table is off, so a tenant cannot pay for a withdrawal yet: withdraw without the tenant tag";
}
const weight = this.creditsWeight(cfg.weights, canonicalNet, assetClass, "instant");
if (typeof weight === "string") throw weight;
const entry = vp.withdrawal[canonicalNet];
const extra = entry && typeof entry === "object" ? entry[assetClass] : undefined;
if (!Number.isInteger(extra) || extra < 0 || extra > 1000000) {
throw `Tenants - Varnir has no tenant price for ${assetClass} withdrawals on ${canonicalNet}: withdraw without the tenant tag`;
}
return weight + extra;
}/**
* votePreSign, for a withdrawal carrying `$i.owner.tenant`: what it reserves, as `{prep, price, plan}`.
* tenantPrepare checks the tag exactly as for a transfer (the tenant and the sender's shard, suspension, the tenant
* key or the membership record, the fee config version) and prices the tenant's user fee from `rates.withdrawal` on
* the amount, refused above the `maxFee` the sender signed. Refused before anything moves:
* - the shard holds no float: a tenant not switched to the float keeps the rule from before stage E (no tag on a
* withdrawal), so a deploy alone changes nothing;
* - Varnir's price is not set (tenantWithdrawPrice);
* - O1: the float cannot pay the price (tenantFloatPlan, "this tenant is out of credits");
* - the sender cannot pay the amount (plus the gas hold on a native send) and the user fee together.
* The sender's own credits, plan and monthly allowance are never read (D2; D5 for a tagged op).
*/ private async tenantWithdrawPlan(senderBalance: BN, totalNeeded: BN): Promise<any> {
const amount = this.getBN(this.transactions.$i.owner.amount).toString();
const prep = this.tenantPrepare("withdrawal", this.owner.getId(), amount);
const st: any = prep.shard.getState();
if (st.float === undefined || st.float === null) {
throw "Tenants - a tenant tag is accepted on a withdrawal only once the tenant runs on the credit float: withdraw without the tenant tag";
}
// Security review (stage E): the tenant pays Varnir's price here, so the ledger does not rely on the gateway alone.
// The sender must hold a valid membership record for the tagged tenant whatever its signing mode (tenantPrepare
// already checks it in membership signing), and the tenant must have opted in to paying for withdrawals by setting a
// `rates.withdrawal` fee in the fee config the sender declared (0 bps and "0" flat to cover it in full).
const tx: any = this.transactions;
// Review (MEDIUM): the tenant's own key must sign the shard ($i.tenant) on every tagged withdrawal, whatever the
// signing mode. A withdrawal spends the tenant's credits at Varnir's price, so it is the tenant's to approve one by
// one: its gateway, which holds that key, applies the tenant's limits (assets, minimums, daily caps) before it
// signs, and no other path (another gateway, an old build, a membership-only sender) can bill the tenant.
const shardSigs = tx.$i.tenant ? (this as any).sigs && (this as any).sigs[prep.shard.getId()] : null;
const shardHashes = shardSigs ? Object.keys(shardSigs) : [];
if (!(prep.shard.getAuthorities() || []).some((a: any) => a.label === "tenant" && shardHashes.indexOf(a.hash) !== -1)) {
throw "Tenants - a tenant-tagged withdrawal needs the tenant key's signature on the shard ($i.tenant): withdraw through the tenant's gateway";
}
const now = new Date(this.cDate).getTime();
const master: any = tx.$r && tx.$r.tenant !== undefined && tx.$r.tenant !== null ? this.getReadOnlyStream("tenant") : this.tenantCopyAsMaster(prep.shard, prep.tenantId, tx.$i.owner.tenant.version, now);
this.tenantAssertMember(master, this.owner.getId(), this.ownerState, now);
const declared = master.feeConfig && master.feeConfig.version === tx.$i.owner.tenant.version ? master.feeConfig : master.previousFeeConfig;
const rate = declared && declared.rates ? declared.rates.withdrawal : undefined;
if (!rate || typeof rate !== "object") throw "Tenants - this tenant has set no withdrawal fee (rates.withdrawal), so it does not pay for withdrawals: withdraw without the tenant tag";
// Review N2: at most 5 open reserves per sender and 1,000 per shard, so one member cannot block the others.
const open: any = st.wdOpen && typeof st.wdOpen === "object" ? st.wdOpen : {};
const openIds = Object.keys(open);
if (openIds.length >= 1000) throw "Tenants - this tenant shard has 1000 withdrawals in flight: try again once some have settled";
const mine = openIds.filter((k) => open[k] && typeof open[k] === "object" && open[k].sender === this.owner.getId()).length;
if (mine >= 5) throw "Tenants - you have 5 tenant-paid withdrawals in flight: wait for one to settle (or withdraw without the tenant tag)";
const cfg = await this.readPlansConfig();
const assetClass = this.layer2TDetails.token === "#native" ? "native" : "token";
const canonicalNet = this.canonicalNetwork(String(this.layer2TDetails.network));
const base = this.tenantWithdrawPrice(cfg, canonicalNet, assetClass);
// Stage F2: the source-count part, from the values the quote bound (null while Varnir's block is not written).
const masterRead = !!(tx.$r && tx.$r.tenant !== undefined && tx.$r.tenant !== null);
const consolidation = this.tenantWithdrawConsolidation(cfg, canonicalNet, assetClass, master, masterRead, st, now);
const price = base + (consolidation ? consolidation.sourcePrice : 0);
const plan = this.tenantFloatPlan({ ...prep, usage: String(price) }, false);
const need = totalNeeded.add(prep.fee);
if (senderBalance.lt(need)) throw `Part-Balance to low : ${senderBalance} < ${need}`;
return { prep, price: String(price), plan, consolidation: consolidation ? { ...consolidation.recorded, base } : null };
}/**
* Stage F2 (docs/plans/tenant-pays-stage-f-consolidation-pricing.md §3.5, §4.2; docs/contracts/
* tenant-consolidation-config.md): the source-count part of a tagged withdrawal's price, from
* `varnirPrices.consolidation` (Varnir's block on the plans config) and the values the quote bound into the tag
* (`$i.owner.tenant.consolidation = {version, multiplierVersion, sources, prepaid}`, which the sender signed):
* - no block on the config: null, and the withdrawal is priced as before F2 (a deploy alone changes nothing). A tag
* that binds values anyway is refused, never priced from values nothing checks;
* - a block: the tag must bind values. The block is the one at `version` (the current one, or the previous one for
* the 10 minutes after it was replaced; older is refused: "prices changed"); the multiplier is the tenant's at
* `multiplierVersion` (the parent's for a sub-tenant), with the same rule. `sources` above the block's `instantMax`
* is refused (the instant limit), and so is `prepaid` above `sources`;
* - a block that is unreadable (any field missing or out of its range, or no unit for this network and class) is
* refused, never priced at 0.
* Returns `{sourcePrice, recorded}`: `recorded` is every value the price used, which the reserve keeps so the settle
* (and anyone later) prices from those alone.
*/ private tenantWithdrawConsolidation(cfg: any, canonicalNet: string, assetClass: string, master: any, masterRead: boolean, shardState: any, now: number): any {
const PREVIOUS_MS = 10 * 60 * 1000;
const tag: any = this.transactions.$i.owner.tenant;
const bound = tag.consolidation;
const c = cfg && cfg.varnirPrices ? cfg.varnirPrices.consolidation : undefined;
if (c === undefined || c === null) {
if (bound !== undefined) throw "Tenants - Varnir prices no withdrawal by its sources yet, but this quote bound source values: request a new quote";
return null;
}
const unreadable = "Tenants - Varnir's consolidation prices are unreadable: withdraw without the tenant tag";
const isMap = (m: any) => !!m && typeof m === "object" && !Array.isArray(m);
const count = (n: any, lo: number, hi: number) => Number.isSafeInteger(n) && n >= lo && n <= hi;
if (!isMap(bound) || Object.keys(bound).length !== 4 || !count(bound.version, 1, 1000000000) || !count(bound.multiplierVersion, 0, 1000000000) || !count(bound.sources, 0, 100000) || !count(bound.prepaid, 0, 100000)) {
throw "Tenants - Varnir prices this withdrawal by its sources: the tag must bind {version, multiplierVersion, sources, prepaid} from a quote; request a new quote";
}
if (!isMap(c) || !count(c.version, 1, 1000000000)) throw unreadable;
let block: any;
if (bound.version === c.version) block = c;
else if (isMap(c.previous) && c.previous.version === bound.version && count(c.previous.replacedAt, 0, Number.MAX_SAFE_INTEGER) && now <= c.previous.replacedAt + PREVIOUS_MS) block = c.previous;
else throw "Tenants - Varnir's prices changed since this quote: request a new quote";
// Every value the price uses, held to the ranges Varnir.Plans validConsolidation enforces (fail closed).
if (!count(block.freeSources, 0, 10) || !count(block.instantMax, 1, 200) || !count(block.prepaidOffsetPct, 0, 100) || typeof block.refundUnused !== "boolean" || typeof block.quoteEnforced !== "boolean" || typeof c.quoteEnforced !== "boolean") throw unreadable;
// Security review (F2): the quote's `sources` is the tenant's claim, and only minigate can hold a payout that needs
// more (the over-quote hold, F3). Until Varnir's block says minigate enforces it, the block prices nothing: refused,
// never an under-quote paid at the quoted price. Varnir sets `quoteEnforced` with the F3 deploy.
// The switch is read from the CURRENT block (review L1), the prices from the one the quote named, so turning
// enforcement off stops pricing at once, even for a quote made under the previous block.
if (c.quoteEnforced !== true || block.quoteEnforced !== true) throw "Tenants - Varnir's gateways do not enforce source quotes yet (quoteEnforced is off): withdraw without the tenant tag";
if (!Array.isArray(block.tiers) || block.tiers.length < 1 || block.tiers.length > 8) throw unreadable;
const tiers: any[] = [];
for (let i = 0; i < block.tiers.length; i++) {
const t = block.tiers[i];
if (!isMap(t) || !count(t.from, 1, 200) || !count(t.pct, 100, 1000)) throw unreadable;
if (i === 0 ? t.from !== block.freeSources + 1 : t.from <= tiers[i - 1].from || t.pct < tiers[i - 1].pct) throw unreadable;
tiers.push({ from: t.from, pct: t.pct });
}
const unitEntry = isMap(block.unit) && isMap(block.unit[canonicalNet]) ? block.unit[canonicalNet][assetClass] : undefined;
if (!count(unitEntry, 1, 10000)) throw `Tenants - Varnir has no consolidation price for ${assetClass} withdrawals on ${canonicalNet}: withdraw without the tenant tag`;
let unit = unitEntry;
const liveEntry = isMap(block.unitLive) && isMap(block.unitLive[canonicalNet]) ? block.unitLive[canonicalNet][assetClass] : undefined;
if (liveEntry !== undefined && typeof liveEntry !== "boolean") throw unreadable;
if (liveEntry === true) {
// Live-priced (eth, sep token): the network's Economy weight, never below the unit (its floor).
const economy = this.creditsWeight(cfg.weights, canonicalNet, assetClass, "economy");
if (typeof economy === "string") throw economy;
if (economy > unit) unit = economy;
// Review I1: never above the unit's range (Varnir.Plans validConsolidation: 1-10,000), whatever the live reading.
if (unit > 10000) unit = 10000;
}
if (bound.sources > block.instantMax) throw `Tenants - this withdrawal needs ${bound.sources} sources; the limit is ${block.instantMax}. Withdraw a smaller amount`;
if (bound.prepaid > bound.sources) throw "Tenants - the quote binds more prepaid sources than sources: request a new quote";
// Security review (F2): the binding is signed by the sender and the tenant, not by Varnir, and the quote cannot know
// which wallets the payout will draw. So a quote may not claim the prepaid discount: it is given only at settle
// (tenantWdUnused), for each source a live minigate key names whose on-ledger mark (stage F4, Varnir.AssignOwner)
// the settle checks and spends, and it can only lower the charge. Under-stated `sources` needs no such check: minigate never moves more sources than the
// quote bound (the over-quote hold, F3), so an under-quote only holds the tenant's own payout.
if (bound.prepaid !== 0) throw "Tenants - a quote cannot claim prepaid sources: bind prepaid 0; the discount is applied at settle, from each source wallet's on-ledger mark";
// The multiplier: the tagged tenant's own, a sub-tenant's parent's (whose credits it spends). From the master when
// it was read, from the shard's copy otherwise (Varnir.Tenants writes it there with every all-shard write).
let m: any;
if (typeof master.parentId === "string") {
const parent: any = this.getReadOnlyStream("parent");
m = parent ? parent.consolidationMultiplier : undefined;
} else if (masterRead) {
m = master.consolidationMultiplier;
} else {
const copy = shardState && shardState.copy;
m = copy ? copy.consolidationMultiplier : undefined;
}
const allowed = [100, 125, 150, 200, 300];
let multiplierPct: number;
if (m === undefined || m === null) {
if (bound.multiplierVersion !== 0) throw "Tenants - this tenant's consolidation multiplier changed since this quote: request a new quote";
multiplierPct = 100;
} else {
if (!isMap(m) || allowed.indexOf(m.pct) === -1 || !count(m.version, 1, 1000000000)) throw "Tenants - this tenant's consolidation multiplier is malformed: withdraw without the tenant tag";
if (bound.multiplierVersion === m.version) multiplierPct = m.pct;
else if (isMap(m.previous) && m.previous.version === bound.multiplierVersion && allowed.indexOf(m.previous.pct) !== -1 && count(m.previous.until, 0, Number.MAX_SAFE_INTEGER) && now <= m.previous.until) multiplierPct = m.previous.pct;
else throw "Tenants - this tenant's consolidation multiplier changed since this quote: request a new quote";
}
const recorded = {
version: bound.version,
multiplierVersion: bound.multiplierVersion,
multiplierPct,
freeSources: block.freeSources,
unit,
tiers,
prepaidOffsetPct: block.prepaidOffsetPct,
refundUnused: block.refundUnused,
sources: bound.sources,
prepaid: bound.prepaid,
};
return { sourcePrice: this.tenantSourcePrice(recorded, bound.sources, bound.prepaid), recorded };
}/** * The source-count price (plan §3.5) for `sources` source wallets, `prepaid` of them with their sweep prepaid, from * recorded values `r` only: each source past the first `freeSources` costs `unit` x its tier's pct, a prepaid source * among those gets `prepaidOffsetPct` of one unit off (at most one per priced source, so a source still pays any tier * premium), the total is scaled by the multiplier and rounded UP to a whole credit. Never below 0. Whole numbers * throughout (pct x 100 scale), so every node gets the same figure. */
private tenantSourcePrice(r: any, sources: number, prepaid: number): number {
let sum = 0;
for (let k = r.freeSources + 1; k <= sources; k++) {
let pct = r.tiers[0].pct;
for (const t of r.tiers) if (k >= t.from) pct = t.pct;
sum += r.unit * pct;
}
const priced = sources > r.freeSources ? sources - r.freeSources : 0;
const offsets = prepaid < priced ? prepaid : priced;
let remaining = sum - offsets * r.unit * r.prepaidOffsetPct;
if (remaining < 0) remaining = 0;
const scaled = remaining * r.multiplierPct;
return Math.floor((scaled + 9999) / 10000);
}/** * commitPreSign, with this.tenantWithdraw, in the presign's own transaction: takes the tenant's user fee from the * sender's partition (the one the amount left), counts the price in the shard's usage and takes it from the float * (tenantFloatApply: floatPaid and floatLow, as for a transfer), and records the reserve as `tenantReserve` on the * presign the loop below writes. The fee is held on the presign, not yet the tenant's: tenantwdsettle pays it to the * shard's fees when the payout was sent, and back to the sender when it was not. */
private tenantWithdrawTake(ownerState: any): void {
const w = this.tenantWithdraw;
const fee = this.getBN(w.prep.fee);
if (fee.gt(0)) this.setL2Balance(ownerState, this.getBN(this.getL2Balance(ownerState)).sub(fee));
const st: any = w.prep.shard.getState();
const fees: any = st.fees || {};
w.prep.shard.setState({ ...st, fees, usage: (BigInt(st.usage || "0") + BigInt(w.price)).toString() });
this.tenantFloatApply(w.plan, w.prep);
this.eventData.tenantReserve = {
tenantId: w.prep.tenantId,
shard: w.prep.shard.getId(),
price: w.price,
fee: w.prep.fee,
...(w.prep.base !== undefined ? { base: w.prep.base, overlay: w.prep.overlay } : {}),
// Stage F2: every value the price used (tenantWithdrawConsolidation), so the settle reads these alone.
...(w.consolidation ? { consolidation: w.consolidation } : {}),
network: this.layer2TDetails.network,
token: this.layer2TDetails.token,
state: "reserved",
at: this.cDate,
};
}/** * A tagged presign that will never be signed: no l1.sign, not armed for Tron mpc2 (`tronMpc`: its bytes may still be * recorded as landed), not held, and older than 7 days of consensus time (TENANT_WD_EXPIRY_MS). */
private tenantWithdrawExpired(pre: any): boolean {
const TENANT_WD_EXPIRY_MS = 7 * 24 * 60 * 60 * 1000;
if (pre.signedStream || pre.confirmed || pre.tronMpc !== undefined) return false;
const now = new Date(this.cDate).getTime();
let from = new Date(pre.tenantReserve.at).getTime();
if (pre.hold && pre.hold.state === "held") {
// Review N2: a hold whose `until` passed and that is never signed expires too, counted from `until`.
const until = new Date(pre.hold.until).getTime();
if (!Number.isFinite(until) || now < until) return false;
if (until > from) from = until;
}
return Number.isFinite(from) && now >= from + TENANT_WD_EXPIRY_MS;
}/** commitPreSign: adds the presign to its shard's open reserves (`wdOpen`: presign id -> consensus ms). */
private tenantWithdrawIndex(presignId: string): void {
const shard = this.tenantWithdraw.prep.shard;
const st: any = shard.getState();
const fees: any = st.fees || {};
const wdOpen: any = st.wdOpen && typeof st.wdOpen === "object" ? { ...st.wdOpen } : {};
wdOpen[presignId] = { at: new Date(this.cDate).getTime(), sender: this.owner.getId() };
shard.setState({ ...st, fees, usage: st.usage || "0", wdOpen });
}/** * `tenantwdsettle` vote (gateway only, assertMinigateSigner): settles a tagged withdrawal's reserve once, from the * outcome the contracts recorded; the gateway only says which withdrawal. Streams: `$o.presign` (the l1.presign with * `tenantReserve` still "reserved"), `$o.tenant` (that reserve's shard), `$o.owner` (the sender, when the held fee * goes back to it) and `$r.signed` (the presign's l1.sign, once it has one). The outcome: * - "sent": Varnir.ConfirmWithdraw confirmed success. The price stays charged; the held fee goes to the shard's fees * (tenantApply, as a transfer's fee; a sub's base to upstream). * - "failed-on-chain": confirmed failed ON chain, or failed before inclusion after a cancel that burnt gas * (`cancelFee` above 0). The price stays charged (D3: the gas was a real cost; the cancel case is this build's * reading of D3, the safer one for Varnir). The fee goes back to the sender, as its own credits would. * - "not-sent": confirmed failed before inclusion with no gas burnt (expired, nonce-consumed, a cancel that cost * nothing, a Bitcoin conflict), or a held withdrawal cancelled before it was ever signed. The price goes back to * the float and the fee to the sender. A shard no longer on the float (disableFloat since) has no float to refund * into: the refund lapses, recorded as "refund-lapsed" (safer for Varnir; a rollback is rare). * Refused while the payout has no outcome yet and for a reserve already settled: the presign is an output, so it is * settled exactly once. */
private async voteTenantWdSettle(): Promise<boolean> {
const tx: any = this.transactions;
// Who asks decides nothing (the outcome is the ledger's own): a minigate, or the tenant's sweeper key signing the
// shard as $i.tenant (tenant-admin settle-withdrawals, manual recovery).
const shardRef = tx.$i && tx.$i.tenant ? tx.$i.tenant : tx.$o && tx.$o.tenant;
if (!tx.$o || !tx.$o.presign || !shardRef) throw "Tenants - tenantwdsettle needs $o.presign and the shard ($o.tenant, or $i.tenant signed by the sweeper key)";
if (tx.$i && tx.$i.tenant) {
const named = this.getActivityStreams(tx.$i.tenant);
const sweeperSigs = (this as any).sigs && (this as any).sigs[named.getId()];
const hashes = sweeperSigs ? Object.keys(sweeperSigs) : [];
if (!(named.getAuthorities() || []).some((a: any) => a.label === "sweeper" && a.stake === 100 && hashes.indexOf(a.hash) !== -1)) throw "Tenants - the shard's sweeper key must sign a tenantwdsettle that names it in $i.tenant";
} else {
await this.assertMinigateSigner();
}
const presign = this.getActivityStreams(tx.$o.presign);
const pre: any = presign.getState();
const r: any = pre && pre.tenantReserve;
if (!r || typeof r !== "object") throw "Tenants - this presign carries no tenant reserve";
if (r.state !== "reserved") throw `Tenants - this withdrawal's tenant reserve is already settled (${r.state})`;
if (typeof r.price !== "string" || !/^[0-9]{1,30}$/.test(r.price) || typeof r.fee !== "string" || !/^[0-9]{1,40}$/.test(r.fee)) throw "Tenants - this presign's tenant reserve is malformed";
const shard = this.getActivityStreams(shardRef);
if (shard.getId() !== r.shard) throw "Tenants - $o.tenant is not the shard this withdrawal reserved from";
const sst: any = shard.getState();
if (!sst || sst.kind !== "varnir.tenant.shard" || sst.tenantId !== r.tenantId) throw "Tenants - $o.tenant is not a shard of the reserving tenant";
let outcome: string;
if (pre.signedStream) {
const ref = tx.$r && tx.$r.signed;
const refId = ref && typeof ref === "object" ? ref.$stream : ref;
if (refId !== pre.signedStream) throw "Tenants - $r.signed must be this presign's l1.sign";
const l1: any = this.getReadOnlyStream("signed");
if (!l1 || l1.preSignedStream !== presign.getId()) throw "Tenants - $r.signed is not this presign's l1.sign";
const c = l1.confirmed;
if (!c || typeof c !== "object") throw "Tenants - this withdrawal is not confirmed yet";
// A Bitcoin cancel (our RBF replacement, `btc.kind` "cancel") confirmed: its fee was a real cost, so the tenant
// keeps paying (security review L1, the safer reading for Varnir), as for an EVM cancel that burnt gas.
const btcCancel = !!c.btc && typeof c.btc === "object" && c.btc.kind === "cancel";
if (c.success === true) outcome = "sent";
else if (c.outcome === "failed-before-inclusion" && !this.getBN(c.cancelFee || 0).gt(0) && !btcCancel) outcome = "not-sent";
else outcome = "failed-on-chain";
} else if (pre.hold && pre.hold.state === "cancelled") {
outcome = "not-sent";
} else if (this.tenantWithdrawExpired(pre)) {
// Never signed or armed, not held (or held past its `until`), for 7 days: the reserve settles as never sent and
// the sign gates refuse the presign from now on; the amount stays held (review N1, tenantwdrelease).
outcome = "expired";
} else {
throw "Tenants - this withdrawal has no outcome yet (neither signed nor cancelled)";
}
let owner: any = null;
if ((outcome !== "sent" && BigInt(r.fee) > BigInt(0)) || outcome === "expired") {
if (!tx.$o.owner) throw "Tenants - $o.owner (the sender) is needed: the fee goes back to it";
owner = this.getActivityStreams(tx.$o.owner);
if (owner.getId() !== pre.sender) throw "Tenants - $o.owner must be the withdrawal's sender";
}
const unused = await this.tenantWdUnused(r, outcome);
this.tenantWdSettle = { presign, r, shard, outcome, owner, unused };
return true;
}/**
* Stage F2 (plan §3.5 "A quote is a cap"): what a settle gives back of a sent (or failed-on-chain) withdrawal's
* reserve when the payout used fewer sources than the quote bound. The counts come only from a minigate (the job
* record; `$i.admin.used = {sources, prepaid}`, signed by a LIVE minigate authority), never from the sweeper path.
* The settle prices the used counts from the values the reserve recorded (tenantSourcePrice), so a later config or
* multiplier change never alters it, and the charge never rises above the reserve: only the difference comes back,
* once (the settle runs once per presign). Null, and the reserve stays charged in full, when: the reserve carries no
* consolidation values (priced before F2's block was written), `refundUnused` was off, no counts were reported, or
* the payout never went out (that refunds the whole price anyway). Counts above what the quote bound are refused.
*/ private async tenantWdUnused(r: any, outcome: string): Promise<any> {
const tx: any = this.transactions;
const report = tx.$i && tx.$i.admin ? tx.$i.admin.used : undefined;
if (report === undefined) return null;
if (tx.$i.tenant) throw "Tenants - only a minigate reports the sources a payout used";
const rc = r.consolidation;
if (!rc || typeof rc !== "object" || outcome === "not-sent" || outcome === "expired") return null;
const count = (n: any, hi: number) => Number.isSafeInteger(n) && n >= 0 && n <= hi;
if (!report || typeof report !== "object" || Array.isArray(report) || Object.keys(report).length !== 2 || !count(report.sources, 100000) || !count(report.prepaid, 100000)) {
throw "Tenants - used must be {sources, prepaid}: whole numbers";
}
if (report.prepaid > report.sources) throw "Tenants - the payout reports more prepaid sources than sources";
await this.tenantWdReporterLive();
// Stage F4: a prepaid source is proven by its own on-ledger mark, never by the count alone.
const prepaidWallets = this.tenantWdPrepaidWallets(r, report.prepaid);
// More sources than the quote bound (a minigate fault: it holds such a payout over-quote): the quote is charged in
// full and nothing comes back. Never refused, so the reserve still settles and leaves the shard's open index.
if (report.sources > rc.sources) return { sources: report.sources, prepaid: report.prepaid, price: r.price, back: BigInt(0), overQuote: true, prepaidWallets: [] };
if (rc.refundUnused !== true) return null;
// Security review H1 + LOW (F4): only as many marks count as there are priced sources (past the free ones), and
// the discount they give is never more than what those marks paid (`sweepPrepaid.credits`), whatever the unit, the
// offset or the multiplier recorded on the reserve. Only the marks that counted are spent; the rest stay unspent.
const priced = report.sources > rc.freeSources ? report.sources - rc.freeSources : 0;
const used = prepaidWallets.slice(0, report.prepaid < priced ? report.prepaid : priced);
let paid = 0;
for (const m of used) paid += m.credits;
const full = this.tenantSourcePrice(rc, report.sources, 0);
let discount = full - this.tenantSourcePrice(rc, report.sources, used.length);
if (discount > paid) discount = paid;
const actual = BigInt(rc.base) + BigInt(full - discount);
const reserved = BigInt(r.price);
const back = actual < reserved ? reserved - actual : BigInt(0);
return { sources: report.sources, prepaid: used.length, price: (actual < reserved ? actual : reserved).toString(), back, prepaidWallets: used.map((m) => m.w) };
}/** * Stage F4 (docs/plans/tenant-pays-stage-f-consolidation-pricing.md §3.2, §3.5; decision 2026-11-06 F2 answer 1): * the deposit wallets a settle claims the prepaid discount for, checked on the ledger. A settle that reports * `prepaid: n` names exactly n wallet streams, `$o.prepaid0` to `$o.prepaid<n-1>`, and each must carry the mark * Varnir.AssignOwner wrote when the tenant paid its address charge (`wallet.deposit`): `tenant` is the reserve's * tenant, `sweepPrepaid` is unspent and names the withdrawal's asset class, and the wallet is on the withdrawal's * network. The marks are spent in this settle's commit (tenantWdSpendPrepaid), so each paid address discounts one * source once, ever. A count with no marks behind it is refused: the discount is never taken on the reporter's word. */
private tenantWdPrepaidWallets(r: any, n: number): any[] {
const tx: any = this.transactions;
const named = Object.keys(tx.$o || {}).filter((k) => /^prepaid[0-9]+$/.test(k));
if (named.length !== n) throw `Tenants - the payout reports ${n} prepaid sources but names ${named.length} prepaid wallets: each prepaid source is proven by its own mark ($o.prepaid0, $o.prepaid1, ...)`;
const assetClass = r.token === "#native" ? "native" : "token";
const network = this.canonicalNetwork(String(r.network));
const seen: string[] = [];
const out: any[] = [];
for (let i = 0; i < n; i++) {
if (tx.$o["prepaid" + i] === undefined) throw `Tenants - $o.prepaid${i} is missing: name the prepaid wallets $o.prepaid0 to $o.prepaid${n - 1}`;
const w = this.getActivityStreams(tx.$o["prepaid" + i]);
const id = w.getId();
if (seen.indexOf(id) !== -1) throw "Tenants - a prepaid wallet is named twice";
seen.push(id);
const st: any = w.getState() || {};
const sp = st.sweepPrepaid;
if (st.tenant !== r.tenantId || !sp || typeof sp !== "object" || Array.isArray(sp)) throw `Tenants - $o.prepaid${i} carries no prepaid mark of this tenant`;
if (sp.spentBy !== undefined) throw `Tenants - $o.prepaid${i}'s prepaid sweep is already spent`;
if (sp.asset !== assetClass) throw `Tenants - $o.prepaid${i} was prepaid as a ${String(sp.asset)} deposit wallet, not ${assetClass}`;
if (typeof st.network !== "string" || this.canonicalNetwork(st.network) !== network) throw `Tenants - $o.prepaid${i} is not a wallet on ${network}`;
if (!Number.isSafeInteger(sp.credits) || sp.credits < 0 || sp.credits > 1000000) throw `Tenants - $o.prepaid${i}'s prepaid mark is malformed`;
out.push({ w, credits: sp.credits });
}
return out;
}/** tenantwdsettle commit, stage F4: spends each claimed wallet's prepaid mark, once (the vote refused a spent one). */
private tenantWdSpendPrepaid(wallets: any[], presignId: string): void {
for (const w of wallets) {
const st: any = w.getState();
w.setState({ ...st, sweepPrepaid: { ...st.sweepPrepaid, spentBy: presignId, spentUmid: this.umid } });
}
}/** The live-authority rule (Varnir.Swap liveAuthority, PR #765) for the minigate key that reports used sources. */
private async tenantWdReporterLive(): Promise<void> {
const tx: any = this.transactions;
const key = tx.$i && tx.$i.admin ? tx.$i.admin.publicKey : undefined;
const meta: any = await this.getAnyStreamReadOnly(`${tx.$r && tx.$r.minigate}:stream`);
const authority = meta && Array.isArray(meta.authorities) ? meta.authorities.find((a: any) => a && a.public === key) : undefined;
let live = !!authority && !!key && !!authority.hash;
if (live && authority.expire !== undefined) {
const at = new Date(authority.expire).getTime();
live = !Number.isNaN(at) && at > new Date(this.cDate).getTime();
}
if (!live) throw "Tenants - the minigate key that reports used sources is expired or unknown";
}/** `tenantwdsettle` commit: see voteTenantWdSettle. Emits `tenant-withdrawal-settled`. */
private async commitTenantWdSettle(): Promise<boolean> {
const s = this.tenantWdSettle;
const r = s.r;
const refund = s.outcome === "not-sent" || s.outcome === "expired";
let state = refund ? "refunded" : "kept";
if (refund) {
const st: any = s.shard.getState();
if (typeof st.float === "string" && /^-?[0-9]{1,30}$/.test(st.float)) {
this.tenantFloatApply({ next: BigInt(st.float) + BigInt(r.price), charged: BigInt(0), uncharged: BigInt(0) }, { tenantId: r.tenantId, shard: s.shard });
} else {
state = "refund-lapsed";
}
}
// Stage F2: a kept reserve gives back the sources the payout did not use (tenantWdUnused), into the float.
let unusedBack = BigInt(0);
let usedRecord: any = null;
if (!refund && s.unused) {
const st: any = s.shard.getState();
const lapsed = s.unused.back > BigInt(0) && !(typeof st.float === "string" && /^-?[0-9]{1,30}$/.test(st.float));
if (s.unused.prepaidWallets && s.unused.prepaidWallets.length) this.tenantWdSpendPrepaid(s.unused.prepaidWallets, s.presign.getId());
if (s.unused.back > BigInt(0) && !lapsed) {
unusedBack = s.unused.back;
this.tenantFloatApply({ next: BigInt(st.float) + unusedBack, charged: BigInt(0), uncharged: BigInt(0) }, { tenantId: r.tenantId, shard: s.shard });
}
usedRecord = { sources: s.unused.sources, prepaid: s.unused.prepaid, price: lapsed ? r.price : s.unused.price, refunded: unusedBack.toString(), ...(lapsed ? { refundLapsed: true } : {}), ...(s.unused.overQuote ? { overQuote: true } : {}) };
}
// The shard's open-reserve index loses it, and a refunded price leaves the usage history (as far as the counters
// since the last sweep still hold it, equally from usage and floatPaid, so the usage left unsettled is unchanged).
{
const st: any = s.shard.getState();
const fees: any = st.fees || {};
const wdOpen: any = st.wdOpen && typeof st.wdOpen === "object" ? { ...st.wdOpen } : {};
delete wdOpen[s.presign.getId()];
const whole = (v: any) => BigInt(typeof v === "string" && /^[0-9]{1,30}$/.test(v) ? v : "0");
let back = state === "refunded" ? BigInt(r.price) : unusedBack;
if (back > whole(st.usage)) back = whole(st.usage);
if (back > whole(st.floatPaid)) back = whole(st.floatPaid);
s.shard.setState({ ...st, fees, usage: (whole(st.usage) - back).toString(), floatPaid: (whole(st.floatPaid) - back).toString(), wdOpen });
}
let amountHeld: any = null;
if (s.outcome === "expired") {
// Review N1: the AMOUNT is not refunded here. A `presigned` round can fail after the signers signed, so bytes for
// this payout may exist off the ledger; refunding the amount could pay it twice. It stays held on the presign until
// Varnir releases it (tenantwdrelease, tenant-admin withdrawal-release) after checking the L1 wallet. The sign
// gates refuse the presign from now on. The payment's repeat-guard record is dropped, as holdcancel drops it.
amountHeld = { at: this.cDate, umid: this.umid };
const refundTo: any = s.owner.getState();
if (Array.isArray(refundTo.recentPayments)) {
const pre: any = s.presign.getState();
refundTo.recentPayments = refundTo.recentPayments.filter((e: any) => !e || e.umid !== pre.umid);
s.owner.setState({ recentPayments: refundTo.recentPayments });
}
}
let feeTo = "none";
if (BigInt(r.fee) > BigInt(0)) {
if (s.outcome === "sent") {
feeTo = "tenant";
const sub = r.base !== undefined ? { base: r.base, overlay: r.overlay } : {};
this.tenantApply({ tenantId: r.tenantId, shard: s.shard, fee: r.fee, ...sub, usage: "0" }, `${r.network}:${r.token}`);
} else {
feeTo = "sender";
this.layer2TDetails.network = r.network;
this.layer2TDetails.token = r.token;
const senderState: any = s.owner.getState();
this.hasValidSchemaObject(senderState);
this.setL2Balance(senderState, this.getBN(this.getL2Balance(senderState)).add(r.fee));
s.owner.setState(senderState);
}
}
const settled: any = { ...r, state, outcome: s.outcome, feeTo, settledAt: this.cDate, settleUmid: this.umid };
if (amountHeld) settled.amountHeld = amountHeld;
if (usedRecord) settled.consolidation = { ...r.consolidation, used: usedRecord };
s.presign.setState({ tenantReserve: settled });
const refunded = state === "refunded" ? r.price : unusedBack.toString();
this.event.emit("tenant-withdrawal-settled", {
tenantId: r.tenantId,
shard: r.shard,
presign: s.presign.getId(),
outcome: s.outcome,
state,
price: r.price,
refunded,
// Stage F2: what stayed charged (the price less any refund); `price` stays the reserve, as before.
charged: state === "refunded" ? "0" : (BigInt(r.price) - unusedBack).toString(),
fee: r.fee,
feeTo,
umid: this.umid,
});
this.returnToRemote({ tenantReserve: settled });
return true;
}/** * `tenantwdrelease` (review N1): Varnir gives back the amount an expired tagged withdrawal still holds, once an * operator has checked on the L1 wallet that no signed bytes for it can land (tenant-admin withdrawal-release). Signed * by the contract's owner ($i.admin, as `mod`), naming the contract ($o.contract), the presign ($o.presign) and its * sender ($o.owner). Once: the release is recorded on the reserve. */
private async voteTenantWdRelease(): Promise<boolean> {
const tx: any = this.transactions;
if (!tx.$i || !tx.$i.admin || !tx.$o || !tx.$o.contract || !tx.$o.presign || !tx.$o.owner) throw "Tenants - tenantwdrelease needs $i.admin, $o.contract, $o.presign and $o.owner";
const contract = this.getActivityStreams(tx.$o.contract);
if (tx.$contract.substring(0, 64) !== contract.getId()) throw "Contract Not Matching";
const admin = this.getActivityStreams(tx.$i.admin);
if (!admin.hasSignature() || !this.hasContractOwnership(contract, admin.getId())) throw "Tenants - only the contract's owner may release a held withdrawal amount";
const presign = this.getActivityStreams(tx.$o.presign);
const pre: any = presign.getState();
const r: any = pre && pre.tenantReserve;
if (!r || !r.amountHeld || r.amountReleased) throw "Tenants - this presign holds no amount to release";
if (pre.signedStream || pre.confirmed) throw "Tenants - this presign was signed: its outcome comes from ConfirmWithdraw";
if (pre.tronMpc !== undefined) throw "presign has an armed mpc2 Tron transaction; refund only through recordlanded";
const owner = this.getActivityStreams(tx.$o.owner);
if (owner.getId() !== pre.sender) throw "Tenants - $o.owner must be the withdrawal's sender";
this.tenantWdSettle = { presign, pre, r, owner };
return true;
} private async commitTenantWdRelease(): Promise<boolean> {
const s = this.tenantWdSettle;
this.layer2TDetails.network = s.r.network;
this.layer2TDetails.token = s.r.token;
const back0 = this.getBN(s.pre.amount);
const back = s.pre.delegated === false && s.pre.gasHold && s.pre.gasHold.amount ? back0.add(s.pre.gasHold.amount) : back0;
const refundTo: any = s.owner.getState();
this.hasValidSchemaObject(refundTo);
this.setL2Balance(refundTo, this.getBN(this.getL2Balance(refundTo)).add(back));
s.owner.setState(refundTo);
const released = { ...s.r, amountReleased: { at: this.cDate, umid: this.umid, amount: back.toString() } };
s.presign.setState({ tenantReserve: released });
this.event.emit("tenant-withdrawal-released", { presign: s.presign.getId(), sender: s.pre.sender, amount: back.toString(), umid: this.umid });
this.returnToRemote({ tenantReserve: released });
return true;
}/** * `tenantpayout` vote: credits a tenant's fee treasury to its named payee as a * spendable L2 balance. A Varnir money path: it is authorised by the Varnir * sweeper key signing one of the tenant's own shards (`$i.shard`), never by * the tenant. `$o.tenant` is the tenant master and `$o.payee` the payee * identity with the asset (`network`, `token`) on it. The destination is fixed * (master.payee) and the amount is the treasury, so a caller chooses nothing. */
private async voteTenantPayout(): Promise<boolean> {
const tx: any = this.transactions;
const masterRef = tx.$o && tx.$o.tenant;
const payeeRef = tx.$o && tx.$o.payee;
const shardRef = tx.$i && tx.$i.shard;
if (!masterRef || !payeeRef || !shardRef) throw "Tenants - $o.tenant, $o.payee and $i.shard are required";
const network = payeeRef.network;
const token = payeeRef.token || "#native";
if (typeof network !== "string" || !network || typeof token !== "string") throw "Tenants - network and token are required";
// "NETWORK:token" is the treasury key, so a ':' in either half could aim at another asset's key.
if (network.indexOf(":") !== -1 || token.indexOf(":") !== -1) throw "Tenants - network and token must not contain ':'";
const { master, state } = this.tenantMasterBySweeper(masterRef, shardRef);
// Varnir no longer pays out on its own (docs/decisions/2026-10-23-tenant-payouts.md): only a tenant Varnir has
// switched back to automatic payouts (Varnir.Tenants setPayoutConfig autoPayout) may still be paid this way.
if (state.autoPayout !== true) throw "Tenants - automatic payouts are off for this tenant: it requests a payout instead (tenantsettle)";
if (!state.payee) throw "Tenants - this tenant has no payee set";
const payee = this.getActivityStreams(payeeRef);
if (state.payee !== payee.getId()) throw "Tenants - $o.payee is not the payee of this tenant";
// One of the tenant's own streams is no wallet: anything credited there could never be spent.
const payeeKind = (payee.getState() as any)?.kind;
if (payee.getId() === master.getId() || (typeof payeeKind === "string" && payeeKind.indexOf("varnir.tenant") === 0)) throw "Tenants - the payee is not a wallet identity";
const key = `${network}:${token}`;
const amount = state.treasury && state.treasury[key];
if (typeof amount !== "string" || !/^[0-9]+$/.test(amount) || BigInt(amount) === BigInt(0)) throw "Tenants - nothing to pay out for this asset";
this.layer2TDetails.network = network;
this.layer2TDetails.token = token;
const payeeState = payee.getState();
this.hasValidSchemaObject(payeeState);
this.tenantPayout = { master, state, key, amount, payee, payeeState };
return true;
}/** `tenantpayout` commit: the treasury amount moves from the master to the payee's L2 balance; value is conserved. Emits `tenant-payout`. */
private async commitTenantPayout(): Promise<boolean> {
const p = this.tenantPayout;
const balance = this.getBN(this.getL2Balance(p.payeeState) || 0);
this.setL2Balance(p.payeeState, balance.add(this.getBN(p.amount)));
p.payee.setState(p.payeeState);
const treasury = { ...p.state.treasury };
delete treasury[p.key];
p.master.setState({ treasury });
this.event.emit("tenant-payout", {
tenantId: p.state.tenantId,
payee: p.payee.getId(),
network: this.layer2TDetails.network,
token: this.layer2TDetails.token,
amount: p.amount,
});
return true;
}/** * The tenant master named by `masterRef` and its state, after checking that `shardRef` is one of that tenant's own * shards (at its derived id) signed by its Varnir sweeper key (stake 100, label `sweeper`). The tenant money paths * (`tenantpayout`, `tenantsettle`) are Varnir's: the tenant key alone never moves the treasury. */
private tenantMasterBySweeper(masterRef: any, shardRef: any): { master: any; state: any }/**
* `tenantsettle` vote: Varnir processes one of a tenant's payout requests (Varnir.Tenants requestPayout) in ONE
* transaction (docs/decisions/2026-10-23-tenant-payouts.md). Varnir's house identity buys the treasury assets it
* takes and pays the tenant what it asked for:
* - `assetsTaken` {"NETWORK:token": raw}: each leaves the master's treasury and lands on the house's L2 balance of
* the SAME asset (never more than the treasury holds);
* - usdt / native: `paid` {token, amountRaw} leaves the house's L2 balance and lands on the payee's (the master's
* payee, `$o.payee`) on the request's network; the house may never go negative;
* - credits: no `paid`; the requested credits go onto the master's prepaid balance, owed first (tenantAddCredits).
* Every asset is conserved; credits are Varnir's own unit, bought with the assets the house keeps.
* Only assets in the admin-set table `payoutConfig.assets` {"NETWORK:token": {decimals, usdt?, symbol?}} may be
* taken or paid; a usdt request is paid only in an asset flagged usdt on its network, a native one only in that
* network's #native. The rate is Varnir's own (no oracle), but the value moved is bound to it here:
* `rateSnapshot` {asset: {usdPerUnit, decimals (= the table's), source, at (ISO, within 10 minutes of cDate)}} must
* cover every asset moved, the assets taken may be worth at most the request plus the tolerance, and what is paid
* at least the request less the tolerance (max(1 credit, payoutConfig.tolerancePct %, default 1)). That keeps a
* mistaken or scoped key from overdrawing a treasury or underpaying a tenant, and makes every settlement auditable.
* Authorised by the sweeper key on a tenant shard (`$i.shard`) AND the house's own stake-100 key (`$i.house`, which
* also carries the terms): the house's balance is debited, so its key must sign, as for any spend. The house must be
* the tenant's configured `payoutConfig.house`, set only by the Varnir admin, so a sweeper key alone cannot aim the
* treasury at an identity of its choosing.
*/ private async voteTenantSettle(): Promise<boolean> {
const tx: any = this.transactions;
const masterRef = tx.$o && tx.$o.tenant;
const houseIn = tx.$i && tx.$i.house;
const shardRef = tx.$i && tx.$i.shard;
if (!masterRef || !houseIn || !shardRef) throw "Tenants - $o.tenant, $i.house and $i.shard are required";
for (const key of Object.keys(houseIn)) {
if (["$stream", "payoutId", "assetsTaken", "paid", "rateSnapshot"].indexOf(key) < 0) throw `Tenants - unknown settle field ${key}`;
}
const { master, state } = this.tenantMasterBySweeper(masterRef, shardRef);
const house = this.getActivityStreams(houseIn);
const config = state.payoutConfig;
if (!config || typeof config.house !== "string" || !/^[0-9a-f]{64}$/.test(config.house)) throw "Tenants - this tenant has no payout house set (Varnir.Tenants setPayoutConfig)";
if (house.getId() !== config.house) throw "Tenants - $i.house is not this tenant's payout house";
// The admin's asset table: what may move and at which decimals. A tenant configured before it existed settles nothing.
const table = config.assets;
if (!table || typeof table !== "object" || Array.isArray(table)) throw "Tenants - this tenant has no payout asset table set (Varnir.Tenants setPayoutConfig assets)";
const tableKeys = Object.keys(table);
const tolerancePct = config.tolerancePct === undefined ? 1 : config.tolerancePct;
if (!Number.isInteger(tolerancePct) || tolerancePct < 0 || tolerancePct > 10) throw "Tenants - this tenant's payout tolerancePct is malformed";
const houseSigned = (this as any).sigs && (this as any).sigs[house.getId()];
const houseHashes = houseSigned ? Object.keys(houseSigned) : [];
if (!(house.getAuthorities() || []).some((a: any) => a.stake === 100 && houseHashes.indexOf(a.hash) !== -1)) {
throw "Tenants - the house's own key (stake 100) must sign a settlement";
}
const list = state.payouts;
if (!Array.isArray(list)) throw "Tenants - this tenant has no payout requests";
if (!Number.isSafeInteger(houseIn.payoutId) || houseIn.payoutId < 1) throw "Tenants - payoutId must be a whole number";
const index = list.findIndex((p: any) => p && p.id === houseIn.payoutId);
if (index < 0) throw `Tenants - there is no payout ${houseIn.payoutId}`;
const request = list[index];
if (request.status !== "requested") throw `Tenants - payout ${request.id} is ${request.status}, not requested`;
if (["credits", "usdt", "native"].indexOf(request.currency) < 0 || !Number.isSafeInteger(request.credits) || request.credits < 1) throw `Tenants - payout ${request.id} is malformed`;
// What the house takes: only assets the treasury holds, never more than it holds.
const ASSET = /^[A-Za-z0-9-]{1,32}:[A-Za-z0-9#]{1,66}$/;
const RAW = /^[1-9][0-9]{0,77}$/;
const taken = houseIn.assetsTaken;
if (!taken || typeof taken !== "object" || Array.isArray(taken)) throw "Tenants - assetsTaken must be an object of asset to raw amount";
const takenKeys = Object.keys(taken);
if (takenKeys.length < 1 || takenKeys.length > 16) throw "Tenants - assetsTaken must name 1 to 16 assets";
const treasury: any = state.treasury && typeof state.treasury === "object" ? state.treasury : {};
for (const key of takenKeys) {
if (!ASSET.test(key)) throw `Tenants - assetsTaken key ${key} is not a NETWORK:token asset`;
if (typeof taken[key] !== "string" || !RAW.test(taken[key])) throw `Tenants - assetsTaken ${key} must be a positive whole-number string`;
if (tableKeys.indexOf(key) < 0) throw `Tenants - ${key} is not in this tenant's asset table`;
const holds = Object.keys(treasury).indexOf(key) >= 0 ? treasury[key] : "0";
if (typeof holds !== "string" || !/^[0-9]+$/.test(holds)) throw `Tenants - the treasury holds a malformed amount for ${key}`;
if (BigInt(taken[key]) > BigInt(holds)) throw `Tenants - assetsTaken ${key} is more than the treasury holds (${holds})`;
}
// What the tenant is paid.
let paid: any;
let payee: any = null;
let payeeState: any = null;
let paidKey: string | null = null;
if (request.currency === "credits") {
if (houseIn.paid !== undefined) throw "Tenants - a credits payout takes no paid amount: the requested credits are paid";
paid = { currency: "credits", network: null, token: null, amountRaw: String(request.credits), credits: request.credits };
} else {
const p = houseIn.paid;
if (!p || typeof p !== "object" || Array.isArray(p)) throw `Tenants - a ${request.currency} payout needs paid {token, amountRaw}`;
for (const key of Object.keys(p)) {
if (key !== "token" && key !== "amountRaw") throw `Tenants - unknown paid field ${key}`;
}
if (typeof p.token !== "string" || !/^(#native|[A-Za-z0-9]{1,66})$/.test(p.token)) throw "Tenants - paid token must be #native or a token id (letters and digits)";
if (request.currency === "native" && p.token !== "#native") throw "Tenants - a native payout is paid in #native";
if (request.currency === "usdt" && p.token === "#native") throw "Tenants - a usdt payout is paid in a token, not #native";
if (typeof p.amountRaw !== "string" || !RAW.test(p.amountRaw)) throw "Tenants - paid amountRaw must be a positive whole-number string";
if (typeof request.network !== "string" || !/^[A-Za-z0-9-]{1,32}$/.test(request.network)) throw `Tenants - payout ${request.id} is malformed`;
paid = { currency: request.currency, network: request.network, token: p.token, amountRaw: p.amountRaw, credits: request.credits };
paidKey = `${request.network}:${p.token}`;
if (tableKeys.indexOf(paidKey) < 0) throw `Tenants - ${paidKey} is not in this tenant's asset table`;
if (request.currency === "usdt" && table[paidKey].usdt !== true) throw `Tenants - ${paidKey} is not a USDT asset in this tenant's asset table`;
const payeeRef = tx.$o && tx.$o.payee;
if (!payeeRef) throw "Tenants - a usdt or native payout needs the payee as $o.payee";
payee = this.getActivityStreams(payeeRef);
if (!state.payee || state.payee !== payee.getId()) throw "Tenants - $o.payee is not the payee of this tenant";
if (payee.getId() === house.getId()) throw "Tenants - the house cannot be the payee";
const payeeKind = (payee.getState() as any)?.kind;
if (payee.getId() === master.getId() || (typeof payeeKind === "string" && payeeKind.indexOf("varnir.tenant") === 0)) throw "Tenants - the payee is not a wallet identity";
}
// The rate is Varnir's own, recorded with the settlement and binding the value moved (below); plain data only.
const rates = houseIn.rateSnapshot;
if (!rates || typeof rates !== "object" || Array.isArray(rates) || Object.keys(rates).length > 17) throw "Tenants - rateSnapshot must be an object of at most 17 assets";
for (const key of Object.keys(rates)) {
const r = rates[key];
if (!ASSET.test(key) || !r || typeof r !== "object" || Array.isArray(r)) throw `Tenants - rateSnapshot ${key} is malformed`;
for (const field of Object.keys(r)) {
if (["usdPerUnit", "decimals", "source", "at"].indexOf(field) < 0) throw `Tenants - rateSnapshot ${key} has an unknown field ${field}`;
}
// A zero price would value any amount at nothing, and so let the value bound below be stepped round.
if (typeof r.usdPerUnit !== "string" || !/^[0-9]{1,18}(\.[0-9]{1,18})?$/.test(r.usdPerUnit) || !/[1-9]/.test(r.usdPerUnit)) throw `Tenants - rateSnapshot ${key} usdPerUnit must be a positive decimal string`;
if (tableKeys.indexOf(key) < 0) throw `Tenants - rateSnapshot ${key} is not in this tenant's asset table`;
if (r.decimals !== table[key].decimals) throw `Tenants - rateSnapshot decimals ${r.decimals} for ${key} but the asset table says ${table[key].decimals}`;
if (typeof r.source !== "string" || !/^[a-z0-9._-]{1,32}$/.test(r.source)) throw `Tenants - rateSnapshot ${key} source must be 1 to 32 of a-z 0-9 . _ -`;
if (typeof r.at !== "string" || !/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{1,3})?Z$/.test(r.at) || isNaN(new Date(r.at).getTime())) throw `Tenants - rateSnapshot ${key} at must be an ISO time (YYYY-MM-DDTHH:MM:SSZ)`;
const age = new Date(r.at).getTime() - new Date(this.cDate).getTime();
if (age > 600000 || age < -600000) throw `Tenants - rateSnapshot ${key} at must be within 10 minutes of the consensus time`;
}
for (const key of paidKey ? takenKeys.concat([paidKey]) : takenKeys) {
if (Object.keys(rates).indexOf(key) < 0) throw `Tenants - rateSnapshot has no rate for ${key}`;
}
// The value bound, in 1e-18 credits (1 credit = 1 US cent): raw * usdPerUnit * 100 / 10^decimals, rounded down.
const ATTO = BigInt("1000000000000000000");
const valueOf = (raw: string, r: any): bigint => {
const parts = String(r.usdPerUnit).split(".");
const frac = parts.length > 1 ? parts[1] : "";
return (BigInt(raw) * BigInt(parts[0] + frac) * BigInt(100) * ATTO) / BigInt(10) ** BigInt(r.decimals + frac.length);
};
const shown = (atto: bigint): string => {
const fracDigits = (atto % ATTO).toString().padStart(18, "0").replace(/0+$/, "");
return (atto / ATTO).toString() + (fracDigits ? "." + fracDigits : "");
};
const wanted = BigInt(request.credits) * ATTO;
const pctTol = (BigInt(request.credits) * BigInt(tolerancePct) * ATTO) / BigInt(100);
const tolerance = pctTol > ATTO ? pctTol : ATTO;
let takenValue = BigInt(0);
for (const key of takenKeys) takenValue += valueOf(taken[key], rates[key]);
if (takenValue > wanted + tolerance) throw `Tenants - the assets taken are worth ${shown(takenValue)} credits, more than ${request.credits} requested (tolerance ${shown(tolerance)})`;
if (paidKey) {
const paidValue = valueOf(paid.amountRaw, rates[paidKey]);
if (paidValue < wanted - tolerance) throw `Tenants - what is paid is worth ${shown(paidValue)} credits, less than ${request.credits} requested (tolerance ${shown(tolerance)})`;
}
// The house after it has taken the assets: it may pay out of what it just bought, never below zero.
const houseState = house.getState();
for (const key of takenKeys) {
const [network, token] = key.split(":");
this.layer2TDetails.network = network;
this.layer2TDetails.token = token;
this.hasValidSchemaObject(houseState);
this.setL2Balance(houseState, this.getBN(this.getL2Balance(houseState) || 0).add(this.getBN(taken[key])));
}
if (paidKey) {
this.layer2TDetails.network = paid.network;
this.layer2TDetails.token = paid.token;
this.hasValidSchemaObject(houseState);
const balance = this.getBN(this.getL2Balance(houseState) || 0);
if (balance.lt(paid.amountRaw)) throw `Tenants - the house holds only ${balance.toString()} of ${paidKey}, less than the ${paid.amountRaw} to pay`;
this.setL2Balance(houseState, balance.sub(paid.amountRaw));
payeeState = payee.getState();
this.hasValidSchemaObject(payeeState);
}
this.tenantSettle = { master, state, index, taken, takenKeys, paid, house, houseState, payee, payeeState, rates };
return true;
}/** `tenantsettle` commit: writes what voteTenantSettle worked out. Emits `tenant-payout-settled`. */
private async commitTenantSettle(): Promise<boolean> {
const s = this.tenantSettle;
s.house.setState(s.houseState);
if (s.payee) {
this.layer2TDetails.network = s.paid.network;
this.layer2TDetails.token = s.paid.token;
this.setL2Balance(s.payeeState, this.getBN(this.getL2Balance(s.payeeState) || 0).add(s.paid.amountRaw));
s.payee.setState(s.payeeState);
}
const state = s.state;
const treasury: any = { ...state.treasury };
for (const key of s.takenKeys) {
const left = BigInt(treasury[key]) - BigInt(s.taken[key]);
if (left === BigInt(0)) delete treasury[key];
else treasury[key] = left.toString();
}
state.treasury = treasury;
// >>> tenant-pays
// A credits payout to a tenant on the float pays what it owes first and ends grace only at 0 owed (review L1).
if (s.paid.currency === "credits" && state.floatMode === true) this.floatCredit(state, BigInt(s.paid.credits));
else
// <<< tenant-pays
if (s.paid.currency === "credits") this.tenantAddCredits(state, BigInt(s.paid.credits));
const now = new Date(this.cDate).getTime();
const assetsTaken: any = {};
for (const key of s.takenKeys) assetsTaken[key] = s.taken[key];
const record = { ...state.payouts[s.index], status: "settled", settledAt: now, closedAt: now, closedUmid: this.umid, assetsTaken, paid: s.paid, rateSnapshot: s.rates };
const list = state.payouts.slice();
list[s.index] = record;
state.payouts = this.tenantTrimPayouts(list);
s.master.setState(state);
this.event.emit("tenant-payout-settled", {
tenant: state.tenantId,
tenantId: state.tenantId,
payoutId: record.id,
ref: record.ref,
currency: record.currency,
network: record.network,
credits: record.credits,
assetsTaken,
paid: s.paid,
house: s.house.getId(),
payee: s.payee ? s.payee.getId() : null,
umid: this.umid,
});
return true;
}/** voteGasFree: hold a ledger transfer to an identity this identity has not paid. */
private holdDecideL2(recipientId: string): void {
this.holdPending = null;
if (!this.holdSwitchOn()) return;
// Paying yourself is never held (and never settles anything anyway).
if (!recipientId || recipientId === this.owner.getId()) return;
const nowMs = this.holdNowMs();
if (!this.holdProtectionOn(this.ownerState, nowMs)) return;
const key = this.holdLedgerKey(recipientId);
if (this.holdKnownSettled(this.ownerState, key, nowMs)) return;
this.holdPending = {key, until: this.holdIso(nowMs + HOLDMS)};
}/** * Emits `withdrawal-held` for the gateway: hold id and kind, umid, * identity, network, token, amount, recipient, `until`, the signing key's * label and whether the payment was a co-signed confirm. */
private emitWithdrawalHeld(holdId: string, kind: "l1" | "l2", to: string, hold: any): void {
this.event.emit("withdrawal-held", {
holdId,
kind,
umid: this.umid,
identity: this.owner.getId(),
network: this.layer2TDetails.network,
token: this.layer2TDetails.token,
amount: String(this.transactions.$i.owner.amount),
to,
until: hold.until,
signingKeyLabel: this.signingKeyLabel(this.owner),
coSigned: !!this.approved,
_dbIndex: this.transactions._dbIndex || 0,
});
}/** votePreSigned's gate: refuse a held presign until it may go; a cancelled one never. */
private holdSignGate(hold: any): void {
if (!hold || typeof hold !== "object") return;
if (hold.state === "cancelled") {
throw "HOLD_NOT_ACTIVE: hold was cancelled - this withdrawal will never be signed";
}
if (hold.state === "released-early" || hold.state === "released") return;
// "held", or anything unrecognised (fail-safe): wait for `until`.
const until = new Date(hold.until).getTime();
if (!Number.isFinite(until) || this.holdNowMs() < until) {
throw `WITHDRAWAL_HELD: withdrawal held until ${hold.until}`;
}
}/** commitGasFree for a held transfer: debit, escrow in l2.hold, recipient untouched. */
private commitHeldTransfer(recipient: any): boolean {
const amount = this.getBN(this.transactions.$i.owner.amount);
const senderBalance = this.holdReadSlot(this.ownerState, this.owner.getId());
// A tenant-tagged held transfer still pays the tenant fee now; only `amount` is escrowed.
this.holdWriteSlot(this.ownerState, this.owner.getId(), senderBalance.sub(amount).sub(this.varnirFee));
if (this.tenantPrep) this.tenantApply(this.tenantPrep, `${this.layer2TDetails.network}:${this.layer2TDetails.token}`);
// >>> tenant-pays
if (this.tenantPrep) this.tenantFloatApply(this.tenantFloat, this.tenantPrep);
// <<< tenant-pays
const holdStream = this.newActivityStream("l2.hold");
const holdId = holdStream.getId();
const hold = this.holdBlock(holdId, "l2", this.holdPending as {key: string; until: string});
const namedWallet = this.transactions.$o?.to?.wallet;
const holdState: any = {
umid: this.umid,
sender: this.owner.getId(),
to: recipient.getId(),
network: this.layer2TDetails.network,
token: this.layer2TDetails.token,
amount: amount.toString(),
created: this.holdIso(this.holdNowMs()),
// Named so neither reads as an l1.presign's `wallet`/`toAddress`
// (readers tell the two kinds apart by those fields).
...(namedWallet ? {recipientWallet: this.filterPrefix(namedWallet)} : {}),
...(namedWallet && this.transactions.$i.owner.toAddress !== undefined
? {recipientAddress: String(this.transactions.$i.owner.toAddress)}
: {}),
hold,
};
// The escrow is a real balance on the hold stream, so value is never
// off-ledger while held: release moves it to the recipient, cancel back.
this.holdWriteSlot(holdState, holdId, amount);
holdStream.setState(holdState);
this.holdRememberPending(this.ownerState, this.holdPending as {key: string; until: string}, holdId);
this.withRecentPayment(this.ownerState);
this.bumpAgentUsage();
this.owner.setState(this.ownerState);
this.emitWithdrawalHeld(holdId, "l2", recipient.getId(), hold);
this.returnToRemote([
{id: this.owner.getId(), partitions: this.ownerState.layer2},
{id: holdId, hold},
]);
return true;
}/** A gateway hold entry: holdnotify always; holdrelease/holdcancel when no identity signs. */
private isGatewayHoldEntry(): boolean {
const entry = this.transactions.$entry;
if (entry === "holdnotify") return true;
return (entry === "holdrelease" || entry === "holdcancel") && !(this.transactions.$i && this.transactions.$i.owner);
}/** The hold named on $o.hold, proved to be one this contract created. */
private holdLoad(): {stream: any; state: any; hold: any; kind: "l1" | "l2"}/** Refuses a hold that is no longer `held`, or an L1 hold that has already been signed. */
private holdRequireActive(state: any, hold: any): void {
if (hold.state === "cancelled") throw "HOLD_NOT_ACTIVE: hold already cancelled";
if (hold.state !== "held") throw "HOLD_NOT_ACTIVE: hold already released";
if (state.signedStream) throw "HOLD_NOT_ACTIVE: hold already released - the withdrawal was signed";
}/** $o.recipient for an L2 release: must be the hold's own recipient. */
private holdRecipient(state: any): any {
const ref = this.transactions.$o && this.transactions.$o.recipient;
const id = ref ? this.filterPrefix(String(ref.$stream ?? ref)) : "";
if (!id || id !== state.to) throw "Recipient output is not the hold's recipient";
return this.getActivityStreams(ref);
}/** A speed-up code as typed: upper-cased, spaces and hyphens removed ("" for a non-string). */ private holdNormaliseCode(code: any): string {
return typeof code === "string" ? code.toUpperCase().replace(/[\s-]/g, "") : "";
}/** * The hold entries the identity signs (`$i.owner`): * - `holdconfig`: `enabled` must be a boolean; turning protection off * needs the stake-100 key. * - `holdlearn`: learns the recipients holdLearnKeys proves. * - `holdcancel`: cancels an active hold of this identity (any key that * passed vote()'s read-only and off-ledger refusals). * - `holdrelease` (the speed-up): the stake-100 key and the emailed code, * before `until`, with fewer than HOLDMAXATTEMPTS wrong codes so far. A * wrong code is committed as an attempt rather than rejected. * The hold, named on `$o.hold`, must have this identity as its sender. */
private async voteHoldOwner(owner: any): Promise<boolean> {
const entry = this.transactions.$entry;
const input = this.transactions.$i.owner || {};
if (entry === "holdconfig") {
if (typeof input.enabled !== "boolean") throw "holdconfig: enabled must be true or false";
// >>> owner-gate
if (!input.enabled && !this.isSingleOwnerKey(owner)) {
throw "HOLD_OWNER_KEY_REQUIRED: turning the protection off needs the owner key";
}
// <<< owner-gate
if (!input.enabled && !this.hasAuthorityStake(100, owner)) {
throw "HOLD_OWNER_KEY_REQUIRED: turning the protection off needs the owner key";
}
this.holdOp = {op: "config", owner, enabled: input.enabled};
return true;
}
if (entry === "holdlearn") {
this.holdOp = {op: "learn", owner, keys: await this.holdLearnKeys(owner)};
return true;
}
const {stream, state, hold, kind} = this.holdLoad();
if (this.filterPrefix(state.sender) !== owner.getId()) throw "Hold belongs to another identity";
if (entry === "holdcancel") {
this.holdRequireActive(state, hold);
this.refuseArmedPresign(state);
this.holdOp = {
op: "cancel", stream, state, hold, kind, refundTo: owner,
by: this.signingKeyHash(owner) ?? "owner",
};
return true;
}
// holdrelease: the speed-up. Owner key AND the emailed code (design §5).
// >>> owner-gate
if (!this.isSingleOwnerKey(owner)) {
throw "HOLD_OWNER_KEY_REQUIRED: speed-up needs the owner key";
}
// <<< owner-gate
if (!this.hasAuthorityStake(100, owner)) {
throw "HOLD_OWNER_KEY_REQUIRED: speed-up needs the owner key";
}
this.holdRequireActive(state, hold);
if (this.holdNowMs() >= new Date(hold.until).getTime()) {
throw "HOLD_NOT_ACTIVE: hold already released - its 24 hours have run out";
}
if (typeof hold.codeHash !== "string" || !hold.codeHash) {
throw "HOLD_CODE_INVALID: no speed-up code has been issued for this hold";
}
if ((Number(hold.failedAttempts) || 0) >= HOLDMAXATTEMPTS) {
throw `HOLD_SPEEDUP_LOCKED: speed-up locked after ${HOLDMAXATTEMPTS} wrong codes`;
}
const code = this.holdNormaliseCode(input.code);
// Not even the shape of a code: refused, and it costs no attempt.
if (!HOLDCODE_PATTERN.test(code)) throw "HOLD_CODE_INVALID: invalid speed-up code";
const recipient = kind === "l2" ? this.holdRecipient(state) : null;
const matched = this.holdHash(`${stream.getId()}:speedup:${code}`) === hold.codeHash;
// A wrong code is COMMITTED as failedAttempts++, not rejected, so that
// attempts actually count (Varnir.Recovery's runSubmit).
this.holdOp = matched
? {op: "release", stream, state, hold, kind, owner, recipient, reason: "speedup"}
: {op: "wrong-code", stream, state, hold, kind};
return true;
}/** * The gateway's hold entries: $selfsign + `$r.minigate`, proved by * assertMinigateSigner, for the hold named on `$o.hold`. * - `holdnotify` phase `claim`: claims the hold's email and records the * sha256 `codeHash` / `cancelHash` - refused once sent, once `until` has * passed, or within HOLDCLAIMTIMEOUTMS of another claim. Phase `sent`: * the claiming gateway records the `resendId`. * - `holdrelease` with reason `elapsed`: releases an L2 hold whose `until` * has passed to its recipient on `$o.recipient`. * - `holdcancel`: the emailed cancel token, checked here against * `cancelHash`; refunds the sender on `$o.owner`. */
private async voteHoldGateway(): Promise<boolean> {
// >>> hold-release-anyone
if (this.transactions.$entry === "holdrelease" && this.transactions.$i.releaser) return this.voteHoldReleaseAnyone();
// <<< hold-release-anyone
await this.assertMinigateSigner();
const entry = this.transactions.$entry;
const admin = this.transactions.$i.admin || {};
const minigate = this.filterPrefix(String(this.transactions.$r.minigate));
const {stream, state, hold, kind} = this.holdLoad();
const nowMs = this.holdNowMs();
if (entry === "holdnotify") {
this.holdRequireActive(state, hold);
const notify = hold.notify && typeof hold.notify === "object" ? hold.notify : {};
if (notify.sentAt) throw "Hold email already sent";
if (admin.phase === "claim") {
// An email about a hold that has already run out would be noise.
// (`sent` is still accepted after `until`: that email went out.)
if (nowMs >= new Date(hold.until).getTime()) throw "HOLD_NOT_ACTIVE: hold already released - nothing to email";
const claimedMs = notify.claimedAt ? new Date(notify.claimedAt).getTime() : NaN;
if (Number.isFinite(claimedMs) && nowMs - claimedMs < HOLDCLAIMTIMEOUTMS) {
throw "Hold email already claimed";
}
const codeHash = String(admin.codeHash ?? "").toLowerCase();
const cancelHash = String(admin.cancelHash ?? "").toLowerCase();
if (!HOLDHASH_PATTERN.test(codeHash) || !HOLDHASH_PATTERN.test(cancelHash)) {
throw "holdnotify: codeHash and cancelHash must be sha256 hex";
}
this.holdOp = {op: "claim", stream, state, hold, minigate, codeHash, cancelHash};
return true;
}
if (admin.phase === "sent") {
if (!notify.claimedAt || notify.claimedBy !== minigate) throw "Hold email not claimed by this gateway";
if (typeof admin.resendId !== "string" || !admin.resendId || admin.resendId.length > 256) {
throw "holdnotify: resendId required";
}
this.holdOp = {op: "sent", stream, state, hold, resendId: admin.resendId};
return true;
}
throw "holdnotify: phase must be claim or sent";
}
if (entry === "holdrelease") {
if (admin.reason !== "elapsed") throw "holdrelease: a gateway may only release an elapsed hold";
if (kind !== "l2") throw "holdrelease: elapsed release is for ledger holds - a withdrawal is released by signing it";
this.holdRequireActive(state, hold);
if (!(nowMs >= new Date(hold.until).getTime())) throw `WITHDRAWAL_HELD: transfer held until ${hold.until}`;
const recipient = this.holdRecipient(state);
this.holdOp = {op: "release", stream, state, hold, kind, owner: null, recipient, reason: "elapsed"};
return true;
}
// holdcancel, from the emailed link (design §5): the token is checked
// against cancelHash here, so the gateway only relays it.
this.holdRequireActive(state, hold);
const token = admin.token;
if (typeof token !== "string" || !HOLDTOKEN_PATTERN.test(token)) throw "holdcancel: malformed cancel token";
if (typeof hold.cancelHash !== "string" || !hold.cancelHash) throw "holdcancel: no cancel link has been issued for this hold";
if (this.holdHash(`${stream.getId()}:cancel:${token}`) !== hold.cancelHash) throw "holdcancel: cancel token does not match";
const ownerRef = this.transactions.$o && this.transactions.$o.owner;
const ownerId = ownerRef ? this.filterPrefix(String(ownerRef.$stream ?? ownerRef)) : "";
if (!ownerId || ownerId !== this.filterPrefix(state.sender)) throw "Owner output is not the hold's sender";
this.refuseArmedPresign(state);
this.holdOp = {
op: "cancel", stream, state, hold, kind,
refundTo: this.getActivityStreams(ownerRef), by: "email-link",
};
return true;
}/** * `holdrelease` signed `$i.releaser` with `$selfsign` (any key; no * gateway, no `$r.minigate`): the gateway's elapsed release, so a held * ledger transfer reaches its recipient with no gateway up * (docs/tenancy/gateway-signing-matrix.md row 10). `$selfsign` only: an * identity releaser would lock its own stream, and the only locks this * entry needs are the hold (`$o.hold`) and the recipient (`$o.recipient`). * It is refused until HOLDPUBLICRELEASEMARGINMS after `until` (cDate is the * entry node's clock, unchecked for drift), so before `until` the sender's * cancel and the emailed cancel keep their whole window. The hold stream is * a locked output: a release and a cancel cannot both commit, and a second * release finds the hold no longer `held`. Testnet only for now * (production keeps the gateway-only release). */
private voteHoldReleaseAnyone(): boolean {
// `$selfsign` sits on the ledger entry, beside `$tx`, so the contract
// cannot read it: it reads the input's shape instead. A self-signed
// input is a key ({publicKey, type}) with no `$stream`; the engine has
// already checked the signature against that key. Without `$selfsign`
// an input names a stream (`$stream`, or a label that is a stream id),
// and that stream would be locked.
const releaser = this.transactions.$i.releaser;
if (!releaser || typeof releaser !== "object" || releaser.$stream !== undefined || typeof releaser.publicKey !== "string" || !releaser.publicKey) {
throw "holdrelease: a release without a gateway must be $selfsign ($i.releaser is a key, not an identity)";
}
const {stream, state, hold, kind} = this.holdLoad();
if (kind !== "l2") throw "holdrelease: elapsed release is for ledger holds - a withdrawal is released by signing it";
this.holdRequireActive(state, hold);
// A missing or unreadable `until` is NaN, and NaN refuses: fail closed.
const untilMs = new Date(hold.until).getTime();
if (!Number.isFinite(untilMs)) throw `WITHDRAWAL_HELD: transfer held until ${hold.until}`;
const fromMs = untilMs + HOLDPUBLICRELEASEMARGINMS;
if (!(this.holdNowMs() >= fromMs)) {
throw `WITHDRAWAL_HELD: transfer held until ${hold.until}; without a gateway it may be released from ${this.holdIso(fromMs)}`;
}
const recipient = this.holdRecipient(state);
this.holdOp = {op: "release", stream, state, hold, kind, owner: null, recipient, reason: "elapsed"};
return true;
}/**
* holdlearn's trustless checks (design §3 seeding 1 and §2b). Every item
* that fails a check is skipped, never trusted; only what passes is learned.
* - $r.sign<N>: an l1.sign whose sender is this identity, confirmed as a
* success, whose originating `${umid}:umid` is this contract's
* transaction signed for this identity to that same address.
* - $i.owner.umids: past ledger transfers - a `${umid}:umid` that is this
* contract's `transfer` for this identity, that raised no proposal and
* was not held (or whose hold was released), read by the deterministic
* stream ids sha256(umid + name).
*/ private async holdLearnKeys(owner: any): Promise<string[]> {
const ownerId = owner.getId();
const reads = this.transactions.$r || {};
const signLabels = Object.keys(reads).filter((label) => /^sign\d+$/.test(label));
const rawUmids = this.transactions.$i.owner.umids;
if (rawUmids !== undefined && !Array.isArray(rawUmids)) throw "holdlearn: umids must be an array";
const umids: string[] = [];
for (const u of rawUmids || []) {
if (typeof u !== "string" || !/^[0-9a-f]{64}$/i.test(u)) throw "holdlearn: umids must be 64-character hex ids";
if (umids.indexOf(u.toLowerCase()) === -1) umids.push(u.toLowerCase());
}
const total = signLabels.length + umids.length;
if (total < 1 || total > HOLDLEARNMAX) throw `holdlearn: between 1 and ${HOLDLEARNMAX} items per transaction`;
const keys: string[] = [];
for (const label of signLabels) {
const sign: any = this.getReadOnlyStream(label);
if (
!sign ||
this.filterPrefix(String(sign.sender ?? "")) !== ownerId ||
!sign.confirmed ||
sign.confirmed.success !== true ||
typeof sign.toAddress !== "string" ||
!sign.toAddress ||
typeof sign.network !== "string" ||
typeof sign.umid !== "string"
) {
continue;
}
const tx = await this.holdUmidTx(sign.umid);
if (!tx || !this.holdTxIsOwn(tx, ownerId)) continue;
const request = tx.$i.owner.signtx ? tx.$i.owner.signtx : tx.$i.owner;
if (!request || typeof request.to !== "string" || !this.sameL1Address(request.to, sign.toAddress)) continue;
const key = this.holdL1Key(sign.network, sign.toAddress);
if (keys.indexOf(key) === -1) keys.push(key);
}
for (const umid of umids) {
const tx = await this.holdUmidTx(umid);
if (!tx || tx.$entry !== "transfer" || !this.holdTxIsOwn(tx, ownerId)) continue;
const to = tx.$o && tx.$o.to;
const recipientId = to ? this.filterPrefix(String(to.$stream ?? to)) : "";
if (!/^[0-9a-f]{64}$/.test(recipientId) || recipientId === ownerId) continue;
// A raised proposal moved nothing: never evidence of a payment.
const proposal = await this.holdReadOptional(this.holdHash(umid + "transfer.multisign"));
if (!proposal || proposal.found) continue;
// A held transfer counts only once released; held or cancelled, never.
const held = await this.holdReadOptional(this.holdHash(umid + "l2.hold"));
if (!held) continue;
if (held.found) {
const state = held.doc.hold && held.doc.hold.state;
if (state !== "released" && state !== "released-early") continue;
}
const key = this.holdLedgerKey(recipientId);
if (keys.indexOf(key) === -1) keys.push(key);
}
return keys;
}/** `${umid}:umid`'s transaction, or null when it cannot be read. */ private async holdUmidTx(umid: string): Promise<any> {
try {
const doc: any = await this.getAnyStreamReadOnly(`${umid}:umid`);
const tx = doc && doc.umid && doc.umid.$tx;
return tx && tx.$i && tx.$i.owner ? tx : null;
} catch (e) {
return null;
}
}/** A transaction on THIS contract, signed for this identity. */
private holdTxIsOwn(tx: any, ownerId: string): boolean {
const mine = String(this.transactions.$contract ?? "").split("@")[0];
const theirs = String(tx.$contract ?? "").split("@")[0];
return (
!!mine &&
mine === theirs &&
this.filterPrefix(String(tx.$i.owner.$stream ?? "")) === ownerId
);
}/**
* {found, doc} for a stream that exists, {found:false} for one the engine
* definitively reports missing ({notFound:true}), null when it cannot tell
* (a read error) - callers skip on null, so an error never counts as absent.
*/ private async holdReadOptional(id: string): Promise<{found: boolean; doc?: any}/** * Applies the hold action vote() validated (`holdOp`): * - config: turns protection on at once; a turn-off takes effect after * HOLDDISABLEDELAYMS unless protection was never on or a turn-off is * already pending. Emits `hold-config-change`. * - learn: adds the proven recipient keys to `withdrawHold.known`. * - claim / sent: records the gateway's email claim and hashes, then the * send. * - wrong-code: increments `failedAttempts`. * - release: marks the hold `released` (elapsed) or `released-early` * (speed-up). An L2 hold's escrow moves to the recipient and * `l2-transfer` is emitted; a speed-up also marks the recipient known. * Emits `hold-released`. A released L1 hold is signed later through * `presigned`. * - cancel: refunds the sender (L2: the escrow; L1: the amount, plus the * gas hold on a native send), drops the hold's pending known entry and * the payment's repeat-guard record, marks the hold `cancelled` and * emits `hold-cancelled`. */
private async commitHold(): Promise<boolean> {
const op = this.holdOp;
if (!op) throw "Unknown entry point";
const nowIso = this.holdIso(this.holdNowMs());
switch (op.op) {
case "config": {
const state = op.owner.getState();
const wh: any = state.withdrawHold && typeof state.withdrawHold === "object" ? {...state.withdrawHold} : {};
let effectiveAt = nowIso;
if (op.enabled) {
wh.enabled = true;
delete wh.disableAt;
} else {
if (typeof wh.disableAt === "string") {
// A turn-off already pending (or applied) keeps its own time: a
// second request never pushes it later, nor brings it forward.
effectiveAt = wh.disableAt;
} else if (wh.enabled !== true) {
// Never turned on (off by default), or already off: nothing to
// protect, so no 24-hour wait.
effectiveAt = nowIso;
} else {
effectiveAt = this.holdIso(this.holdNowMs() + HOLDDISABLEDELAYMS);
wh.disableAt = effectiveAt;
}
wh.enabled = false;
}
state.withdrawHold = wh;
op.owner.setState(state);
this.event.emit("hold-config-change", {
identity: op.owner.getId(),
enabled: op.enabled,
...(op.enabled ? {} : {disableAt: effectiveAt}),
umid: this.umid,
when: nowIso,
});
this.returnToRemote({
withdrawHold: {enabled: op.enabled, ...(op.enabled ? {} : {disableAt: effectiveAt})},
effectiveAt,
});
return true;
}
case "learn": {
const state = op.owner.getState();
const known = this.holdKnownOf(state);
const nowMs = this.holdNowMs();
let added = 0;
for (const key of op.keys) {
if (this.holdKnownSettled(state, key, nowMs)) continue;
known[key] = {at: nowIso, via: "learn"};
added++;
}
this.holdCapKnown(known);
op.owner.setState(state);
this.returnToRemote({added});
return true;
}
case "claim": {
const hold = {
...op.hold,
codeHash: op.codeHash,
cancelHash: op.cancelHash,
notify: {claimedBy: op.minigate, claimedAt: nowIso},
};
op.state.hold = hold;
op.stream.setState(op.state);
return true;
}
case "sent": {
op.state.hold = {
...op.hold,
notify: {...op.hold.notify, sentAt: nowIso, resendId: op.resendId},
};
op.stream.setState(op.state);
return true;
}
case "wrong-code": {
const hold = {...op.hold, failedAttempts: (Number(op.hold.failedAttempts) || 0) + 1};
op.state.hold = hold;
op.stream.setState(op.state);
this.returnToRemote({hold});
return true;
}
case "release": {
const hold: any = {
...op.hold,
state: op.reason === "elapsed" ? "released" : "released-early",
releasedAt: nowIso,
releasedReason: op.reason,
};
op.state.hold = hold;
if (op.kind === "l2") {
// Escrow out of the hold stream, into the recipient.
this.layer2TDetails.network = op.state.network;
this.layer2TDetails.token = op.state.token || "#native";
const amount = this.holdReadSlot(op.state, op.stream.getId());
this.holdWriteSlot(op.state, op.stream.getId(), this.getBN());
const recipientState = op.recipient.getState();
this.holdAddSlot(recipientState, op.recipient.getId(), amount);
op.recipient.setState(recipientState);
}
op.stream.setState(op.state);
if (op.owner) {
// A speed-up makes the recipient known now (design §4 step 9).
const ownerState = op.owner.getState();
const known = this.holdKnownOf(ownerState);
const entry = known[op.hold.key];
known[op.hold.key] = entry ? {...entry, until: nowIso} : {at: nowIso, until: nowIso, via: op.stream.getId()};
this.holdCapKnown(known);
op.owner.setState(ownerState);
}
this.event.emit("hold-released", {
holdId: op.stream.getId(),
kind: op.kind,
identity: this.filterPrefix(op.state.sender),
reason: op.reason,
releasedAt: nowIso,
when: nowIso,
umid: this.umid,
});
if (op.kind === "l2") {
// The credit happens now, so the transfer history hears of it now.
this.event.emit("l2-transfer", {
umid: op.state.umid,
from: this.filterPrefix(op.state.sender),
to: op.state.to,
network: op.state.network,
token: op.state.token,
amount: op.state.amount,
fee: "0",
selfSend: false,
when: nowIso,
hold: op.stream.getId(),
...(op.state.recipientWallet ? {wallet: op.state.recipientWallet} : {}),
...(op.state.recipientWallet && op.state.recipientAddress !== undefined ? {toAddress: op.state.recipientAddress} : {}),
});
}
this.returnToRemote({hold});
return true;
}
case "cancel": {
const holdId = op.stream.getId();
const refundState = op.refundTo.getState();
const refundId = op.refundTo.getId();
this.layer2TDetails.network = op.state.network;
this.layer2TDetails.token = op.state.token || "#native";
if (op.kind === "l2") {
const escrow = this.holdReadSlot(op.state, holdId);
this.holdWriteSlot(op.state, holdId, this.getBN());
this.holdAddSlot(refundState, refundId, escrow);
} else {
// The amount, and a native send's gas hold, both left the owner at
// presign. No Varnir fee was taken (credit-only model), so there is
// no fee to refund or to have deferred.
this.holdAddSlot(refundState, refundId, this.getBN(op.state.amount));
if (op.state.delegated === false && op.state.gasHold && op.state.gasHold.amount) {
this.layer2TDetails.token = "«redacted»";
this.holdAddSlot(refundState, refundId, this.getBN(op.state.gasHold.amount));
}
// The withdrawal's credit charge comes back with the amount. Once:
// holdRequireActive refuses a hold already cancelled.
const charge = op.state.creditCharge;
if (charge && charge.identity === refundId) {
const usedBefore = this.creditsAllowanceUsed(refundState);
const back = this.creditsRefundCharge(refundState, charge, this.umid, this.holdNowMs());
const allowanceBack = usedBefore - this.creditsAllowanceUsed(refundState);
// An allowance-only refund moves no balance but still changes the allowance.
if (back > 0 || allowanceBack > 0) this.emitCredits(refundId, back, refundState, "refund", allowanceBack);
}
}
// Drop the pending known entry this hold created, and this payment's
// repeat-guard record, so an honest re-send is neither exempt nor
// refused as a repeat.
if (refundState.withdrawHold && refundState.withdrawHold.known) {
const known = this.holdKnownOf(refundState);
if (known[op.hold.key] && known[op.hold.key].via === holdId) delete known[op.hold.key];
}
if (Array.isArray(refundState.recentPayments)) {
refundState.recentPayments = refundState.recentPayments.filter(
(e: any) => !e || e.umid !== op.state.umid
);
}
op.refundTo.setState(refundState);
const hold = {...op.hold, state: "cancelled", cancelledAt: nowIso, cancelledBy: op.by};
op.state.hold = hold;
op.stream.setState(op.state);
this.event.emit("hold-cancelled", {
holdId,
kind: op.kind,
identity: refundId,
cancelledAt: nowIso,
cancelledBy: op.by,
when: nowIso,
umid: this.umid,
});
this.returnToRemote({hold, layer2: [{id: refundId, partitions: refundState.layer2}]});
return true;
}
}
throw "Unknown entry point";
}/** The balance for the current network/token on `obj` (0 when missing). */
private holdReadSlot(obj: any, _id: string): BN {
this.hasValidSchemaObject(obj);
return this.getBN(this.getL2Balance(obj) || 0);
}/** Writes the balance for the current network/token on `obj`. */
private holdWriteSlot(obj: any, _id: string, value: BN): void {
this.hasValidSchemaObject(obj);
this.setL2Balance(obj, value);
}/** Adds `amount` to the balance for the current network/token on `obj`. */
private holdAddSlot(obj: any, id: string, amount: BN): void {
this.holdWriteSlot(obj, id, this.holdReadSlot(obj, id).add(amount));
}/** * Normalises a stream reference: an id longer than 64 characters keeps * only its last 64, and a `:suffix` (`:volatile`, `:stream`, `:umid`) is * kept. */
private filterPrefix(stream: string): string {
// Split off any suffix like :volatile :stream :umid (re-added below)
let [streamId, suffix] = stream.split(":");
// If id length more than 64 trim the start
if (streamId.length > 64) {
streamId = streamId.slice(-64);
}
// If suffix add it back to return
if (suffix) {
return streamId + ":" + suffix;
}
// Return just the id
return streamId;
}/** EVM addresses are case-insensitive (checksums are presentation); Tron base58 is case-sensitive. */
private sameL1Address(a: string, b: string): boolean {
if (/^0x[0-9a-fA-F]{40}$/.test(a) && /^0x[0-9a-fA-F]{40}$/.test(b)) {
return a.toLowerCase() === b.toLowerCase();
}
return a === b;
}