Testnet Mode — switch back to Production in the menuheader when you're done.
VarnirCreate extends PostProcessEvent
/**
* Voting round: the social-recovery guard; `mod` goes to voteMod.
* Otherwise refuses a missing `symbol` and an unknown network, checks the
* Bitcoin rules and the mpc-tss refusals, then calls the confidentialVM
* (`/generate`; for mpc-tss `mpc2/keygen` through the egress agent when
* `mpc2Enabled`, else on testnet `/mpc/generate-remote` then
* `/mpc/generate/fetch`) and votes yes only when this node got a share
* whose hash is in the returned hash table (for MPC-TSS, both parties'
* shares) and, for Bitcoin, the address is the P2WPKH address of the
* returned key. Every failure after the network checks also emits
* `key-generated-failed`.
*
* @returns {Promise<boolean>}
* @memberof VarnirCreate
*/ public vote(): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
// Social recovery (spec §4.5): a recovered identity is dead, a frozen one cannot move money.
const recoveryRefusal = this.refuseRecoveredStreams([]);
if (recoveryRefusal) return reject(recoveryRefusal);
if (this.transactions.$entry === "mod") {
try {
return resolve(await this.voteMod());
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
}
// Fails closed (evm-registry block): a key is only made for a network
// this contract knows - Tron, Solana, or a known EVM chain (the four
// constants or an enabled `evmNetworks` entry). EVM keys also get the
// lower-case address cache in commit().
if (this.transactions.$i.owner.symbol) {
const keyNetwork = String(this.transactions.$i.owner.network || this.transactions.$i.owner.symbol);
try {
// Bitcoin (btc block): the exact lower-case code with an enabled
// `btcNetworks` entry. No data means no Bitcoin keys.
this.btcKey = !!this.btcNetworkData(keyNetwork);
this.evmKey = !this.btcKey && !!this.evmNetworkData(keyNetwork);
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
if (!this.btcKey && !this.evmKey && this.evmNonEvmCodes().indexOf(keyNetwork.toLowerCase()) === -1) {
return reject(`Unknown network ${keyNetwork}`);
}
// Roles off Bitcoin (Bitcoin keeps its own rule below), checked before
// any CVM call so a refused key is never made. A gas key (the network
// fee wallet, spec §4.4.1) pays for moves and holds only Varnir's
// coin: pre-generated, because it is never anyone's (an owner could
// spend Varnir's float, and Deposit never credits it); Standard,
// because it signs often (an Advanced key signs at most 30 an hour);
// EVM or Tron only, the chains whose moves it pays gas for. "One per
// network" is not enforced here (it would need an index); minigate
// uses a gas key only when exactly one exists per network.
if (!this.btcKey) {
const role = this.transactions.$i.owner.role === undefined ? "deposit" : this.transactions.$i.owner.role;
if (role !== "deposit" && role !== "gas" && role !== "vault") {
return reject("A wallet role must be deposit, gas or vault (change is Bitcoin's)");
}
if (role === "gas") {
if (!this.evmKey && MPC2_TRON_CODES.indexOf(keyNetwork.toLowerCase()) === -1) {
return reject("A gas key is for an EVM or Tron network");
}
if (this.transactions.$i.owner.keyMethod === "mpc-tss") {
return reject("A gas key is Standard (Shamir) only");
}
if (!this.transactions.$i.owner.preGenerate) {
return reject("A gas key is pre-generated, never anyone's");
}
// I2: only a gateway makes a gas key. Each one comes with a fresh
// book, and although Varnir.Consolidation honours only the
// registered key, a stranger's gas keys would still be streams
// that look like Varnir's float (and a pre-generated pool key
// costs the CVMs a keygen).
try {
await this.assertGatewaySigner("A gas key");
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
this.gasKey = true;
}
// A pool vault (consolidation step 2 spec §3.1): an Advanced key that
// holds pooled coin for payouts. Advanced (mpc2) because a vault holds
// the most, and an mpc2 key is never whole anywhere, even while it
// signs (Adam, 2026-10-10). Pre-generated because it is never anyone's:
// AssignOwner refuses it and Deposit credits no one. EVM or Tron, the
// balance-based chains whose payouts a vault serves. Only a gateway
// makes one, because every gateway treats a stream with this role as a
// payout source and the destination of refill moves: a stranger's
// "vault" would be trusted as both.
if (role === "vault") {
if (!this.evmKey && MPC2_TRON_CODES.indexOf(keyNetwork.toLowerCase()) === -1) {
return reject("A vault is for an EVM or Tron network");
}
if (this.transactions.$i.owner.keyMethod !== "mpc-tss") {
return reject("A vault is Advanced (mpc-tss) only");
}
if (!this.transactions.$i.owner.preGenerate) {
return reject("A vault is pre-generated, never anyone's");
}
try {
await this.assertGatewaySigner("A vault");
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
this.vaultKey = true;
}
}
if (this.transactions.$i.owner.keyMethod === "mpc-tss") {
// Before any CVM call: a network that may not have Advanced keys
// never gets one, on either path.
const networkRefusal = this.mpcTssNetworkRefusal(keyNetwork);
if (networkRefusal) {
return reject(networkRefusal);
}
try {
this.mpc2Key = this.mpc2Enabled();
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
// Production's code-level guard: with mpc2 off there, no mpc-tss
// key is made at all, rather than one on the old protocol.
if (!this.mpc2Key && !LEGACY_MPC_TSS_ALLOWED) {
return reject("Advanced (mpc-tss) wallets are not enabled on this network");
}
// Bitcoin (plan Task 4.3): mpc2 only. The old #200 path would make a
// key that neither Bitcoin signer accepts (CryptoTransfer
// btcReadWallet refuses an mpc-tss wallet without mpcProtocol), so
// every deposit into it would be stuck.
if (this.btcKey && !this.mpc2Key) {
return reject("Bitcoin Advanced (mpc-tss) keys need mpc2");
}
// A vault is an mpc2 key only: the old (#200) protocol's keys are
// retired after the cutover, so a vault made on it could never pay.
// Checked before any CVM call, so no key is made and wasted.
if (this.vaultKey && !this.mpc2Key) {
return reject("A vault is an mpc2 key (mpc2Enabled is off)");
}
// The per-network switch (contract data `mpc2BtcNetworks`, owner
// `mod`, absent = none): OFF until the Signet drills pass. A key is
// only ever made where Varnir.CryptoTransfer can spend it, and the
// owner turns a network on only once CryptoTransfer's mpc2 Bitcoin
// branch is deployed and `maxMpcInputs` is above 0 there.
if (this.btcKey) {
try {
if (this.mpc2BtcNetworks().indexOf(keyNetwork) === -1) {
return reject(`Advanced Bitcoin wallets are off on ${keyNetwork} (mpc2BtcNetworks)`);
}
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
}
// The address rule is decided before the CVMs make a key: finding
// after keygen that the address cannot be computed would waste the
// key the CVMs just split and handed out.
if (this.mpc2Key) {
try {
this.mpc2Rule = this.mpc2AddressRule(keyNetwork);
// Before the keygen too: without both pinned signers no answer
// can be verified, and a key made anyway would be lost.
this.mpc2Signers();
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
}
}
if (this.btcKey) {
this.btcCode = keyNetwork;
const role = this.transactions.$i.owner.role === undefined ? "deposit" : this.transactions.$i.owner.role;
if (role !== "deposit" && role !== "change") {
return reject("Bitcoin wallet role must be deposit or change");
}
if (role === "change" && !this.transactions.$i.owner.preGenerate) {
return reject("A Bitcoin change wallet belongs to the pool, never to an owner");
}
// Task 4.3: every payout's change goes to a change wallet, and a
// payout may spend inputs of at most one Advanced wallet (one mpc2
// signing per transaction: the CVMs key a sign job by umid). An
// Advanced change wallet would turn ordinary change into inputs only
// that one-wallet slot can spend.
if (role === "change" && this.transactions.$i.owner.keyMethod === "mpc-tss") {
return reject("Bitcoin change wallets are Standard (Shamir) only");
}
this.btcRole = role;
}
// Credits (fix round 1, I2): a key made already owned by its signer
// never passes through Varnir.AssignOwner, so it is priced here the
// same way - the first Standard wallet per network free, any other
// at list price less the tier discount - and refused, before any key
// is made, when the balance cannot pay.
if (!this.transactions.$i.owner.preGenerate) {
try {
const owner = this.getActivityStreams(this.transactions.$i.owner);
// >>> tenant-pays
const tenantRefusal = await this.tenantOwnedKeyRefusal(owner);
if (tenantRefusal) return reject(tenantRefusal);
// <<< tenant-pays
this.walletPricing = await this.creditsPriceWallets(
owner.getState(),
// `invoice`: a single-use invoice wallet, priced higher (credits-wallets).
[{network: keyNetwork, advanced: this.transactions.$i.owner.keyMethod === "mpc-tss", invoice: this.transactions.$i.owner.invoice}],
"Credits - the plans config could not be read; the wallet was not created, try again shortly"
);
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
}
}
if (this.transactions.$i.owner.symbol) {
// Strange problem running here even in broadcast
// 1 node hangs (must be related to rebroadcast)
// Then as other suddenly vote this one times out then gets the response
// even if I set the timeou to a minute same thing
// Update Above
// Issue was with first rebroadcast, This has now been resolved. Still need to test running here.
// mpc-tss needs real headroom for two sequential cross-CVM HTTP
// calls (see the individual HTTP.send timeouts below) on top of
// real consensus vote timing across 4 separate nodes - 60s was
// sized for the single-hop standard path only.
// mpc2: above the HTTP timeout, see MPC2_VOTE_TIMEOUT_MS.
this.setTimeout(this.mpc2Key ? MPC2_VOTE_TIMEOUT_MS : 120000);
//this.ActiveLogger.info("SENDING " + this.umid);
this.keyMethod = this.transactions.$i.owner.keyMethod === 'mpc-tss' ? 'mpc-tss' : 'standard';
if (this.mpc2Key) {
try {
await this.voteMpc2(String(this.transactions.$i.owner.network || this.transactions.$i.owner.symbol));
} catch (e) {
const error = typeof e === "string" ? e : "mpc2 keygen failed";
this.event.emit('key-generated-failed', {
umid: this.umid,
error,
inputs: this.transactions.$i.owner
});
return reject(error);
}
return resolve(true);
}
try {
if (this.keyMethod === 'standard') {
const response = await HTTP.send(
`https://${CVM_HOST}/generate`,
"POST",
[],
{
umid: this.umid,
// The VM needs the Bitcoin network itself: it decides the
// address prefix (bc / tb / bcrt).
network: this.btcKey ? this.btcCode : this.transactions.$i.owner.symbol,
splits: {
threshold: THRESHOLD,
total: TOTAL
}
},
false,
20
);
if (response.data) {
this.keyGenOutput = response.data as KeyGenOutput;
if (
this.keyGenOutput.part &&
this.keyGenOutput.address &&
this.keyGenOutput.hashes
) {
// Diffy Consensus still best to check, As we maybe the only node that hasn't
// got the hash so the network will confirm we won't and then data will be lost!
if (this.keyGenOutput.hashes.indexOf(this.ActiveCrypto.Hash.getHash(this.keyGenOutput.part)) === -1) {
this.event.emit('key-generated-failed', {
umid: this.umid,
error: 'Matching hash not found',
inputs: this.transactions.$i.owner
});
return reject("Matching hash not found");
}
// Bitcoin (spec §8.4): the VM's address must be the lower-case
// P2WPKH address of the compressed key it returned, on this
// network, before anyone can be handed it to pay into.
if (this.btcKey) {
try {
this.btcAssertP2wpkhKey(this.btcCode, this.keyGenOutput.address, this.keyGenOutput.pubkey);
} catch (e) {
this.event.emit('key-generated-failed', {
umid: this.umid,
error: 'Bitcoin key check failed',
inputs: this.transactions.$i.owner
});
return reject(typeof e === "string" ? e : "Bitcoin key check failed");
}
}
resolve(true);
} else {
this.event.emit('key-generated-failed', {
umid: this.umid,
error: 'General Failure',
inputs: this.transactions.$i.owner
});
return reject("Key Generation Failed");
}
} else {
this.event.emit('key-generated-failed', {
umid: this.umid,
error: 'Single Node',
inputs: this.transactions.$i.owner
});
return reject("Key Generation Failed - Single Node");
}
} else {
// MPC-TSS: call CVM host 1 first - it drives the interactive
// protocol against host 2 itself and only then Shamir-splits
// its own party-1 share across the node quorum. Only once that
// has completed does host 2 have anything to fetch, so this
// must not run in parallel with the call below.
const response = await HTTP.send(
`https://${MPC_CVM_HOST_1}/mpc/generate-remote`,
"POST",
[],
{
umid: this.umid,
network: this.transactions.$i.owner.symbol,
remote: `https://${MPC_CVM_HOST_2}`,
splits: {
threshold: THRESHOLD,
total: TOTAL
}
},
false,
50
);
if (!response.data) {
this.event.emit('key-generated-failed', {
umid: this.umid,
error: 'Single Node',
inputs: this.transactions.$i.owner
});
return reject("Key Generation Failed - Single Node");
}
this.keyGenOutput = response.data as KeyGenOutput;
const response2 = await HTTP.send(
`https://${MPC_CVM_HOST_2}/mpc/generate/fetch`,
"POST",
[],
{
umid: this.umid,
network: this.transactions.$i.owner.symbol,
splits: {
threshold: THRESHOLD,
total: TOTAL
}
},
false,
50
);
if (!response2.data) {
this.event.emit('key-generated-failed', {
umid: this.umid,
error: 'Single Node',
inputs: this.transactions.$i.owner
});
return reject("Key Generation Failed - Single Node");
}
this.keyGenOutput2 = response2.data as MpcKeyGenOutput;
if (
this.keyGenOutput.part &&
this.keyGenOutput.address &&
this.keyGenOutput.hashes &&
this.keyGenOutput2.part2 &&
this.keyGenOutput2.hashes
) {
// Same consensus-safety check as Shamir, applied to both
// parties' shares independently - they're split on two
// different hosts with two different hash tables.
if (this.keyGenOutput.hashes.indexOf(this.ActiveCrypto.Hash.getHash(this.keyGenOutput.part)) === -1) {
this.event.emit('key-generated-failed', {
umid: this.umid,
error: 'Matching hash not found (party 1)',
inputs: this.transactions.$i.owner
});
return reject("Matching hash not found");
}
if (this.keyGenOutput2.hashes.indexOf(this.ActiveCrypto.Hash.getHash(this.keyGenOutput2.part2)) === -1) {
this.event.emit('key-generated-failed', {
umid: this.umid,
error: 'Matching hash not found (party 2)',
inputs: this.transactions.$i.owner
});
return reject("Matching hash not found");
}
resolve(true);
} else {
this.event.emit('key-generated-failed', {
umid: this.umid,
error: 'General Failure',
inputs: this.transactions.$i.owner
});
return reject("Key Generation Failed");
}
}
} catch (e) {
this.event.emit('key-generated-failed', {
umid: this.umid,
error: 'Caught Exception',
inputs: this.transactions.$i.owner,
e
});
return reject("Key Generation Failed - Caught Node");
}
} else {
reject("Missing Symbol");
}
});
}/**
* Commit round (`mod`: commitMod): writes the wallet stream (owner is
* `$i.owner`, or null with `preGenerate`) and, for Bitcoin, its UTXO book;
* stores this node's share, address and hash table as the stream's
* volatile; records address -> stream in the node's local wallets
* database (EVM also under the lower-cased address); emits
* `key-generated` and returns `{id, address, hashes}` (Bitcoin adds
* `utxoBook`, `pubkey`).
*
* @returns {Promise<any>}
* @memberof VarnirCreate
*/ public commit(): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
if (this.transactions.$entry === "mod") {
return resolve(await this.commitMod());
}
this.owner = this.transactions.$i.owner.preGenerate ? null : this.getActivityStreams(this.transactions.$i.owner);
// Credits first (priced in vote), so a broken invariant refuses before any stream is written.
if (this.owner && this.walletPricing) {
const ownerState: any = this.owner.getState() || {};
const refusal = this.creditsRecordWallets(ownerState, this.walletPricing, this.umid, new Date(this.cDate).getTime());
if (refusal) return reject(refusal);
this.owner.setState(ownerState);
if (this.walletPricing.live && this.walletPricing.credits > 0) {
this.event.emit("credits-changed", {
identity: this.owner.getId(), delta: -this.walletPricing.split.fromBalance, balance: this.creditsBalance(ownerState), allowance: 0 - this.walletPricing.split.fromAllowance, allowanceUsed: this.creditsAllowanceUsed(ownerState), reason: "wallet", umid: this.umid,
});
}
}
this.keyStream = this.newActivityStream("ntx.new.key");
const network = this.transactions.$i.owner.network || this.transactions.$i.owner.symbol;
// Bitcoin: every pool wallet gets its own UTXO book (spec §3.3), one
// stream per wallet so no single stream is locked by every deposit
// and payout. Entries are keyed `<txid>_<vout>`.
let utxoBook: any = null;
if (this.btcKey) {
utxoBook = this.newActivityStream("varnir.btc.utxobook");
utxoBook.setState({
type: "btc-utxo-book",
wallet: this.keyStream.getId(),
network,
address: this.keyGenOutput.address,
role: this.btcRole,
entries: {},
uncreditedTotal: "0",
created: this.cDate,
});
}
// A gas key's book (spec §4.3.7, §4.5.1): its own stream, as a Bitcoin
// wallet has its UTXO book, holding the top-up debt the pool lent it
// (Varnir.Consolidation) and what it paid rental providers
// (Varnir.Fees energycost, Consolidation rentalfund).
let gasBook: any = null;
if (this.gasKey) {
gasBook = this.newActivityStream("varnir.gas.book");
gasBook.setState({
type: "gas-book",
wallet: this.keyStream.getId(),
network,
topupDebt: "0",
rentalSpent: {},
rentalFunded: {},
created: this.cDate,
});
}
// Store ownership information on the key
// Can add further securty information / challanges at this point
this.keyStream.setState({
owner: this.transactions.$i.owner.preGenerate ? null : this.owner.getId(),
symbol: this.transactions.$i.owner.symbol,
network,
restrictions: {},
security: {
twoFA: this.transactions.$i.owner.twoFA || false,
personal: this.transactions.$i.owner.personal || false,
},
address: this.keyGenOutput.address,
business: this.transactions.$i.owner.business || false,
_dbIndex: this.transactions._dbIndex || 0,
// Read by CryptoTransfer/KeyHealthFix to pick the right signing
// path later - the transaction doesn't need to repeat it, it's a
// property of the key itself.
keyMethod: this.keyMethod,
// mpc2 keys (spec §4.2): Q, the protocol, and both CVMs' part-hash
// tables. In state, not volatile, because every node must send the
// same signing payload `{publicKey, partHashes, tx}` (Task 3.2).
// Q under both names, always equal: `publicKey` is what the mpc2
// signing payload sends, `pubkey` is what the Bitcoin code reads
// (CryptoTransfer btcReadWallet, the P2WPKH witness), so an Advanced
// Bitcoin wallet (Task 4.3) has Q where the Bitcoin code looks.
...(this.mpc2Key ? {
mpcProtocol: MPC2_PROTOCOL,
publicKey: this.keyGenOutput.pubkey,
pubkey: this.keyGenOutput.pubkey,
partHashes: [this.keyGenOutput.hashes, this.keyGenOutput2.hashes],
} : {}),
// Bitcoin: the compressed key goes in every P2WPKH witness (spec §2.3).
...(this.btcKey ? {pubkey: this.keyGenOutput.pubkey, role: this.btcRole, utxoBook: utxoBook.getId()} : {}),
...(this.gasKey ? {role: "gas", book: gasBook.getId()} : {}),
...(this.vaultKey ? {role: "vault"} : {}),
});
// MPC-TSS keys carry a second share (part2, from the second CVM
// host) alongside the first - standard keys only ever have `part`.
this.keyStream.setVolatile({
private: this.keyMethod === 'mpc-tss' ? {
part: this.keyGenOutput.part,
part2: this.keyGenOutput2.part2,
} : {
part: this.keyGenOutput.part,
},
public: {
address: this.keyGenOutput.address,
key: this.keyGenOutput.address,
hashes: this.keyGenOutput.hashes,
...(this.btcKey ? {pubkey: this.keyGenOutput.pubkey} : {}),
...(this.mpc2Key ? {hashes2: this.keyGenOutput2.hashes, publicKey: this.keyGenOutput.pubkey, pubkey: this.keyGenOutput.pubkey} : {}),
},
});
const dbCacheUrl = "http://127.0.0.1:5259/activeledger_wallets"
await HTTP.send(`${dbCacheUrl}`, "POST", [], {
_id: this.keyGenOutput.address,
symbol: this.transactions.$i.owner.symbol,
stream: this.keyStream.getId(),
_dbIndex: this.transactions._dbIndex || 0,
});
if (this.evmKey) {
// Lower case cache
await HTTP.send(`${dbCacheUrl}`, "POST", [], {
_id: this.keyGenOutput.address.toLowerCase(),
symbol: this.transactions.$i.owner.symbol,
stream: this.keyStream.getId(),
_dbIndex: this.transactions._dbIndex || 0,
});
}
// Instead we can have the wallets pending their first deposit
// if (this.owner && this.transactions.$i.owner.business && !this.transactions.$i.owner.preGenerate) {
// const ownerState = this.owner.getState();
// if (ownerState.walletDepositPending) {
// ownerState.walletDepositPending[this.keyStream.getId()] = this.cDate;
// } else {
// ownerState.walletDepositPending = {
// [this.keyStream.getId()]: this.cDate
// }
// }
// this.owner.setState(ownerState);
// }
this.event.emit('key-generated', {
address: this.keyGenOutput.address,
symbol: this.transactions.$i.owner.symbol,
network: this.transactions.$i.owner.network || this.transactions.$i.owner.symbol,
stream: this.keyStream.getId(),
...(this.btcKey ? {utxoBook: utxoBook.getId(), role: this.btcRole} : {}),
...(this.gasKey ? {role: "gas", book: gasBook.getId()} : {}),
...(this.vaultKey ? {role: "vault"} : {}),
});
this.returnToRemote({
id: this.keyStream.getId(),
address: this.keyGenOutput.address,
hashes: this.keyGenOutput.hashes,
...(this.btcKey ? {utxoBook: utxoBook.getId(), pubkey: this.keyGenOutput.pubkey} : {}),
...(this.gasKey ? {book: gasBook.getId()} : {}),
...(this.mpc2Key ? {publicKey: this.keyGenOutput.pubkey} : {}),
});
// Now if they provide $o.pool we can use this as the trigger to add this new wallet to the pool
// if (this.transactions.$o?.pool) {
// const pool = this.getActivityStreams(this.transactions.$o.pool);
// const poolState = pool.getState();
// // Lets make sure the pool is setup!
// if (poolState.stakedWallets) {
// poolState.stakedWallets.push(key.getId());
// } else {
// poolState.stakedWallets = [key.getId()];
// }
// }
resolve(true);
});
} private refuseRecoveredIdentity(state: any, outgoing: boolean): string | null {
if (state && state.recoveredTo) {
// A dead identity may still RECEIVE: the credit lands and is swept to recoveredTo.
return outgoing
? `Identity recovered - new identity is ${state.recoveredTo}; your keys are still valid`
: null;
}
if (outgoing && state && state.recovery && state.recovery.frozen) {
return "Identity frozen - a social recovery is in its 48h waiting period";
}
return null;
} private refuseRecoveredStreams(incomingOnly: string[] | "all-outputs"): string | null {
// Never getActivityStreams(ref): an unloaded ref CREATES a stream. The
// no-argument form returns only the streams this transaction loaded.
const ctx: any = this as any;
const loaded: any = ctx.getActivityStreams() || {};
const outputs: any = (ctx.transactions && ctx.transactions.$o) || {};
const toId = (label: string, ref: any): string | null => {
const raw = ref && typeof ref === "object" ? ref.$stream : typeof ref === "string" ? ref : /^[0-9a-f]{64}$/i.test(label) ? label : null;
return typeof raw === "string" ? raw.split(":")[0].slice(-64) : null;
};
const outputIds: string[] = [];
const incomingIds: string[] = [];
for (const label of Object.keys(outputs)) {
const id = toId(label, outputs[label]);
if (!id) continue;
outputIds.push(id);
if (incomingOnly === "all-outputs" || incomingOnly.indexOf(label) !== -1) incomingIds.push(id);
}
for (const id of Object.keys(loaded)) {
const activity = loaded[id];
if (!activity || typeof activity.getState !== "function") continue;
const signed = typeof activity.hasSignature === "function" && activity.hasSignature();
const incoming = !signed && outputIds.indexOf(id) !== -1 && incomingIds.indexOf(id) !== -1;
const refusal = this.refuseRecoveredIdentity(activity.getState(), !incoming);
if (refusal) return refusal;
}
return null;
} 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;
}/**
* 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();
}
}/** Advanced (mpc2) wallets are priced as `walletAdvanced` and are never the sign-up wallet. */
private creditsIsAdvancedWallet(state: any): boolean {
return state.mpcProtocol !== undefined || state.keyMethod === "mpc-tss";
}/** * Stage F4 (docs/plans/tenant-pays-stage-f-consolidation-pricing.md §3.2, answer 5), for an OWNED key (not * `preGenerate`), only while Varnir's consolidation block has `addressCharge: true` (a deploy alone changes nothing): * - a tenant tag (`$i.owner.tenant`) is refused: a tenant deposit wallet is a pool wallet assigned through the tenant * (Varnir.AssignOwner, which bills `wallet.deposit` to the tenant's float and marks the wallet); * - otherwise the member rule (memberRuleRefusal, the same as Varnir.AssignOwner's): a member is refused unless its * tenant (named as `$r.memberOf`, or read by the record's `m`) is not on the float or is suspended. A key let * through is priced by creditsPriceWallets exactly as for a non-member (sign-up wallet and allowance included). * `owner` is the `$i.owner` activity. Why not, or null. An unreadable plans config refuses, as creditsPriceWallets * does. */
private async tenantOwnedKeyRefusal(owner: any): Promise<string | null> {
if (!PLANS_CONFIG_STREAM) return null;
let cfg: any;
try {
cfg = await this.getAnyStreamReadOnly(PLANS_CONFIG_STREAM);
} catch (e) {
return "Credits - the plans config could not be read; the wallet was not created, try again shortly";
}
if (!cfg || typeof cfg !== "object" || cfg.kind !== "varnir.plans.config") return "Credits - the plans config could not be read; the wallet was not created, try again shortly";
const c = cfg.varnirPrices ? cfg.varnirPrices.consolidation : undefined;
if (!c || typeof c !== "object" || c.addressCharge !== true) return null;
if (this.transactions.$i.owner.tenant) return "Tenants - a tenant deposit wallet is a pool wallet assigned through the tenant (Varnir.AssignOwner), never a key made here";
return this.memberRuleRefusal(c, owner.getId(), owner.getState(), new Date(this.cDate).getTime());
}/** * The member rule (docs/plans/tenant-pays-stage-f-consolidation-pricing.md §3.2, answer 5; `memberUntaggedWallets`), * for an UNTAGGED new wallet while `addressCharge` is on (`block`, Varnir's consolidation block): with "refuse", an * identity holding an unexpired membership record (`tm`, written only by Varnir.Tenants `join`) is refused unless its * tenant cannot take the wallet itself: * - the tenant is not on the credit float; * - the tenant master's `suspended` is exactly true, or it is a sub-tenant whose parent, named as `$r.memberParent`, * is suspended (exactly true). * The master is `$r.memberOf` when the transaction names it (the fast path). Otherwise, when the record carries `m` * (the master's stream id, written by `join`), it is read by that id (a plain read: no lock). Either way the master * is bound to the record: its `tenantId` must be the id it was read under and the record's hash `h` is recomputed * from it (for a sub-tenant: its parent and itself), so a wrong or forged master or `m` lifts nothing (nor does a * sub-tenant reparented or detached since `join`: its member must leave or join again); a parent that is not this * sub-tenant's is refused. Known limitation: the master (and parent) read is each node's local copy, not pinned to * a revision, so a node a revision behind on `suspended`, `floatMode` or `revokedBefore` can vote differently around * a flip; the master is rarely written, and a retry resolves it. A record issued at or before the tenant's `revokedBefore` is no membership. * A wallet let through is priced to the identity exactly as for a non-member (the caller's creditsPriceWallets, * creditsWalletCharge): the first Standard wallet per network is the free sign-up wallet and the monthly allowance * is drawn first, so Varnir carries those as it does for anyone; the tenant pays nothing. Why not, or null. */
private async memberRuleRefusal(block: any, ownerId: string, ownerState: any, now: number): Promise<string | null> {
if (!block || block.memberUntaggedWallets !== "refuse") return null;
const tm = ownerState && ownerState.tm;
if (!tm || typeof tm !== "object" || !Number.isSafeInteger(tm.expires) || !(now < tm.expires)) return null;
const r: any = this.transactions.$r || {};
const idOf = (ref: any) => (ref !== null && typeof ref === "object" ? ref.$stream : ref);
let refId: any;
let master: any;
let via: string;
if (r.memberOf !== undefined && r.memberOf !== null) {
refId = idOf(r.memberOf);
via = "$r.memberOf";
master = this.getReadOnlyStream("memberOf");
} else if (typeof tm.m === "string" && /^[0-9a-f]{64}$/.test(tm.m)) {
refId = tm.m;
via = "the tenant master this identity's membership record names (tm.m " + tm.m + ")";
try {
master = await this.getAnyStreamReadOnly(tm.m);
} catch (e) {
return "Tenants - this identity's tenant master could not be read; the wallet was not created, try again shortly (or name its master as $r.memberOf)";
}
} else {
return "Tenants - this identity belongs to a tenant: create its deposit wallets through the tenant (a tenant not on the credit float or suspended: name its master as $r.memberOf)";
}
if (!master || master.kind !== "varnir.tenant" || typeof master.tenantId !== "string" || master.tenantId !== refId) return "Tenants - " + via + " is not a tenant master";
// A sub-tenant reparented or detached since `join` no longer hashes to the record either: the message says so.
if (tm.h !== this.memberLiftHash(master, ownerId)) return "Tenants - " + via + " is not the tenant this identity belongs to, or its parent has changed since this identity joined (the membership no longer matches the tenant's current parent): leave the tenant or join it again";
const before = Number.isSafeInteger(master.revokedBefore) ? master.revokedBefore : 0;
if (!Number.isSafeInteger(tm.issued) || !(tm.issued > before)) return null;
if (master.floatMode !== true) return null;
if (master.suspended === true) return null;
if (r.memberParent !== undefined && r.memberParent !== null) {
if (typeof master.parentId !== "string" || idOf(r.memberParent) !== master.parentId) return "Tenants - $r.memberParent is not this sub-tenant's parent";
const parent: any = this.getReadOnlyStream("memberParent");
if (!parent || parent.kind !== "varnir.tenant" || parent.tenantId !== master.parentId) return "Tenants - $r.memberParent is not this sub-tenant's parent";
if (parent.suspended === true) return null;
}
return "Tenants - this identity belongs to a tenant that runs on the credit float: create its deposit wallets through the tenant";
}/** The membership record's hash (Varnir.Tenants `join`): sha256(tenantId|subId|senderId|"varnir.tenant.member"), a sub naming its parent and itself. */
private memberLiftHash(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 `evmNetworks` fields this contract stores and reads (evm-registry block). */
private evmFieldSpec(): {required: string[]; optional: string[]}/**
* True when one of the contract stream's authorities has `public` equal to
* `identity` (voteMod passes the signing identity's stream id).
*/
/**
* Proves a $selfsign signer is a Varnir gateway (minigate), as
* Varnir.Deposit's assertMinigateSigner does: the signer names its
* minigate identity as `$r.minigate`; that identity's `:volatile` carries
* the `minigate` flag (only an operator writes it) and `$i.owner.publicKey`
* is one of its authorities (`:stream`). $selfsign alone proves only that
* the signer holds some key. Missing reference, missing docs or a failed
* read all refuse (fail closed).
*
* @private
* @returns {Promise<void>}
* @memberof VarnirCreate
*/ private async assertGatewaySigner(what: string): Promise<void> {
const ref = this.transactions.$r ? this.transactions.$r.minigate : undefined;
if (!ref || typeof ref !== "string") {
throw `${what} is made only by a gateway (missing $r.minigate)`;
}
let volatile: any = null;
let meta: any = null;
try {
volatile = await this.getAnyStreamReadOnly(`${ref}:volatile`);
meta = await this.getAnyStreamReadOnly(`${ref}:stream`);
} catch (e) {
throw `${what} is made only by a gateway (reference unreadable)`;
}
if (!volatile || !volatile.minigate) {
throw `${what} is made only by a gateway (reference is not a gateway)`;
}
const key = this.transactions.$i.owner.publicKey;
const ok = typeof key === "string" && key.length > 0 && meta && Array.isArray(meta.authorities) &&
meta.authorities.some((a: any) => a && a.public === key);
if (!ok) {
throw `${what} is made only by a gateway (signing key is not a gateway authority)`;
}
} private hasContractOwnership(contract: any, identity: string): boolean {
return contract.getAuthorities().some((v: any) => v.public === identity);
}/** * Owner-only `mod`: writes this contract's `evmNetworks` (the evm-registry * block's chain table) and `btcNetworks` (the btc block's). Each whole map * is validated first; one bad field refuses the write. */
private async voteMod(): Promise<boolean> {
if (!this.transactions.$o || !this.transactions.$o.contract) {
throw "Missing Contract Output";
}
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)) {
throw "No Contract Authority";
}
this.assertEvmNetworks(this.transactions.$i.owner.evmNetworks);
this.assertBtcNetworks(this.transactions.$i.owner.btcNetworks);
this.assertMpc2Enabled(this.transactions.$i.owner.mpc2Enabled);
this.assertMpc2BtcNetworks(this.transactions.$i.owner.mpc2BtcNetworks);
return true;
}/** `mod` commit: stores `evmNetworks`, `btcNetworks` and `mpc2Enabled` (each replaced whole, else kept), `umid` and `updated`. */
private async commitMod(): Promise<boolean> {
const wrapper: any = this.getContractData();
const cd: any = wrapper && wrapper.data ? wrapper.data : {};
// Replaced whole, never merged here: the write script merges first.
cd.evmNetworks = this.transactions.$i.owner.evmNetworks ?? cd.evmNetworks ?? null;
cd.btcNetworks = this.transactions.$i.owner.btcNetworks ?? cd.btcNetworks ?? null;
cd.mpc2Enabled = this.transactions.$i.owner.mpc2Enabled ?? cd.mpc2Enabled ?? null;
// Replaced whole; `[]` switches every network off again.
cd.mpc2BtcNetworks = this.transactions.$i.owner.mpc2BtcNetworks ?? cd.mpc2BtcNetworks ?? null;
cd.umid = this.umid;
cd.updated = this.cDate;
this.setContractData(cd);
return true;
}/** * 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 wrapper: any = this.getContractData();
const stored = wrapper && wrapper.data ? wrapper.data.mpc2Enabled : undefined;
if (stored === undefined || stored === null) {
return false;
}
if (typeof stored !== "boolean") {
throw "mpc2Enabled contract data is malformed";
}
return stored;
}/** The `mod` validator for `mpc2Enabled`: absent leaves it alone, else exactly true or false. */ /** * The Bitcoin networks where Advanced (mpc2) wallets may be made (plan Task * 4.3): contract data `mpc2BtcNetworks`, a list of exact Bitcoin codes. * Absent or null is none, the default. Anything malformed throws: a typo * must not switch a network on. */
private mpc2BtcNetworks(): string[] {
const wrapper: any = this.getContractData();
const stored = wrapper && wrapper.data ? wrapper.data.mpc2BtcNetworks : undefined;
if (stored === undefined || stored === null) {
return [];
}
if (!this.validMpc2BtcNetworks(stored)) {
throw "mpc2BtcNetworks contract data is malformed";
}
return stored.slice();
}/** The `mod` validator for `mpc2BtcNetworks`: absent leaves it alone, else a list of distinct Bitcoin codes. */
private assertMpc2BtcNetworks(value: any): void {
if (value === undefined || value === null) {
return;
}
if (!this.validMpc2BtcNetworks(value)) {
throw "mpc2BtcNetworks must be a list of distinct Bitcoin network codes";
}
} private validMpc2BtcNetworks(v: any): boolean {
return Array.isArray(v) && v.every((c: any, i: number) => typeof c === "string" && this.btcParams(c) !== null && v.indexOf(c) === i);
} 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";
}
}/** * The one place that says which networks may never have an Advanced key, * on either path (plan Global Constraints: refuse rather than guess). * Null when `keyNetwork` may. */
private mpcTssNetworkRefusal(keyNetwork: string): string | null {
// Bitcoin is allowed since plan Task 4.3 (mpc2 path only, checked in
// vote(); the P2WPKH rule is in mpc2AddressRule / mpc2AddressOf).
// Solana is Ed25519 and every mpc2 key is secp256k1, so an Advanced
// Solana key could never sign. Refused for good (plan, Decided).
if (MPC2_SOLANA_CODES.indexOf(keyNetwork.toLowerCase()) !== -1) {
return "Solana keys are Standard (Shamir) only";
}
return null;
}/** * The mpc2 vote: asks this node's egress agent for `mpc2/keygen` and checks * both CVMs' answers. On success sets keyGenOutput (CVM-A: Q as `pubkey`, * A's table and part) and keyGenOutput2 (CVM-B's table and part) for * commit(). Throws a string on any failure; the caller emits * `key-generated-failed` and refuses. */
private async voteMpc2(keyNetwork: string): Promise<void> {
let response: any;
try {
response = await HTTP.send(
`${MPC2_EGRESS_URL}/mpc2/keygen`,
"POST",
[],
{
umid: this.umid,
// The key's own network, not the symbol: the CVMs bind it into the
// sid and into each sealed part, and refuse a non-secp256k1 one.
network: keyNetwork,
// The CVM schema requires exactly this at keygen (node-auth.ts
// keygenKeyId): the key stream is only created in commit().
keyId: utils.sha256(utils.toUtf8Bytes(this.umid + "ntx.new.key")).slice(2),
keyMethod: "mpc-tss",
mpcProtocol: MPC2_PROTOCOL,
// Keygen agrees on nothing but the fields above. No `splits`,
// `threshold` or `remote`: those are compiled into the CVMs (C3).
payload: {},
},
false,
MPC2_HTTP_TIMEOUT_S
);
} catch (e) {
throw "mpc2 keygen: the egress agent did not answer";
}
const both = response ? response.data : null;
if (!both || typeof both !== "object" || Array.isArray(both)) {
throw "mpc2 keygen: no answer from the egress agent";
}
const a = this.mpc2CheckAnswer(both.a, "CVM-A", 0);
const b = this.mpc2CheckAnswer(both.b, "CVM-B", 1);
// Spec §4.2 step 5: the CVMs compare Q between themselves, but a node
// does not take that on trust: two different Qs mean the two shares do
// not belong to one key, and nothing could ever sign with it.
if (a.publicKey !== b.publicKey) {
throw "mpc2 keygen: Q differs between CVM-A and CVM-B";
}
// Both parts must be at this node's one index, or the node would hold
// part i of A's share and part j of B's, and its signing request would
// be refused by one CVM's table.
if (a.partIndex !== b.partIndex) {
throw "mpc2 keygen: partIndex differs between CVM-A and CVM-B";
}
// Two independent shares have disjoint part tables. A shared entry means
// one CVM's answer was replayed as the other's, and this node would hold
// two parts of one share and none of the other.
for (const hash of a.partHashes) {
if (b.partHashes.indexOf(hash) !== -1) {
throw "mpc2 keygen: CVM-A and CVM-B answered with the same share";
}
}
this.mpc2CheckSignedTuples(both.a, both.b, keyNetwork, a, b);
const address = this.mpc2AddressOf(a.publicKey);
this.keyGenOutput = {
status: "ok",
umid: this.umid,
address,
pubkey: a.publicKey,
hashes: a.partHashes,
part: a.part,
};
this.keyGenOutput2 = {
status: "ok",
umid: this.umid,
address,
pubkey: b.publicKey,
hashes: b.partHashes,
part2: b.part,
};
}/** One CVM's answer, checked on its own against the party it must come from. Throws a string naming the CVM. */
private mpc2CheckAnswer(raw: any, who: string, party: number): Mpc2KeygenAnswer {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
throw `mpc2 keygen: no answer from ${who}`;
}
// The CVMs answer `{status: 'error', error}` on a refusal (conflict,
// busy, aux not ready): a failed keygen, never a partial key.
if (raw.status !== "ok") {
throw `mpc2 keygen: ${who} refused`;
}
// An answer for another umid belongs to another key: storing its part
// here would tie this wallet stream to shares nobody else recorded.
if (raw.umid !== this.umid) {
throw `mpc2 keygen: ${who} answered for another umid`;
}
// The answer must name the party it is filed under. Swapped answers pass
// every other check (same Q, disjoint tables), but would store B's table
// as A's: at signing CVM-A would then be sent B's parts, which match
// that table, and rebuild B's share after holding its own at keygen, so
// one machine would have seen both shares (spec §3.2). Until Task 2.8
// signs the answers this binds only the labelling, not authenticity.
if (raw.party !== party) {
throw `mpc2 keygen: ${who}'s answer is not from party ${party}`;
}
// Q is stored and later sent as the signing payload's `publicKey`, which
// the CVMs accept only as a compressed point (mpc2/digest.ts Q_HEX).
if (typeof raw.publicKey !== "string" || !/^0[23][0-9a-f]{64}$/.test(raw.publicKey)) {
throw `mpc2 keygen: ${who}'s Q must be a compressed secp256k1 key`;
}
// An x with no point on the curve has no key and no address behind it.
// x must also be below the field prime: the curve library reduces a
// larger x silently, so one key would have two spellings of Q.
const fieldPrime = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");
if (BigInt("0x" + raw.publicKey.slice(2)) >= fieldPrime) {
throw `mpc2 keygen: ${who}'s Q is not a secp256k1 point`;
}
try {
utils.computePublicKey("0x" + raw.publicKey, false);
} catch (e) {
throw `mpc2 keygen: ${who}'s Q is not a secp256k1 point`;
}
// Four distinct SHA-256 hashes, one per part of the 3-of-4 split
// (TOTAL): KeyHealthCheck and the signing CVM match parts against these
// entries, so a short or repeated table could let a wrong part pass.
const table = raw.partHashes;
if (!Array.isArray(table) || table.length !== TOTAL) {
throw `mpc2 keygen: ${who}'s table must be four distinct part hashes`;
}
for (let i = 0; i < table.length; i++) {
if (typeof table[i] !== "string" || !/^[0-9a-f]{64}$/.test(table[i]) || table.indexOf(table[i]) !== i) {
throw `mpc2 keygen: ${who}'s table must be four distinct part hashes`;
}
}
// The index names the table entry this node's part must match.
if (typeof raw.partIndex !== "number" || !Number.isInteger(raw.partIndex) || raw.partIndex < 1 || raw.partIndex > TOTAL) {
throw `mpc2 keygen: ${who}'s partIndex must be 1 to 4`;
}
// Diffy consensus, as on the Standard path: this node votes yes only for
// a part it really holds, at its own index. A node that cannot vouch for
// its part says no, so the network never records a key it cannot rebuild.
if (typeof raw.part !== "string" || raw.part.length === 0 ||
this.ActiveCrypto.Hash.getHash(raw.part, "sha256") !== table[raw.partIndex - 1]) {
throw `mpc2 keygen: ${who}'s part hash is not this node's entry in its table`;
}
return {
status: raw.status,
umid: raw.umid,
party: raw.party,
publicKey: raw.publicKey,
partHashes: table,
partIndex: raw.partIndex,
part: raw.part,
};
}/** * How an Advanced key's address is computed on `keyNetwork`: "evm", * "tron" or (plan Task 4.3) "p2wpkh" for an enabled Bitcoin network. * Decided in vote() before any CVM call. Anything else throws (Solana never * has a rule). */
private mpc2AddressRule(keyNetwork: string): string {
// Before the EVM rule: a Bitcoin code is never an EVM network, but the
// order keeps a Bitcoin key from ever getting a keccak address.
if (this.btcKey) {
return "p2wpkh";
}
if (this.evmKey) {
return "evm";
}
if (MPC2_TRON_CODES.indexOf(keyNetwork.toLowerCase()) !== -1) {
return "tron";
}
throw `mpc2 keygen: no Advanced address rule for ${keyNetwork}`;
}/** * The address of Q under the rule vote() chose, computed here so the * wallet stream records exactly what Q can spend from (spec §4.2 step 5), * never an address a CVM or the agent supplied. EVM: the checksummed * keccak address. Tron: base58check of 41 ‖ the same 20 bytes. Bitcoin * (Task 4.3): the lower-case P2WPKH address of HASH160(Q) on this network, * then decoded again by btcAssertP2wpkhKey, the check every Standard * Bitcoin key passes (spec §8.4), so the encoder and the btc block's decoder * must agree before anyone is handed the address to pay into. */
private mpc2AddressOf(q: string): string {
if (this.mpc2Rule === "p2wpkh") {
if (!this.btcKey || this.btcCode === "") {
throw "mpc2 keygen: no Bitcoin network for the P2WPKH rule";
}
const address = this.btcP2wpkhAddressOf(this.btcCode, q);
this.btcAssertP2wpkhKey(this.btcCode, address, q);
return address;
}
const evmAddress = utils.computeAddress("0x" + q);
if (this.mpc2Rule === "evm") {
return evmAddress;
}
if (this.mpc2Rule === "tron") {
const payload = "0x41" + evmAddress.slice(2).toLowerCase();
const checksum = utils.sha256(utils.sha256(payload)).slice(2, 10);
return utils.base58.encode(payload + checksum);
}
throw "mpc2 keygen: no Advanced address rule was chosen";
}/** * The lower-case P2WPKH (witness v0, bech32 BIP173) address of compressed * key `pubkey` on Bitcoin network `code`, from the btc block's own HASH160 * and bech32 helpers. The btc block only decodes addresses (a contract * never needed to make one: Standard keys arrive with the CVM's address, * which btcAssertP2wpkhKey checks); an mpc2 key arrives as Q alone. * Tested against @varnir/btc-core's p2wpkhAddress and BIP173's vectors. */
private btcP2wpkhAddressOf(code: string, pubkey: string): string {
if (typeof pubkey !== "string" || !/^0[23][0-9a-f]{64}$/.test(pubkey)) {
throw "Bitcoin: key must be a 33-byte compressed public key";
}
const params = this.btcParams(code);
if (params === null) {
throw `Unknown Bitcoin network ${code}`;
}
const program = Array.from(this.btcHash160(this.btcHexToBytes(pubkey)));
const data = [0].concat(this.btcConvertBits(program, 8, 5, true));
// BIP173: the checksum makes polymod(hrp ‖ data ‖ checksum) equal 1
// (bech32, the constant for witness version 0; bech32m is for v1+).
const mod = this.btcPolymod(this.btcHrpExpand(params.hrp).concat(data).concat([0, 0, 0, 0, 0, 0])) ^ 1;
const charset = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let out = params.hrp + "1";
for (const d of data) {
out += charset.charAt(d);
}
for (let i = 0; i < 6; i++) {
out += charset.charAt((mod >>> (5 * (5 - i))) & 31);
}
return out;
}/** The per-tree signer constants, read in one place (tests pin other values here). */
private mpc2SignerConstants(): [string, string] {
return [CVM_A_SIGNER, CVM_B_SIGNER];
}/** * `[CVM-A's signer, CVM-B's signer]`, checksummed. Throws while either is * blank (not configured until gate G3) or malformed, or when they are * equal: one key on both hosts lets one host sign both tuples (PR #355 * review L-2). */
private mpc2Signers(): [string, string] {
const [rawA, rawB] = this.mpc2SignerConstants();
if (rawA === "" || rawB === "") {
throw "mpc2 keygen: the CVM signers are not configured on this network";
}
let a = "";
let b = "";
try {
a = utils.getAddress(rawA);
b = utils.getAddress(rawB);
} catch (e) {
throw "mpc2 keygen: a CVM signer address is malformed";
}
if (a === b) {
throw "mpc2 keygen: the two CVM signers must differ";
}
return [a, b];
}/** Canonical JSON as the CVMs sign it (packages/cvm-attest canonical.ts): keys sorted, no whitespace. */
private mpc2Canonical(v: any): string {
if (Array.isArray(v)) {
return "[" + v.map((x) => this.mpc2Canonical(x)).join(",") + "]";
}
if (v !== null && typeof v === "object") {
return "{" + Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + this.mpc2Canonical(v[k])).join(",") + "}";
}
if (typeof v === "number" && !Number.isFinite(v)) {
throw "mpc2 keygen: a tuple holds a non-finite number";
}
return JSON.stringify(v);
}/** * The address whose key made `signerSig` (`r ‖ s ‖ v` hex, v 27/28) over * SHA-256(MPC2_KEYGEN_ANSWER_DOMAIN + "\n" + canonical JSON of `tuple`), * or "" when it is malformed. Pinned by the published vector * (apps/confidentialVM/test/vectors/keygen-answer-v1.json). */
private mpc2AnswerSigner(tuple: any, signerSig: any): string {
if (typeof signerSig !== "string" || !/^[0-9a-f]{128}(1b|1c)$/.test(signerSig)) {
return "";
}
try {
const digest = utils.sha256(utils.toUtf8Bytes(MPC2_KEYGEN_ANSWER_DOMAIN + "\n" + this.mpc2Canonical(tuple)));
return utils.recoverAddress(digest, "0x" + signerSig);
} catch (e) {
return "";
}
}/**
* The CVMs' signed keygen tuples, checked by this node itself (PR #350
* review M1, PR #356 review M2): the agent checks them too, but M1's point
* is that every node does, so a compromised agent cannot have its node
* record a Q of its choosing, or tables no CVM made.
* - each tuple is exactly `{v: 1, umid, keyId, network, party, publicKey,
* partHashes: [A's 4, B's 4]}` for this request, naming the Q and both
* tables this node is about to store, and its own party;
* - CVM-A's recovers to CVM_A_SIGNER with party 0, CVM-B's to CVM_B_SIGNER
* with party 1;
* - the two are equal but for `party`, so all four nodes store one Q and
* one pair of tables.
* Throws a string naming the failed check.
*/ private mpc2CheckSignedTuples(rawA: any, rawB: any, keyNetwork: string, a: Mpc2KeygenAnswer, b: Mpc2KeygenAnswer): void {
const [signerA, signerB] = this.mpc2Signers();
const keyId = utils.sha256(utils.toUtf8Bytes(this.umid + "ntx.new.key")).slice(2);
const tables = JSON.stringify([a.partHashes, b.partHashes]);
const parties: [any, number, string, string][] = [[rawA, 0, "CVM-A", signerA], [rawB, 1, "CVM-B", signerB]];
for (const [raw, party, who, signer] of parties) {
const t = raw.answer;
// Exactly the seven fields the CVMs sign: an extra one would be a
// claim nobody checks, a missing one a claim nobody made.
if (!t || typeof t !== "object" || Array.isArray(t) || Object.keys(t).length !== 7 || t.v !== 1) {
throw `mpc2 keygen: ${who}'s signed tuple is malformed`;
}
// Its own role: a tuple signed for the other party would let one CVM's
// signature stand for both.
if (t.party !== party) {
throw `mpc2 keygen: ${who}'s signed tuple is not for party ${party}`;
}
// This request, this Q and the very tables stored: a signed tuple about
// anything else proves nothing about this key.
if (t.umid !== this.umid || t.keyId !== keyId || t.network !== keyNetwork || t.publicKey !== a.publicKey ||
JSON.stringify(t.partHashes) !== tables) {
throw `mpc2 keygen: ${who}'s signed tuple is not this key's tuple`;
}
if (this.mpc2AnswerSigner(t, raw.signerSig) !== signer) {
throw `mpc2 keygen: ${who}'s signerSig is not its pinned signer's`;
}
}
// Equal but for party (implied by the checks above, said once here so a
// later edit to them cannot quietly drop it).
if (this.mpc2Canonical({...rawA.answer, party: 0}) !== this.mpc2Canonical({...rawB.answer, party: 0})) {
throw "mpc2 keygen: the two signed tuples differ";
}
}/** 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)`;
}
}
}/** 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};
} public postProcess(territoriality: boolean, who: string): Promise<any> {
return new Promise<any>((resolve) => resolve(true));
}