From 6d5740c56dc0aecfb2b2ce526ba347af34d5a983 Mon Sep 17 00:00:00 2001 From: OmO Orchestrator Date: Fri, 20 Nov 2026 14:59:49 -0500 Subject: [PATCH] fix(ledger): reject wallet.transfer not signed by the from-account's own key --- src/lib/ledger.test.ts | 192 +++++++++++++++++++++----------- src/lib/ledger.ts | 56 +++++++--- src/lib/ledgerConflicts.test.ts | 34 ++++-- 3 files changed, 196 insertions(+), 86 deletions(-) diff --git a/src/lib/ledger.test.ts b/src/lib/ledger.test.ts index b37f6ee..71217dd 100644 --- a/src/lib/ledger.test.ts +++ b/src/lib/ledger.test.ts @@ -1,6 +1,13 @@ import { describe, expect, it } from "vitest"; import type { StoredEventLogEntry } from "./eventlog"; import { balanceOf, computeBalances } from "./ledger"; +import { toAccountId } from "../shell/accountId"; +import { + buildDemoWalletPayloads, + HOLLOW_DEMO_COMMONS_FUND_ACCOUNT, + HOLLOW_DEMO_WALLET_COMMONS_CONTRIBUTION, + HOLLOW_DEMO_WALLET_WELCOME_GRANT, +} from "../admin/seedEvents"; let nextId = 1; @@ -19,71 +26,133 @@ function entry( }; } +/** The ledger account id a signer with this single-byte pubkey owns - a + * `wallet.transfer` can only legitimately move funds `from` this id when + * it's signed with this exact `authorPubkey` (see `computeBalances`'s + * signer-binding check). Mirrors how `entry()`'s default `authorPubkey` + * (1) corresponds to `accountFor(1)`. */ +function accountFor(authorPubkey: number): string { + return toAccountId(new Uint8Array([authorPubkey])); +} + describe("ledger.computeBalances", () => { it("replays a sequence of valid transfers to a hand-calculated balance", () => { + const A = accountFor(1); + const B = accountFor(2); + const C = accountFor(3); const entries = [ - entry(0, { type: "wallet.issue", account: "A", amount: 100 }), - entry(1, { type: "wallet.transfer", from: "A", to: "B", amount: 40 }), - entry(2, { type: "wallet.transfer", from: "B", to: "C", amount: 15 }), + entry(0, { type: "wallet.issue", account: A, amount: 100 }), + // Signed by A's own key (1): A -> B is legitimate. + entry(1, { type: "wallet.transfer", from: A, to: B, amount: 40 }, 1), + // Signed by B's own key (2): B -> C is legitimate. + entry(2, { type: "wallet.transfer", from: B, to: C, amount: 15 }, 2), ]; const state = computeBalances(entries); // Hand-calculated: A issued 100, sends 40 -> A=60. B receives 40, sends // 15 -> B=25. C receives 15 -> C=15. - expect(balanceOf(state, "A")).toBe(60); - expect(balanceOf(state, "B")).toBe(25); - expect(balanceOf(state, "C")).toBe(15); + expect(balanceOf(state, A)).toBe(60); + expect(balanceOf(state, B)).toBe(25); + expect(balanceOf(state, C)).toBe(15); expect(state.rejected).toHaveLength(0); }); it("rejects a transfer that would breach a configured credit limit", () => { + const A = accountFor(1); + const B = accountFor(2); const entries = [ - entry(0, { type: "wallet.issue", account: "A", amount: 10 }), - entry(1, { type: "wallet.transfer", from: "A", to: "B", amount: 30 }), + entry(0, { type: "wallet.issue", account: A, amount: 10 }), + entry(1, { type: "wallet.transfer", from: A, to: B, amount: 30 }, 1), ]; const state = computeBalances(entries, { - creditLimits: { A: -20 }, + creditLimits: { [A]: -20 }, }); // 10 - 30 = -20, which is exactly the floor, so it is allowed. - expect(balanceOf(state, "A")).toBe(-20); - expect(balanceOf(state, "B")).toBe(30); + expect(balanceOf(state, A)).toBe(-20); + expect(balanceOf(state, B)).toBe(30); const breaching = computeBalances( - [...entries, entry(2, { type: "wallet.transfer", from: "A", to: "B", amount: 10 })], - { creditLimits: { A: -20 } }, + [...entries, entry(2, { type: "wallet.transfer", from: A, to: B, amount: 10 }, 1)], + { creditLimits: { [A]: -20 } }, ); // A further transfer of 10 would push A to -30, breaching the -20 floor. expect(breaching.rejected).toHaveLength(1); expect(breaching.rejected[0].reason).toBe("credit-limit-breach"); - expect(breaching.rejected[0].wouldBeBalance).toBe(-30); - expect(balanceOf(breaching, "A")).toBe(-20); - expect(balanceOf(breaching, "B")).toBe(30); + expect((breaching.rejected[0] as { wouldBeBalance: number }).wouldBeBalance).toBe(-30); + expect(balanceOf(breaching, A)).toBe(-20); + expect(balanceOf(breaching, B)).toBe(30); }); it("defaults the credit limit floor to zero for accounts without one configured", () => { + const A = accountFor(1); + const B = accountFor(2); const entries = [ - entry(0, { type: "wallet.issue", account: "A", amount: 10 }), - entry(1, { type: "wallet.transfer", from: "A", to: "B", amount: 15 }), + entry(0, { type: "wallet.issue", account: A, amount: 10 }), + entry(1, { type: "wallet.transfer", from: A, to: B, amount: 15 }, 1), ]; const state = computeBalances(entries); expect(state.rejected).toHaveLength(1); - expect(balanceOf(state, "A")).toBe(10); - expect(balanceOf(state, "B")).toBe(0); + expect(balanceOf(state, A)).toBe(10); + expect(balanceOf(state, B)).toBe(0); + }); + + it("rejects a wallet.transfer not signed by the from account's own key (a forged transfer)", () => { + // The core regression: a transfer naming `victim` as `from` but signed + // by `attacker`'s own key must never move the victim's funds, no matter + // what the payload itself claims. + const victim = accountFor(1); + const attacker = accountFor(2); + const entries = [ + entry(0, { type: "wallet.issue", account: victim, amount: 100 }), + // Signed by attacker's key (2), NOT victim's (1) - a forgery. + entry(1, { type: "wallet.transfer", from: victim, to: attacker, amount: 100 }, 2), + ]; + + const state = computeBalances(entries); + + expect(balanceOf(state, victim)).toBe(100); + expect(balanceOf(state, attacker)).toBe(0); + expect(state.rejected).toHaveLength(1); + expect(state.rejected[0].reason).toBe("unauthorized-signer"); + }); + + it("applies the Hollow demo fixture's wallet.issue + wallet.transfer when both are signed by the demo-loading identity", () => { + // Confirms the fix needs no demo-fixture exemption: buildDemoWalletPayloads + // sets `from` to the demo-loading identity's OWN account id, so signing + // both payloads with that same identity's key satisfies the new binding + // check exactly like any other legitimate transfer. + const agent = accountFor(3); + const payloads = buildDemoWalletPayloads(agent); + const entries = payloads.map((payload, index) => entry(index, payload, 3)); + + const state = computeBalances(entries); + + expect(balanceOf(state, agent)).toBe( + HOLLOW_DEMO_WALLET_WELCOME_GRANT - HOLLOW_DEMO_WALLET_COMMONS_CONTRIBUTION, + ); + expect(balanceOf(state, HOLLOW_DEMO_COMMONS_FUND_ACCOUNT)).toBe( + HOLLOW_DEMO_WALLET_COMMONS_CONTRIBUTION, + ); + expect(state.rejected).toHaveLength(0); }); it("resolves two same-Lamport-timestamp entries deterministically regardless of input order", () => { - // Two conflicting transfers from the same account, both stamped at the - // same lamportTs (e.g. two merged replicas racing), only one of which - // can be honoured given A's balance. - const low = entry(5, { type: "wallet.transfer", from: "A", to: "B", amount: 30 }, 1, 1); - const high = entry(5, { type: "wallet.transfer", from: "A", to: "C", amount: 30 }, 9, 9); - const issue = entry(0, { type: "wallet.issue", account: "A", amount: 30 }); + // Two conflicting transfers signed by the SAME account's own key (e.g. + // a client bug or an attempted double-spend by the legitimate owner), + // both stamped at the same lamportTs (two merged replicas racing), only + // one of which can be honoured given A's balance. + const A = accountFor(1); + const B = accountFor(2); + const C = accountFor(3); + const low = entry(5, { type: "wallet.transfer", from: A, to: B, amount: 30 }, 1, 1); + const high = entry(5, { type: "wallet.transfer", from: A, to: C, amount: 30 }, 1, 9); + const issue = entry(0, { type: "wallet.issue", account: A, amount: 30 }); const forward = computeBalances([issue, low, high]); const backward = computeBalances([issue, high, low]); @@ -98,10 +167,11 @@ describe("ledger.computeBalances", () => { shuffled.rejected.map((r) => r.entry.id), ); - // The tie-break is by authorPubkey bytes ascending, so `low` (pubkey=1) - // applies and `high` (pubkey=9) is the one left to reject. - expect(balanceOf(forward, "B")).toBe(30); - expect(balanceOf(forward, "C")).toBe(0); + // Both entries share the same authorPubkey (A's own key), so the tie-break + // falls through to signature bytes ascending: `low` (signature=1) applies + // and `high` (signature=9) is the one left to reject. + expect(balanceOf(forward, B)).toBe(30); + expect(balanceOf(forward, C)).toBe(0); expect(forward.rejected).toHaveLength(1); expect(forward.rejected[0].entry.id).toBe(high.id); }); @@ -144,12 +214,14 @@ describe("ledger.computeBalances", () => { }); it("ignores wallet.transfer events with a negative, NaN, or Infinity amount instead of silently applying them", () => { + const X = accountFor(1); + const Y = accountFor(2); const entries = [ - entry(0, { type: "wallet.issue", account: "X", amount: 100 }), - entry(1, { type: "wallet.transfer", from: "X", to: "Y", amount: -1000 }), - entry(2, { type: "wallet.transfer", from: "X", to: "Y", amount: Number.NaN }), - entry(3, { type: "wallet.transfer", from: "X", to: "Y", amount: Number.POSITIVE_INFINITY }), - entry(4, { type: "wallet.transfer", from: "X", to: "Y", amount: Number.NEGATIVE_INFINITY }), + entry(0, { type: "wallet.issue", account: X, amount: 100 }), + entry(1, { type: "wallet.transfer", from: X, to: Y, amount: -1000 }, 1), + entry(2, { type: "wallet.transfer", from: X, to: Y, amount: Number.NaN }, 1), + entry(3, { type: "wallet.transfer", from: X, to: Y, amount: Number.POSITIVE_INFINITY }, 1), + entry(4, { type: "wallet.transfer", from: X, to: Y, amount: Number.NEGATIVE_INFINITY }, 1), ]; const state = computeBalances(entries); @@ -158,55 +230,49 @@ describe("ledger.computeBalances", () => { // credit-limit-breach rejection - it must be ignored outright, never // applied (which would otherwise increase `from`'s balance for a // negative amount while driving `to` below its own limit unchecked). - expect(balanceOf(state, "X")).toBe(100); - expect(balanceOf(state, "Y")).toBe(0); + expect(balanceOf(state, X)).toBe(100); + expect(balanceOf(state, Y)).toBe(0); expect(state.rejected).toHaveLength(0); }); it("still applies a legitimate zero-amount transfer (0 is finite and non-negative)", () => { + const A = accountFor(1); + const B = accountFor(2); const entries = [ - entry(0, { type: "wallet.issue", account: "A", amount: 10 }), - entry(1, { type: "wallet.transfer", from: "A", to: "B", amount: 0 }), + entry(0, { type: "wallet.issue", account: A, amount: 10 }), + entry(1, { type: "wallet.transfer", from: A, to: B, amount: 0 }, 1), ]; const state = computeBalances(entries); - expect(balanceOf(state, "A")).toBe(10); - expect(balanceOf(state, "B")).toBe(0); + expect(balanceOf(state, A)).toBe(10); + expect(balanceOf(state, B)).toBe(0); expect(state.rejected).toHaveLength(0); }); it("treats an account named like an Object.prototype property identically to any other account name", () => { // "constructor" (and similar: toString, hasOwnProperty, valueOf, ...) is // an inherited property on a plain `{}`, not an own property - a naive - // `{}`-backed balances/credit-limit map would read back the inherited - // Object.prototype value instead of treating the account as unseen. + // `{}`-backed balances map would read back the inherited Object.prototype + // value instead of treating the account as unseen. Exercised here as an + // issue target and a transfer recipient (`balances[account]` / + // `balances[to]`) - a real `wallet.transfer` can never originate FROM an + // account literally named "constructor" post-fix, since `from` must equal + // `toAccountId(authorPubkey)`, always a lowercase-hex string; `creditLimitFor`'s + // own Object.prototype safety is separately guaranteed unconditionally by + // its `hasOwnProperty.call` check regardless of which account is looked up. + const sender = accountFor(7); const entries = [ entry(0, { type: "wallet.issue", account: "constructor", amount: 100 }), - entry(1, { type: "wallet.transfer", from: "constructor", to: "B", amount: 40 }), + entry(1, { type: "wallet.issue", account: sender, amount: 50 }), + entry(2, { type: "wallet.transfer", from: sender, to: "constructor", amount: 40 }, 7), ]; - const state = computeBalances(entries, { creditLimits: { constructor: -20 } }); + const state = computeBalances(entries); expect(typeof balanceOf(state, "constructor")).toBe("number"); - expect(balanceOf(state, "constructor")).toBe(60); - expect(balanceOf(state, "B")).toBe(40); + expect(balanceOf(state, "constructor")).toBe(140); + expect(balanceOf(state, sender)).toBe(10); expect(state.rejected).toHaveLength(0); - - // A further transfer that would breach the -20 floor configured for - // "constructor" must actually be rejected - not silently let through - // because the credit-limit lookup resolved to an inherited Function - // instead of the configured number. - const breaching = computeBalances( - [ - ...entries, - entry(2, { type: "wallet.transfer", from: "constructor", to: "B", amount: 90 }), - ], - { creditLimits: { constructor: -20 } }, - ); - - expect(breaching.rejected).toHaveLength(1); - expect(breaching.rejected[0].reason).toBe("credit-limit-breach"); - expect(balanceOf(breaching, "constructor")).toBe(60); }); }); diff --git a/src/lib/ledger.ts b/src/lib/ledger.ts index 595b512..8481cbf 100644 --- a/src/lib/ledger.ts +++ b/src/lib/ledger.ts @@ -1,4 +1,5 @@ import type { StoredEventLogEntry } from "./eventlog"; +import { toAccountId } from "../shell/accountId"; /** * Deterministic ledger: balances are never stored directly, they are always @@ -9,7 +10,10 @@ import type { StoredEventLogEntry } from "./eventlog"; * `{ type: "wallet.issue", account, amount }` - credits `account`. * `{ type: "wallet.transfer", from, to, amount }` - double-entry move * from `from` to `to`, rejected if it would push `from` below its - * configured credit limit. + * configured credit limit, and rejected outright if the entry's own + * signer does not own `from` (see `toAccountId`/`RejectedTransfer`'s + * `"unauthorized-signer"` reason) - a resident can only ever sign a + * transfer moving funds out of their OWN account. * Any entry whose payload doesn't match one of these shapes is ignored by * the ledger (it may still matter to other reducers folding over the same * log). @@ -54,15 +58,25 @@ export function isTransferPayload(payload: unknown): payload is TransferPayload } /** Why a `wallet.transfer` event was rejected rather than applied. */ -export interface RejectedTransfer { - entry: StoredEventLogEntry; - payload: TransferPayload; - reason: "credit-limit-breach"; - /** The balance `from` would have ended up at, had the transfer applied. */ - wouldBeBalance: number; - /** The configured floor that balance would have breached. */ - creditLimit: number; -} +export type RejectedTransfer = + | { + entry: StoredEventLogEntry; + payload: TransferPayload; + reason: "credit-limit-breach"; + /** The balance `from` would have ended up at, had the transfer applied. */ + wouldBeBalance: number; + /** The configured floor that balance would have breached. */ + creditLimit: number; + } + | { + entry: StoredEventLogEntry; + payload: TransferPayload; + /** The entry's signer does not own the `from` account - a forged + * transfer naming someone else's account as the source, exactly the + * same signer-binding check `governanceEvents.ts`'s `extractQvBallots` + * applies to ballots (`toAccountId(entry.authorPubkey) === payload.voterId`). */ + reason: "unauthorized-signer"; + }; export interface LedgerOptions { /** Per-account credit-limit floor: a transfer is rejected if it would @@ -131,9 +145,11 @@ function creditLimitFor( * deterministic replay order (see `sortForReplay`) regardless of the order * they're passed in. * - * A `wallet.transfer` that would push its `from` account strictly below its - * configured credit limit is rejected (not applied) and recorded in - * `rejected`; every other recognised event is applied unconditionally. + * A `wallet.transfer` is rejected (not applied, recorded in `rejected`) if + * either: the entry's signer does not own the `from` account (forged - + * `"unauthorized-signer"`), or applying it would push `from` strictly below + * its configured credit limit (`"credit-limit-breach"`). Every other + * recognised event is applied unconditionally. */ export function computeBalances( entries: readonly StoredEventLogEntry[], @@ -162,6 +178,20 @@ export function computeBalances( if (isTransferPayload(entry.payload)) { const { from, to, amount } = entry.payload; + + // Signer binding: a `wallet.transfer` only moves funds OUT of `from` + // when the entry's own signer owns that account - otherwise anyone + // could sign a transfer naming someone else's account as the source + // and drain it. Mirrors `extractQvBallots`'s voter-binding check. + if (toAccountId(entry.authorPubkey) !== from) { + rejected.push({ + entry, + payload: entry.payload, + reason: "unauthorized-signer", + }); + continue; + } + const wouldBeBalance = getBalance(from) - amount; const limit = creditLimitFor(from, resolved); diff --git a/src/lib/ledgerConflicts.test.ts b/src/lib/ledgerConflicts.test.ts index 6f7288c..d02e3e7 100644 --- a/src/lib/ledgerConflicts.test.ts +++ b/src/lib/ledgerConflicts.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import type { StoredEventLogEntry } from "./eventlog"; import { balanceOf } from "./ledger"; import { mergeReplicas, UnresolvedLamportTieError } from "./ledgerConflicts"; +import { toAccountId } from "../shell/accountId"; let nextId = 1; @@ -20,18 +21,27 @@ function entry( }; } +/** See `ledger.test.ts`'s identical helper: the account id a signer with + * this single-byte pubkey owns, so a `wallet.transfer` `from` this id + * signed with the same `authorPubkey` passes `computeBalances`'s + * signer-binding check. */ +function accountFor(authorPubkey: number): string { + return toAccountId(new Uint8Array([authorPubkey])); +} + describe("ledgerConflicts.mergeReplicas", () => { it("applies the earlier of two conflicting same-signer spends and flags the later one for refund", () => { - const issue = entry(0, { type: "wallet.issue", account: "A", amount: 100 }); + const A = accountFor(7); + const issue = entry(0, { type: "wallet.issue", account: A, amount: 100 }); const earlySpend = entry( 5, - { type: "wallet.transfer", from: "A", to: "B", amount: 100 }, + { type: "wallet.transfer", from: A, to: "B", amount: 100 }, 7, 5, ); const lateSpend = entry( 7, - { type: "wallet.transfer", from: "A", to: "C", amount: 100 }, + { type: "wallet.transfer", from: A, to: "C", amount: 100 }, 7, 7, ); @@ -52,8 +62,9 @@ describe("ledgerConflicts.mergeReplicas", () => { }); it("deduplicates an entry that both replicas already share", () => { - const issue = entry(0, { type: "wallet.issue", account: "A", amount: 10 }); - const spend = entry(1, { type: "wallet.transfer", from: "A", to: "B", amount: 5 }); + const A = accountFor(1); + const issue = entry(0, { type: "wallet.issue", account: A, amount: 10 }); + const spend = entry(1, { type: "wallet.transfer", from: A, to: "B", amount: 5 }); const result = mergeReplicas([issue, spend], [issue, spend]); @@ -63,16 +74,17 @@ describe("ledgerConflicts.mergeReplicas", () => { }); it("throws an unresolved-tie error instead of silently picking a winner when conflicting same-signer spends share an identical lamportTs", () => { - const issue = entry(0, { type: "wallet.issue", account: "A", amount: 100 }); + const A = accountFor(7); + const issue = entry(0, { type: "wallet.issue", account: A, amount: 100 }); const tiedA = entry( 5, - { type: "wallet.transfer", from: "A", to: "B", amount: 100 }, + { type: "wallet.transfer", from: A, to: "B", amount: 100 }, 7, 5, ); const tiedB = entry( 5, - { type: "wallet.transfer", from: "A", to: "C", amount: 100 }, + { type: "wallet.transfer", from: A, to: "C", amount: 100 }, 7, 55, ); @@ -83,12 +95,14 @@ describe("ledgerConflicts.mergeReplicas", () => { }); it("does not flag a lone credit-limit breach that has no conflicting same-signer sibling", () => { - const issue = entry(0, { type: "wallet.issue", account: "A", amount: 10 }); - const overspend = entry(1, { type: "wallet.transfer", from: "A", to: "B", amount: 50 }); + const A = accountFor(1); + const issue = entry(0, { type: "wallet.issue", account: A, amount: 10 }); + const overspend = entry(1, { type: "wallet.transfer", from: A, to: "B", amount: 50 }, 1); const result = mergeReplicas([issue, overspend], []); expect(result.ledger.rejected).toHaveLength(1); + expect(result.ledger.rejected[0].reason).toBe("credit-limit-breach"); expect(result.flagged).toHaveLength(0); }); });