Testnet Mode — switch back to Production in the menuheader when you're done.
VarnirDeposit extends PostProcessEvent
/**
* Voting round. Every output is a credit, so recovered or frozen
* identities may receive. `mod` goes to voteMod. Otherwise: the signer
* must be a gateway (assertMinigateSigner); a deposit carrying `btc` or
* `btcKnown` is refused (those are the contract's own fields). Per
* deposit, a wallet/user mismatch, a missing `txhash`, a repeated deposit
* id in this batch or a failed lookup marks it as an error and it is not
* credited; the network must be a known one or an `evmNetworks` entry
* (else the whole vote is refused); Bitcoin runs btcVoteDeposit. The vote
* fails with "Deposit(s) Already Processed" when every deposit is already
* recorded, and with "DAP:[ids]" when any is.
*
* @returns {Promise<boolean>}
* @memberof VarnirDeposit
*/ public vote(): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
// Social recovery (spec §4.5): every output here is a deposit credit
// landing on a user's wallet, never a debit - all may be tombstoned/frozen.
const recoveryRefusal = this.refuseRecoveredStreams("all-outputs");
if (recoveryRefusal) return reject(recoveryRefusal);
// Mod contract first
if (this.transactions.$entry === "mod") {
// A refusal is the transaction's rejection message, never an
// unhandled throw inside this executor (which would leave the vote to
// time out instead of failing).
try {
return resolve(await this.voteMod());
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
}
// Every non-mod entry credits a user's L2 balance, so the signer must be
// a Varnir gateway (see assertMinigateSigner). Checked before anything
// else reads the deposit list.
try {
await this.assertMinigateSigner();
} catch (e) {
return reject(e);
}
// We need to make sure the calling user is allowed to make an update to the balance
// Maybe include the transaction on L1 that does it so we can verify
// Possibly we can verify anyway using a scanner / node and this is a trigger
// TODO - Add age check just in case we delete this database for checking
// TODO - Should we actually write it as a determanistic stream? Then if 2 selfsign process at once
// Only one should actually work?
// Lets assume admin.multi is the array to check
this.multiDeposits = this.transactions.$i.admin.multi || [];
let alreadyDeposited = 0;
const depositedMap = [];
const depositedL1Check = [];
const multiDepositCheck = [];
// Actually can await here local calls no real advantage
for (let i = this.multiDeposits.length; i--;) {
const deposit = this.multiDeposits[i];
// `btc` and `btcKnown` are worked out by btcVoteDeposit, never sent:
// commit writes the book `btc` names, so a gateway-made one would
// reach a book (or a credit minimum) nothing checked (security
// review L1).
if (deposit && (deposit.btc !== undefined || deposit.btcKnown !== undefined)) {
return reject("Bitcoin: btc fields are the contract's own, never the gateway's");
}
// Verify wallet (in $r) has this userStream so no node owner can change it
const inboundWallet = this.getReadOnlyStream(deposit.wallet);
// A network fee wallet (gas key, consolidation spec §4.4.1, §5.1)
// holds Varnir's float, which is no user's balance: a sighting into
// it is credited to no one. Checked on the role, not left to the
// pairing check below: a gas key has no owner, so a sighting with no
// userStream would pass that check (undefined === undefined) and
// credit whatever the gateway named.
if (inboundWallet && inboundWallet.role === "gas") {
deposit.error = "A network fee wallet is credited to no one";
} else if (inboundWallet && inboundWallet.role === "vault") {
// A pool vault (consolidation step 2) holds pooled coin, no user's
// balance. Checked on the role, explicitly: a vault has no owner, so
// a sighting with no userStream would pass the pairing check below
// (undefined === undefined) and credit whatever the gateway named.
deposit.error = "A pool vault is credited to no one";
} else if (inboundWallet.owner !== deposit.userStream) {
// should make $i.owner
deposit.error = "Invalid Wallet User Pairing";
} else {
if (deposit.txhash) {
try {
// txhash here is a deposit ID, not necessarily a bare
// transaction hash: a token transfer arrives as
// `<hash>_<logIndex>` so that two deposits in ONE transaction
// stay distinct. That is the whole point - this check used to
// see one hash twice and reject the second as "multiple entries
// found in tx", which silently dropped a real deposit whenever a
// batch payout paid two watched wallets at once. Native
// transfers keep the bare hash, since there is only ever one per
// transaction.
if (multiDepositCheck.indexOf(deposit.txhash) === -1) {
multiDepositCheck.push(deposit.txhash);
depositedL1Check.push(
HTTP.send(
// The `#` rewrite is for LEGACY ids only. The id format
// used to be `<hash>#<index>` and `#` is a URI fragment
// delimiter, so it had to be rewritten to reach the
// document at all. Current ids use `_`, which is safe in a
// URI untouched - that is precisely why it was changed -
// so this replace is a no-op for anything written now and
// stays only so records created under the old format
// remain readable.
`${this.txDepositedUrl}/${deposit.txhash?.replace(
"#",
":"
)}`,
"GET"
)
.then(async (deposited) => {
if ((deposited.data as any)._id) {
deposit.alreadyDeposited = true;
alreadyDeposited++;
depositedMap.push(deposit.txhash);
return;
}
// A token transfer's id is `<hash>_<logIndex>` and a
// Bitcoin output's `<txid>_<vout>`. An internal move
// (consolidation, ceiling move, frozen-key sweep) is
// marked by its bare hash when CryptoTransfer signs it,
// before any broadcast, so it is never credited to the
// destination's owner, whatever order the sighting and
// the confirm arrive in (Adam, 2026-10-09).
// Marks are lower case, as CryptoTransfer writes them.
const id = String(deposit.txhash);
const cut = id.indexOf("_");
const bare = (cut > 0 ? id.slice(0, cut) : id).toLowerCase();
if (bare !== id) {
try {
const base: any = (await HTTP.send(`${this.txDepositedUrl}/${bare}`, "GET")).data;
if (base && base._id && base.consolidation === true) {
deposit.alreadyDeposited = true;
deposit.internalMove = true;
alreadyDeposited++;
depositedMap.push(deposit.txhash);
}
} catch (e) {
// No record of the bare hash: an ordinary deposit.
}
}
})
.catch(() => {
deposit.error =
"couldn't verify if deposit already processed";
})
);
} else {
// shouldn't increase counters here may cause other problems if already already deposited.
// Also adding it to depositMap may also be a bad idea at this point.
deposit.error = "multiple entries found in tx";
}
} catch {
// Most likely noit found
deposit.error = "couldn't verify if deposit already processed";
}
} else {
deposit.error = "txhash missing";
}
}
// At this point we may or may not know about errors but can still check!
if (!deposit.error) {
// Bitcoin (spec §8.3): an explicit branch from `btcNetworks`, never
// the EVM default below. A Bitcoin code with no enabled entry fails
// closed.
if (this.btcParams(deposit.network) !== null) {
try {
this.btcVoteDeposit(deposit);
} catch (e) {
return reject(typeof e === "string" ? e : "Bitcoin deposit refused");
}
continue;
}
// Now fetch the transaction, will use some hard coded values to customise the url
let lowercaseCompare = false;
let networkUrl: string;
switch (deposit.network) {
case "TRX":
networkUrl = "TRX_TRX";
break;
case "TRX-SHASTA":
networkUrl = "TRX_SHASTA";
break;
case "TRX-NILE":
// Varnir's own Tron testnet (see QuickNodeMonitor.chain2Network -
// this is the exact string every deposit-watch provider
// credits Tron Nile deposits under). Missing here made every
// Tron Nile deposit vote-fail forever with "Unknown network
// type" - found live: minigate's own logs showed the same
// deposit retried every ~2s, never committing, despite the
// scanner already showing it "Confirmed" (that status only
// reflects the webhook/D1 sighting, not real on-chain
// crediting - see Deposits.Credit's own doc comment on the
// pending-queue/broadcast split). Not lowercase-compared
// (lowercaseCompare stays false, matching TRX/TRX-SHASTA
// above) - Tron's base58 addresses are case-sensitive by
// encoding, unlike EVM's checksum casing.
networkUrl = "TRX_NILE";
break;
case "ETH":
networkUrl = "ETH_ETH";
lowercaseCompare = true;
break;
case "SEP":
networkUrl = "ETH_SEP";
lowercaseCompare = true;
break;
case "BNB":
networkUrl = "BSC_BSC";
lowercaseCompare = true;
break;
case "tBNB":
networkUrl = "BSC_CHAPEL";
lowercaseCompare = true;
break;
case "SOL":
networkUrl = "SOL_SOL";
//lowercaseCompare = true;
break;
case "SOLDEV":
networkUrl = "SOL_DEV";
//lowercaseCompare = true;
break;
default: {
// An EVM chain from this contract's own `evmNetworks` data
// (evm-registry block), matched on its exact ledger spelling like
// the cases above. Anything else is still refused.
let evmChain: any = null;
try {
evmChain = this.evmNetworkData(deposit.network);
} catch (e) {
return reject(typeof e === "string" ? e : "L1 Check : Unknown network type");
}
if (!evmChain || evmChain.ledger !== deposit.network) {
return reject("L1 Check : Unknown network type");
}
networkUrl = evmChain.ledger;
lowercaseCompare = true;
break;
}
}
// The BlockSignal L1 deposit-confirmation call was removed here. It
// was already dead - DEPOSIT_CONFIRMATION_API was empty, so this
// branch never ran - and the provider is gone. The switch above still
// validates the network (rejecting unknown ones); the actual deposit
// crediting below runs regardless and is unchanged.
}
}
// We can now possible combine the loops
await Promise.allSettled(depositedL1Check);
// A Bitcoin output already in its wallet's UTXO book was recorded by an
// earlier deposit, whatever the volatile cache says.
for (const deposit of this.multiDeposits) {
if (deposit.btcKnown && !deposit.alreadyDeposited) {
deposit.alreadyDeposited = true;
alreadyDeposited++;
depositedMap.push(deposit.txhash);
}
}
if (this.multiDeposits.length === alreadyDeposited) {
return reject("Deposit(s) Already Processed");
}
// Todo we could always process the others that made it this is just safest
if (depositedMap.length) {
return reject("DAP:" + JSON.stringify(depositedMap));
}
return resolve(true);
});
}/**
* Commit round (`mod`: commitMod). For each deposit without an error:
* adds the amount (Bitcoin: what btcCommitDeposit releases from the UTXO
* book) to `userStream`'s `layer2[network][token].balance`, sets
* `lastDeposit` when the credit is non-zero, and queues a response
* (amount, network, token, txHash, accounts, layer2) for the caller.
*
* @returns {Promise<any>}
* @memberof VarnirDeposit
*/ public commit(): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
// Mod contract first
if (this.transactions.$entry === "mod") {
return resolve(await this.commitMod());
}
//let walletDbIndex = 0;
for (let i = this.multiDeposits.length; i--;) {
const deposit = this.multiDeposits[i];
if (!deposit.error && !deposit.alreadyDeposited) {
// Currently all the same users so could cache
const user = deposit.userStream;
const userStream = this.getActivityStreams(user);
const userState = userStream.getState();
this.layer2TDetails = {
network: deposit.network,
token: deposit.token || "#native",
};
this.hasValidSchemaObject(userState);
const layer2WalletParts =
userState.layer2[deposit.network][deposit.token];
const ownerBalance = this.getBN(layer2WalletParts.balance);
//const walletState = await this.getAnyStreamReadOnly(deposit.wallet);
const walletState = this.getReadOnlyStream(deposit.wallet);
deposit.walletDbIndex = walletState._dbIndex;
deposit.toWalletAddress = walletState.address;
// Bitcoin: the output goes into the wallet's UTXO book first, and
// only what the accumulation rule releases is credited (spec §4.4).
const tmpAmount = deposit.btc
? this.getBN(this.btcCommitDeposit(deposit, walletState))
: this.getBN(deposit.amount);
// Credit-only fee model (docs/superpowers/specs/2026-09-25-withdrawal-fee-integrity revision;
// ruling RV11): every deposit - above or below the old minimum, first or
// not, business wallet or not - credits the FULL amount. No on-ledger
// Varnir fee, minimum-deposit floor, business-wallet uplift or
// first-deposit surcharge is taken. A below-minimum deposit was never
// rejected even before this change (the old fee branches' own "no
// deposit fees" fallthrough already credited it in full), so there is
// no dust-rejection behaviour to preserve here. The
// `deposit.firstDeposit` / `walletState.firstDeposit[network]` /
// `walletDepositPending` markers had no reader anywhere in this repo
// other than this now-removed surcharge (checked: minigate's
// Deposits.Credit computes and forwards `firstDeposit` solely to
// decide the surcharge and to request wallet write access for it),
// so they are dropped rather than kept as inert tracking.
deposit.varnirFee = "0";
layer2WalletParts.balance = ownerBalance.add(tmpAmount).toString();
// Credits-only pricing: the largest single deposit per partition,
// raw units. Free's free payout unlocks on a $10+ stablecoin
// deposit (the config's stablecoin list names the partitions).
if (!tmpAmount.isZero()) {
const credits = userState.credits && typeof userState.credits === "object" ? userState.credits : {};
const largest = credits.maxDeposit && typeof credits.maxDeposit === "object" ? credits.maxDeposit : {};
const netLargest = largest[deposit.network] && typeof largest[deposit.network] === "object" ? largest[deposit.network] : {};
const previous = netLargest[this.layer2TDetails.token];
if (!previous || !/^[0-9]+$/.test(String(previous)) || tmpAmount.gt(previous)) {
netLargest[this.layer2TDetails.token] = tmpAmount.toString();
}
largest[deposit.network] = netLargest;
credits.maxDeposit = largest;
userState.credits = credits;
}
// Set last deposit processed (a Bitcoin output below the minimum
// credits nothing yet, so it is not one)
if (!tmpAmount.isZero()) {
layer2WalletParts.lastDeposit = this.umid;
}
userStream.setState(userState);
this.response.push({
metadata: this.transactions.metadata || null,
umid: this.umid,
amount: deposit.amount,
varnirFee: deposit.varnirFee.toString(),
network: deposit.network,
token: deposit.token,
txHash: deposit.txhash,
toAccount: deposit.userStream,
toAddress: deposit.toWalletAddress,
fromAddress: deposit.from,
alreadyDeposited: deposit.alreadyDeposited,
walletDbIndex: deposit.walletDbIndex,
...(deposit.btc ? { btc: deposit.btc.result } : {}),
layer2: [
{
id: userStream.getId(),
partitions: userState.layer2,
alreadyDeposited: deposit.alreadyDeposited,
},
],
});
} else {
// TODO return response show error linked to txhash
}
}
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;
}/** A BN from a `{hex}` object, a decimal / 0x string or a number; 0 for a falsy value. */ private getBN(data?: any): BN {
if (data) {
if (data.hex) {
return BN.from(data.hex);
} else {
return BN.from(data);
}
} else {
return BN.from("0x00");
}
}/** * After commit, on each node: records every credited deposit id in the * node's local deposits database (the double-credit check vote() reads) * and emits `tx-known` (txhash, network, the receiving wallet's address * and token). A failed write is only logged. */
public postProcess(territoriality: boolean, who: string): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
for (let i = this.response.length; i--;) {
const response = this.response[i];
if (!response.alreadyDeposited) {
try {
// Update "Volatile" cache
await HTTP.send(`${this.txDepositedUrl}/`, "POST", null, {
// Keyed on the deposit ID, so two deposits in one transaction
// persist as two records instead of the second colliding with
// the first. The `#` rewrite is legacy-only - see the lookup
// above.
_id: response.txHash?.replace("#", ":"),
umid: this.umid,
//response,
});
// network, wallet (the pool wallet's L1 address the deposit
// landed in) and token: each gateway marks that wallet's cached
// L1 balance stale (minigate balance-view.ts), so its next
// read is live. Gateways still accept the older txhash-only event.
this.event.emit("tx-known", {
txhash: response.txHash,
network: response.network,
wallet: response.toAddress,
token: response.token,
});
} catch (e) {
// Not much we can do apart from report it in the logs
this.ActiveLogger.error({ response, e }, "Deposit Register Error");
}
}
}
return resolve(true);
});
}/** * Sets up and manages the layer2 object across all streams. * * Used to key by a `partitions[id]` dict where `id` was always the * document's own stream id (never a different party's) - genuinely * redundant, confirmed by reading every call site in this file, so * simplified to a single `balance` field instead of a one-entry dict. */
private hasValidSchemaObject(obj: any) {
const defaultBalance = this.getBN(0);
// Make sure layer 2 object exists on this wallet
// (Must be a better way to do this, but this will always work and be dynamic)
if (!obj.layer2) {
obj.layer2 = {};
}
// Ensure that this network has been setup for layer 2 operations (+ token)
if (!obj.layer2[this.layer2TDetails.network]) {
obj.layer2[this.layer2TDetails.network] = {
[this.layer2TDetails.token]: { balance: defaultBalance },
};
}
// Double check token as it maybe a new token on an old network
if (!obj.layer2[this.layer2TDetails.network][this.layer2TDetails.token]) {
obj.layer2[this.layer2TDetails.network][this.layer2TDetails.token] = { balance: defaultBalance };
}
}/** This contract's own data (`getContractData().data`), or {} when unset. */ private getContractDataHelper() {
//this.ActiveLogger.warn(this.getContractData(), "CONTRACT DATA");
return this.getContractData().data ?? {};
}/** * Proves the $selfsign signer is a Varnir gateway (minigate), the same gate * as Varnir.CryptoTransfer's assertMinigateSigner. $selfsign only proves the * signer holds the private key for $i.admin.publicKey - any generated key * passes that - so without this anyone could credit any wallet. The signer * names its minigate identity as a read-only $r.minigate reference and we * require: * 1. that stream's :volatile carries the `minigate` flag, which only an * operator can write (no contract exposes a write to it); * 2. $i.admin.publicKey is one of that identity's authorities (:stream). * Either alone is bypassable. Missing reference, missing docs or a failed * read all refuse (fail closed). */
private async assertMinigateSigner(): Promise<void> {
const minigateRef = this.transactions.$r?.minigate;
if (!minigateRef || typeof minigateRef !== "string") {
throw "Deposit not authorised - missing minigate reference";
}
let minigateVolatile: any = null;
let minigateMeta: any = null;
try {
minigateVolatile = await this.getAnyStreamReadOnly(`${minigateRef}:volatile`);
minigateMeta = await this.getAnyStreamReadOnly(`${minigateRef}:stream`);
} catch {
throw "Deposit not authorised - minigate reference unreadable";
}
if (!minigateVolatile?.minigate) {
throw "Deposit not authorised - reference is not a minigate";
}
const signingKey = this.transactions.$i?.admin?.publicKey;
const authorised =
typeof signingKey === "string" &&
signingKey.length > 0 &&
Array.isArray(minigateMeta?.authorities) &&
minigateMeta.authorities.some((a: any) => a?.public === signingKey);
if (!authorised) {
throw "Deposit not authorised - signing key is not a minigate authority";
}
}/** The `evmNetworks` fields this contract stores and reads (evm-registry block). */
private evmFieldSpec(): {required: string[]; optional: string[]}/** 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)`;
}
}
}/**
* Bitcoin deposit checks for one entry of `multi` (spec §3.3, §4.4, §8.3).
* Throws a string; any refusal rejects the whole transaction. The gateway
* sends `{wallet, userStream, network, token: "«redacted»", txhash:
* "<txid>_<vout>", amount: "<sats>", to: "<address>", height?}` and puts
* the wallet's UTXO book in `$o`.
*/ private btcVoteDeposit(deposit: any): void {
const btcNet = this.requireBtcNetwork(deposit.network);
this.btcParseOutpoint(deposit.txhash);
if (deposit.token !== "#native") {
throw "Bitcoin: deposit token must be #native";
}
if (typeof deposit.amount !== "string" || !/^[1-9][0-9]{0,15}$/.test(deposit.amount) || BigInt(deposit.amount) > 2100000000000000n) {
throw "Bitcoin: deposit amount must be a positive whole number of sats";
}
// Dust never enters a book (security review M6): it costs more to spend
// than it is worth, and recording each one would let anyone grow a book
// without limit.
if (BigInt(deposit.amount) < BigInt(btcNet.dustSats)) {
throw "Bitcoin: deposit is below the network dust floor (dustSats)";
}
if (deposit.height !== undefined && (typeof deposit.height !== "number" || !Number.isInteger(deposit.height) || deposit.height < 0)) {
throw "Bitcoin: deposit height must be a non-negative integer";
}
const wallet = this.getReadOnlyStream(deposit.wallet);
if (!wallet || typeof wallet.owner !== "string" || wallet.owner === "") {
throw "Bitcoin: deposit wallet has no owner";
}
if (wallet.network !== btcNet.code || wallet.role !== "deposit" || typeof wallet.utxoBook !== "string") {
throw "Bitcoin: not a Bitcoin deposit wallet for this network";
}
// Exact match on the normalised address (spec §9): no lower-case
// compare, the normaliser refuses mixed case and other networks.
if (typeof deposit.to !== "string" || this.btcNormaliseAddress(btcNet.code, deposit.to) !== wallet.address) {
throw "Bitcoin: deposit address does not match the wallet";
}
// The book must be loaded by this transaction to be written. Never
// getActivityStreams(ref) for an unloaded ref: that creates a stream.
const loaded: any = (this as any).getActivityStreams() || {};
const book = loaded[wallet.utxoBook];
if (!book || typeof book.getState !== "function") {
throw "Bitcoin: the wallet's UTXO book is not an output of this transaction";
}
const state = book.getState();
if (!state || state.type !== "btc-utxo-book" || state.wallet !== deposit.wallet || state.network !== btcNet.code || state.address !== wallet.address) {
throw "Bitcoin: UTXO book does not belong to this wallet";
}
if (!/^(0|[1-9][0-9]*)$/.test(String(state.uncreditedTotal))) {
throw "Bitcoin: UTXO book is malformed";
}
if (state.entries && Object.keys(state.entries).indexOf(deposit.txhash) !== -1) {
deposit.btcKnown = true;
}
deposit.btc = { book: wallet.utxoBook, minCreditSats: String(btcNet.minCreditSats) };
// EVERY deposit to a frozen Advanced address is HELD (PR #417 review
// H1, re-review N1; Adam 2026-10-09). Its key signs nothing but its
// owner-authorised sweep, and a sweep's reach is finite (min(maxMpcInputs,
// 5) inputs a signing, 32 signings a key), so crediting a coin there would
// be L2 credit that may have nothing spendable behind it, a loss to the
// pool a sender could repeat at will. "A sweep could still move it" was
// not enough: a signing already armed has picked its inputs, and many
// small coins outrun any count. So the coin is recorded in the book as
// `held` (with whom it is for), credited to nobody, and paged; a sweep
// spends it, and ConfirmWithdraw credits it to `heldFor` when that sweep
// confirms, exactly once.
// Whatever the freeze flag says (round 3 review R3-1): `mpc2FreezeEnabled`
// stops NEW freezes being recorded; it does not stop honouring a record
// that exists (from before the flag, or recorded while it was on). Such a
// key signs nothing, as the CVMs and CryptoTransfer already treat it, so a
// credit here would have nothing spendable behind it.
if (wallet.mpcFrozen !== undefined) {
deposit.btc.hold = true;
}
}/**
* Record one Bitcoin deposit in its wallet's UTXO book and apply the
* accumulation rule (spec §4.4): the output is added as `uncredited` and to
* the book's `uncreditedTotal`; once that total reaches `minCreditSats`
* (which a deposit at or above the minimum always does), the whole total is
* credited, every `uncredited` entry becomes `spendable` and the total
* resets. Returns the sats to credit now, as a string ("0" while below).
*/ private btcCommitDeposit(deposit: any, walletState: any): string {
const book = this.getActivityStreams(deposit.btc.book);
const state = book.getState();
const entries = state.entries || {};
if (deposit.btc.hold) {
// Held (btcVoteDeposit says why): in the book, out of the
// accumulation total, credited to nobody now. `heldFor` is whom the
// sweep's confirmation credits once it has moved the coin.
entries[deposit.txhash] = {
value: deposit.amount,
scriptType: "p2wpkh",
source: "deposit",
depositId: deposit.txhash,
state: "held",
heldFor: deposit.userStream,
heldBy: this.umid,
created: this.cDate,
...(deposit.height !== undefined ? {height: deposit.height} : {}),
};
state.entries = entries;
book.setState(state);
deposit.btc.result = {
utxoBook: deposit.btc.book,
address: walletState.address,
credited: "0",
held: true,
uncreditedTotal: String(state.uncreditedTotal),
minCreditSats: deposit.btc.minCreditSats,
creditedDepositIds: [],
};
this.event.emit("deposit-held", {
wallet: deposit.wallet,
owner: deposit.userStream,
network: deposit.network,
txhash: deposit.txhash,
amount: deposit.amount,
address: walletState.address,
});
return "0";
}
const entry: any = {
value: deposit.amount,
scriptType: "p2wpkh",
source: "deposit",
depositId: deposit.txhash,
state: "uncredited",
created: this.cDate,
};
if (deposit.height !== undefined) {
entry.height = deposit.height;
}
entries[deposit.txhash] = entry;
let total = BigInt(state.uncreditedTotal) + BigInt(deposit.amount);
let credited = 0n;
const creditedIds: string[] = [];
if (total >= BigInt(deposit.btc.minCreditSats)) {
credited = total;
for (const id of Object.keys(entries).sort()) {
if (entries[id].state === "uncredited") {
entries[id].state = "spendable";
entries[id].creditedBy = this.umid;
creditedIds.push(id);
}
}
total = 0n;
}
state.entries = entries;
state.uncreditedTotal = total.toString();
book.setState(state);
deposit.btc.result = {
utxoBook: deposit.btc.book,
address: walletState.address,
credited: credited.toString(),
uncreditedTotal: total.toString(),
minCreditSats: deposit.btc.minCreditSats,
creditedDepositIds: creditedIds,
};
return credited.toString();
}/** Address parameters per code. Returned fresh, never shared. */
private btcParams(code: string): {hrp: string; p2pkh: number; p2sh: number}/** This contract's stored `btcNetworks` map ({} when unset). Throws when it is not an object. */ private btcStoredNetworks(): {[code: string]: any}/** The `btcNetworks` entry for `code`, enabled or not, with `code` set, or null. Throws when it is malformed. */
private btcAnyNetworkData(code: string): any | null {
const key = typeof code === "string" ? code : "";
if (this.btcParams(key) === null) {
return null;
}
const stored = this.btcStoredNetworks();
if (Object.keys(stored).indexOf(key) === -1) {
return null;
}
this.assertBtcNetworkEntry(key, stored[key]);
return {...stored[key], code: key};
}/** The enabled `btcNetworks` entry for `code` with `code` set, or null. Throws when it is malformed. */
private btcNetworkData(code: string): any | null {
const found = this.btcAnyNetworkData(code);
return found && found.enabled === true ? found : null;
}/** btcNetworkData, failing closed. For new Bitcoin work: wallets, deposits, payouts. */
private requireBtcNetwork(code: string): any {
const found = this.btcNetworkData(code);
if (!found) {
throw `Unknown Bitcoin network ${code}`;
}
return found;
}/** * btcAnyNetworkData, failing closed. For finishing what is already signed * (broadcast, bump, cancel, confirm, refund): `enabled: false` stops new * Bitcoin work, never the way out of a payout in flight. */
private requireBtcNetworkInFlight(code: string): any {
const found = this.btcAnyNetworkData(code);
if (!found) {
throw `Unknown Bitcoin network ${code}`;
}
return found;
}/** The `mod` validator for a whole `btcNetworks` map. Absent leaves the stored map alone. */
private assertBtcNetworks(value: any): void {
if (value === undefined || value === null) {
return;
}
if (typeof value !== "object" || Array.isArray(value)) {
throw "btcNetworks must be an object keyed by network code";
}
for (const code of Object.keys(value)) {
this.assertBtcNetworkEntry(code, value[code]);
}
}/** * One `btcNetworks` entry (spec §8.1). Every field is required but the * optional `mpcCeilingSats` (PR #417 review M1); no others are allowed. */
private assertBtcNetworkEntry(code: string, entry: any): void {
const params = this.btcParams(code);
if (params === null) {
throw `btcNetworks: ${code} is not a Bitcoin network`;
}
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
throw `btcNetworks.${code} must be an object`;
}
const fields = ["ledger", "hrp", "enabled", "confirmations", "conflictDepth", "feeRateCapSatVb",
"sweepFeeRateCap", "referenceVbytes", "dustSats", "minCreditSats", "maxInputs", "maxMpcInputs",
"maxSweepInputs", "maxBatchOutputs", "broadcast"];
// The Advanced (mpc2) wallet ceiling, in sats (PR #417 review M1):
// Varnir.CryptoTransfer's `btcmove` reason `ceiling` checks a move
// against it, so a gateway cannot move Advanced coins on its own word.
// Optional: absent, no ceiling move is accepted on the network.
const optional = ["mpcCeilingSats"];
for (const field of Object.keys(entry)) {
if (fields.indexOf(field) === -1 && optional.indexOf(field) === -1) {
throw `btcNetworks.${code}.${field} is not a Bitcoin network field`;
}
}
if (entry.mpcCeilingSats !== undefined && (typeof entry.mpcCeilingSats !== "string" || !/^[1-9][0-9]{0,15}$/.test(entry.mpcCeilingSats))) {
throw `btcNetworks.${code}.mpcCeilingSats must be a positive integer string of sats`;
}
for (const field of fields) {
if (Object.keys(entry).indexOf(field) === -1) {
throw `btcNetworks.${code}.${field} is required`;
}
}
if (entry.ledger !== code) {
throw `btcNetworks.${code}.ledger must be ${code}`;
}
if (entry.hrp !== params.hrp) {
throw `btcNetworks.${code}.hrp must be ${params.hrp}`;
}
if (typeof entry.enabled !== "boolean") {
throw `btcNetworks.${code}.enabled must be true or false`;
}
const int = (name: string, min: number, max: number) => {
const v = entry[name];
if (typeof v !== "number" || !Number.isSafeInteger(v) || v < min || v > max) {
throw `btcNetworks.${code}.${name} must be an integer from ${min} to ${max}`;
}
};
int("confirmations", 1, 100);
int("conflictDepth", 1, 100);
if (entry.conflictDepth < entry.confirmations) {
throw `btcNetworks.${code}.conflictDepth must be at least confirmations`;
}
int("sweepFeeRateCap", 1, 10000);
int("referenceVbytes", 100, 1000);
int("maxInputs", 1, 100);
int("maxMpcInputs", 0, 100);
int("maxSweepInputs", 1, 100);
int("maxBatchOutputs", 1, 100);
if (entry.maxMpcInputs > entry.maxInputs) {
throw `btcNetworks.${code}.maxMpcInputs must not exceed maxInputs`;
}
const caps = entry.feeRateCapSatVb;
if (!caps || typeof caps !== "object" || Array.isArray(caps) || Object.keys(caps).length !== 3) {
throw `btcNetworks.${code}.feeRateCapSatVb must be {instant, standard, economy}`;
}
for (const speed of ["instant", "standard", "economy"]) {
const v = caps[speed];
if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 1 || v > 10000) {
throw `btcNetworks.${code}.feeRateCapSatVb.${speed} must be an integer from 1 to 10000`;
}
}
for (const name of ["dustSats", "minCreditSats"]) {
if (typeof entry[name] !== "string" || !/^[1-9][0-9]{0,15}$/.test(entry[name])) {
throw `btcNetworks.${code}.${name} must be a positive integer string of sats`;
}
}
if (BigInt(entry.dustSats) < this.btcDustThreshold("p2wpkh")) {
throw `btcNetworks.${code}.dustSats must be at least the P2WPKH relay dust (294)`;
}
const urls = entry.broadcast;
if (!Array.isArray(urls) || urls.length < 1 || urls.length > 4) {
throw `btcNetworks.${code}.broadcast must list 1 to 4 URLs`;
}
for (const u of urls) {
// Keyless endpoints only: no credentials or query strings in contract data.
if (typeof u !== "string" || !/^https:\/\/[a-z0-9.-]+(:[0-9]{1,5})?(\/[A-Za-z0-9._~\/-]*)?$/.test(u)) {
throw `btcNetworks.${code}.broadcast entries must be plain https URLs`;
}
}
} private btcHexToBytes(hex: string): Uint8Array {
if (typeof hex !== "string" || hex.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(hex)) {
throw "Bitcoin: invalid hex";
}
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return out;
} private btcBytesToHex(bytes: Uint8Array): string {
let s = "";
for (let i = 0; i < bytes.length; i++) {
s += (bytes[i] < 16 ? "0" : "") + bytes[i].toString(16);
}
return s;
} private btcConcat(parts: Uint8Array[]): Uint8Array {
let len = 0;
for (const p of parts) {
len += p.length;
}
const out = new Uint8Array(len);
let off = 0;
for (const p of parts) {
out.set(p, off);
off += p.length;
}
return out;
} private btcReverse(bytes: Uint8Array): Uint8Array {
const out = new Uint8Array(bytes.length);
for (let i = 0; i < bytes.length; i++) {
out[i] = bytes[bytes.length - 1 - i];
}
return out;
} private btcSha256d(data: Uint8Array): Uint8Array {
return utils.arrayify(utils.sha256(utils.sha256(data)));
} private btcHash160(data: Uint8Array): Uint8Array {
return utils.arrayify(utils.ripemd160(utils.sha256(data)));
} private btcU32(n: number): Uint8Array {
if (typeof n !== "number" || !Number.isInteger(n) || n < 0 || n > 4294967295) {
throw "Bitcoin: u32 out of range";
}
return Uint8Array.from([n & 255, (n >>> 8) & 255, (n >>> 16) & 255, (n >>> 24) & 255]);
} private btcU64(n: bigint): Uint8Array {
if (typeof n !== "bigint" || n < 0n || n > 2100000000000000n) {
throw "Bitcoin: amount out of range";
}
const out = new Uint8Array(8);
let v = n;
for (let i = 0; i < 8; i++) {
out[i] = Number(v & 255n);
v = v >> 8n;
}
return out;
} private btcVarint(n: number): Uint8Array {
if (n < 253) {
return Uint8Array.from([n]);
}
if (n <= 65535) {
return Uint8Array.from([253, n & 255, n >>> 8]);
}
throw "Bitcoin: varint too large";
} private btcVarbytes(b: Uint8Array): Uint8Array {
return this.btcConcat([this.btcVarint(b.length), b]);
} private btcPolymod(values: number[]): number {
const gen = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
let chk = 1;
for (const v of values) {
const hi = chk >>> 25;
chk = (((chk & 0x1ffffff) << 5) ^ v) >>> 0;
for (let i = 0; i < 5; i++) {
if ((hi >>> i) & 1) {
chk = (chk ^ gen[i]) >>> 0;
}
}
}
return chk;
} private btcHrpExpand(hrp: string): number[] {
const out: number[] = [];
for (let i = 0; i < hrp.length; i++) {
out.push(hrp.charCodeAt(i) >>> 5);
}
out.push(0);
for (let i = 0; i < hrp.length; i++) {
out.push(hrp.charCodeAt(i) & 31);
}
return out;
} private btcConvertBits(data: number[], from: number, to: number, pad: boolean): number[] {
let acc = 0;
let bits = 0;
const out: number[] = [];
const maxv = (1 << to) - 1;
for (const value of data) {
acc = (acc << from) | value;
bits += from;
while (bits >= to) {
bits -= to;
out.push((acc >> bits) & maxv);
}
}
if (pad) {
if (bits > 0) {
out.push((acc << (to - bits)) & maxv);
}
} else if (bits >= from || ((acc << (to - bits)) & maxv) !== 0) {
throw "Bitcoin: invalid address padding";
}
return out;
}/** A segwit address for `hrp` (BIP173 + BIP350): {version, program}. Throws on any rule break. */ private btcDecodeSegwit(hrp: string, s: string): {version: number; program: Uint8Array} private btcBase58checkDecode(s: string): Uint8Array {
const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
if (s.length < 1 || s.length > 64) {
throw "Bitcoin: malformed base58 address";
}
let n = 0n;
for (let i = 0; i < s.length; i++) {
const d = alphabet.indexOf(s.charAt(i));
if (d === -1) {
throw "Bitcoin: invalid base58 character";
}
n = n * 58n + BigInt(d);
}
const body: number[] = [];
while (n > 0n) {
body.unshift(Number(n & 255n));
n = n >> 8n;
}
let zeros = 0;
while (zeros < s.length && s.charAt(zeros) === "1") {
zeros++;
}
const raw = new Uint8Array(zeros + body.length);
raw.set(Uint8Array.from(body), zeros);
if (raw.length < 5) {
throw "Bitcoin: base58 address too short";
}
const payload = raw.slice(0, raw.length - 4);
const check = this.btcSha256d(payload);
for (let i = 0; i < 4; i++) {
if (raw[raw.length - 4 + i] !== check[i]) {
throw "Bitcoin: invalid base58 checksum";
}
}
return payload;
}/**
* Decode an address for one network: {type, hash, address} with `address`
* the normalised form (bech32 lower-case, base58 as given). Refuses another
* network's address, mixed case, whitespace, and witness versions nobody can
* spend yet (v2-16, and v1 programs that are not 32 bytes).
*/ private btcDecodeAddress(code: string, s: string): {type: string; hash: Uint8Array; address: string}/** * A key the confidential VM made for a pool wallet (spec §8.4): `pubkey` * must be a 33-byte compressed key and `address` exactly the lower-case * P2WPKH address of its HASH160 on this network. Returns the pubkey hex. */
private btcAssertP2wpkhKey(code: string, address: string, pubkey: string): string {
if (typeof pubkey !== "string" || !/^0[23][0-9a-f]{64}$/.test(pubkey)) {
throw "Bitcoin: key must come with its 33-byte compressed public key";
}
const d = this.btcDecodeAddress(code, address);
if (d.type !== "p2wpkh" || d.address !== address) {
throw "Bitcoin: a pool wallet must have a lower-case P2WPKH address";
}
if (this.btcBytesToHex(this.btcHash160(this.btcHexToBytes(pubkey))) !== this.btcBytesToHex(d.hash)) {
throw "Bitcoin: address does not match the public key";
}
return pubkey;
}/** The one normaliser (spec §9). */
private btcNormaliseAddress(code: string, s: string): string {
return this.btcDecodeAddress(code, s).address;
}/** Serialised output size per address type. */
private btcOutputBytes(type: string): number {
const sizes: {[type: string]: number} = {p2pkh: 34, p2sh: 32, p2wpkh: 31, p2wsh: 43, p2tr: 43};
if (Object.keys(sizes).indexOf(type) === -1) {
throw "Bitcoin: unknown output type";
}
return sizes[type];
}/** * Worst-case vsize of a transaction spending `inputs` P2WPKH inputs (each * with a 72-byte signature, 272 weight units) to these output types. Never * below the signed transaction's real vsize, so fee checks use it. */
private btcEstimateVsize(inputs: number, outputTypes: string[]): number {
if (!Number.isInteger(inputs) || inputs < 1 || inputs > 252 || outputTypes.length < 1 || outputTypes.length > 252) {
throw "Bitcoin: bad transaction shape";
}
let base = 4 + 1 + 1 + 4;
for (const t of outputTypes) {
base += this.btcOutputBytes(t);
}
return Math.ceil((base * 4 + 2 + inputs * 272) / 4);
}/** Bitcoin Core's relay dust threshold at 3 sat/vB: 294 P2WPKH, 330 P2WSH/P2TR, 546 P2PKH, 540 P2SH. */
private btcDustThreshold(type: string): bigint {
const segwit = type === "p2wpkh" || type === "p2wsh" || type === "p2tr";
const spend = segwit ? 67 : 148;
return BigInt(Math.floor((this.btcOutputBytes(type) + spend) * 3));
}/** * `<txid>_<vout>` to its parts. Strict: lower-case hex, canonical vout. * Split by hand: the engine's deploy scan refuses `.exec`. */
private btcParseOutpoint(key: string): {txid: string; vout: number}/**
* Serialise {version, locktime, inputs: [{txid, vout, sequence, witness?}],
* outputs: [{value, script}]}. Inputs have empty scriptSigs (Varnir spends
* P2WPKH only). With `withWitness`, every input must carry its witness.
*/ private btcSerialize(tx: any, withWitness: boolean): Uint8Array {
const parts: Uint8Array[] = [this.btcU32(tx.version)];
if (withWitness) {
parts.push(Uint8Array.from([0, 1]));
}
parts.push(this.btcVarint(tx.inputs.length));
for (const i of tx.inputs) {
parts.push(this.btcReverse(this.btcHexToBytes(i.txid)), this.btcU32(i.vout), Uint8Array.from([0]), this.btcU32(i.sequence));
}
parts.push(this.btcVarint(tx.outputs.length));
for (const o of tx.outputs) {
parts.push(this.btcU64(o.value), this.btcVarbytes(o.script));
}
if (withWitness) {
for (const i of tx.inputs) {
if (!Array.isArray(i.witness) || i.witness.length < 1) {
throw "Bitcoin: every input needs a witness";
}
parts.push(this.btcVarint(i.witness.length));
for (const item of i.witness) {
parts.push(this.btcVarbytes(item));
}
}
}
parts.push(this.btcU32(tx.locktime));
return this.btcConcat(parts);
}/** The txid: double-SHA256 of the non-witness serialisation, display order. */
private btcTxid(tx: any): string {
return this.btcBytesToHex(this.btcReverse(this.btcSha256d(this.btcSerialize(tx, false))));
}/** * Put the VM's witnesses (hex items, one stack per input) on the unsigned * transaction this contract built. Returns the signed hex and the txid, * which witnesses don't change. Each P2WPKH witness must be exactly * <signature> <33-byte compressed key>. */
private btcAssembleSigned(unsignedHex: string, witnesses: string[][]): {hex: string; txid: string}/** Parse an unsigned transaction this block serialised (empty scriptSigs, no witness). */
private btcParseUnsigned(hex: string): any {
const b = this.btcHexToBytes(hex);
let off = 0;
const take = (n: number): Uint8Array => {
if (off + n > b.length) {
throw "Bitcoin: truncated transaction";
}
const out = b.slice(off, off + n);
off += n;
return out;
};
const u32 = (): number => {
const x = take(4);
return (x[0] | (x[1] << 8) | (x[2] << 16) | (x[3] << 24)) >>> 0;
};
const varint = (): number => {
const first = take(1)[0];
if (first < 253) {
return first;
}
if (first === 253) {
const x = take(2);
const v = x[0] | (x[1] << 8);
if (v < 253) {
throw "Bitcoin: non-canonical varint";
}
return v;
}
throw "Bitcoin: varint too large";
};
const version = u32();
const nIn = varint();
const inputs: any[] = [];
for (let k = 0; k < nIn; k++) {
const txid = this.btcBytesToHex(this.btcReverse(take(32)));
const vout = u32();
if (varint() !== 0) {
throw "Bitcoin: unsigned inputs have empty scriptSigs";
}
inputs.push({txid, vout, sequence: u32()});
}
const nOut = varint();
const outputs: any[] = [];
for (let k = 0; k < nOut; k++) {
const v = take(8);
let value = 0n;
for (let i = 7; i >= 0; i--) {
value = (value << 8n) | BigInt(v[i]);
}
outputs.push({value, script: take(varint())});
}
const locktime = u32();
if (off !== b.length || nIn < 1 || nOut < 1) {
throw "Bitcoin: malformed unsigned transaction";
}
return {version, locktime, inputs, outputs};
}/** * True when one of the contract stream's authorities has `public` equal to * `identity` (voteMod passes the signing identity's stream id). */
private hasContractOwnership(contract: Activity, identity: string): boolean {
return contract.getAuthorities().some((v) => v.public === identity);
}/** * `mod` vote: `$o.contract` must be this contract's own stream and * `$i.owner` its owner or ALLOWEDMOD; only the owner may write * `evmNetworks` / `btcNetworks`, and both tables are validated whole. */
private async voteMod(): Promise<boolean> {
if (this.transactions.$o.contract) {
const contract = this.getActivityStreams(this.transactions.$o.contract);
if (this.transactions.$contract.substring(0, 64) !== contract.getId()) {
throw "Contract Not Matching";
}
const modId = this.getActivityStreams(this.transactions.$i.owner).getId();
if (
this.hasContractOwnership(contract, modId) ||
modId === ALLOWEDMOD // Maybe specific id's are allowed
) {
// The EVM chain table decides which chains are signed for: only the
// contract OWNER may add or alter it, never ALLOWEDMOD.
if (
this.transactions.$i.owner.evmNetworks !== undefined &&
this.transactions.$i.owner.evmNetworks !== null &&
!this.hasContractOwnership(contract, modId)
) {
throw "evmNetworks may only be written by the contract owner";
}
if (
this.transactions.$i.owner.btcNetworks !== undefined &&
this.transactions.$i.owner.btcNetworks !== null &&
!this.hasContractOwnership(contract, modId)
) {
throw "btcNetworks may only be written by the contract owner";
}
// The EVM chain table (evm-registry block): validated whole.
this.assertEvmNetworks(this.transactions.$i.owner.evmNetworks);
// The Bitcoin network table (btc block): validated whole.
this.assertBtcNetworks(this.transactions.$i.owner.btcNetworks);
return true;
}
throw "No Contract Authority";
} else {
throw "Missing Contract Output";
}
}/** * `mod` commit: stores the legacy minimum-deposit fields (never read), * `evmNetworks` and `btcNetworks` (each replaced whole, else kept), and * stamps `umid` and `updated`. */
private async commitMod(): Promise<boolean> {
const cd = this.getContractDataHelper();
const inputs = this.transactions.$i.owner;
// Credit-only fee model (ruling RV6): these minimum-deposit fields fed
// the deposit fee floor, which no longer exists (see the credit-full-
// amount comment in commit()). Still accepted here, unread anywhere
// else, purely so an owner `mod` transaction carrying them does not
// fail.
cd.minDepositTRX = inputs.minTRX ?? cd.minDepositTRX ?? null;
cd.minDepositETH = inputs.minETH ?? cd.minDepositETH ?? null;
cd.minDepositBSC = inputs.minBSC ?? cd.minDepositBSC ?? null;
cd.minDepositUSDT = inputs.minUSDT ?? cd.minDepositUSDT ?? null;
cd.minDepositBSCUSDT = inputs.minBSCUSDT ?? cd.minDepositBSCUSDT ?? null;
cd.minDepositSOL = inputs.minSOL ?? cd.minDepositSOL ?? null;
// The EVM chain table (evm-registry block). Replaced whole, never merged
// here: the write script merges with what is stored before it sends.
cd.evmNetworks = inputs.evmNetworks ?? cd.evmNetworks ?? null;
// The Bitcoin network table (btc block), replaced whole the same way.
cd.btcNetworks = inputs.btcNetworks ?? cd.btcNetworks ?? null;
cd.umid = this.umid;
cd.updated = this.cDate;
this.setContractData(cd);
return true;
}