Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(knock): read an escrowed knock off the chain before delivering it
nirholasdb6d6a18cbf6
diff --git a/api/_lib/knock/escrow.js b/api/_lib/knock/escrow.jsnew file mode 100644index 000000000..8de3c1b47--- /dev/null+++ b/api/_lib/knock/escrow.js@@ -0,0 +1,275 @@+// The escrowed knock lane: reading and verifying the on-chain half.+//+// The x402 lane (api/x402/knock.js) settles the sender's USDC straight to the+// recipient's own wallet the moment the payment clears, and the door row says+// so: nothing here holds funds. That is the right shape between people who+// already trust each other, and the wrong one for a stranger, because the+// recipient can bank every knock and answer none.+//+// The escrowed lane closes that. The sender signs a `knock` instruction on the+// knock_escrow program (contracts/knock-escrow), which parks the payment in a+// vault owned by the knock's own PDA. The recipient is paid only by answering+// inside the reply window; if they refuse, or the window lapses, every unit+// goes back to the sender and anyone at all can crank that refund.+//+// This module is the READ side, and deliberately nothing else. three.ws never+// holds the money, never signs for either party, and cannot release an escrow:+// it verifies against the chain that a knock was really made, for the right+// amount, carrying the hash of the exact message being delivered, and still+// live. Everything it returns is derived from account bytes the RPC gave us, so+// a caller lying about what they paid fails here rather than at the inbox.+//+// The account layouts below are the program's borsh encoding. They are asserted+// against the compiled program's own PDAs in tests/knock-escrow-pda.test.js,+// which shares fixtures with the Rust suite, so a layout or seed change on+// either side fails a test rather than silently reading the wrong bytes.++import { createHash } from 'node:crypto';+import { PublicKey } from '@solana/web3.js';++/** knock_escrow's `declare_id!`. */+export const KNOCK_ESCROW_PROGRAM_ID = 'uVX46U6sGUs6PD3339ZXbTpMyhZwkQhBLPxnvRX9ps7';++/** PDA seeds, byte-identical to the constants in the program. */+const CONFIG_SEED = Buffer.from('config');+const DOOR_SEED = Buffer.from('door');+const KNOCK_SEED = Buffer.from('knock');+const VAULT_SEED = Buffer.from('vault');++/** `KnockRecord.state`, matching the program's `KnockState`. */+export const KNOCK_STATE = Object.freeze({+ PENDING: 0,+ ANSWERED: 1,+ REFUNDED: 2,+ REFUSED: 3,+});++/** Human-readable names for the states, for API responses and the inbox. */+export const KNOCK_STATE_NAME = Object.freeze({+ 0: 'pending',+ 1: 'answered',+ 2: 'refunded',+ 3: 'refused',+});++/** SHA-256, the digest the program hashes door ids and message bodies with. */+export function sha256(input) {+ return createHash('sha256').update(input).digest();+}++/**+ * A door's 32-byte on-chain id: the SHA-256 of the owner's handle.+ *+ * The handle is normalized to lower case first because the off-chain door is+ * keyed case-insensitively; deriving from the raw string would give `/knock/Ada`+ * and `/knock/ada` two different doors on-chain for one door in the product.+ */+export function doorId(handle) {+ return sha256(String(handle).trim().toLowerCase());+}++/**+ * Anchor's 8-byte account discriminator: `sha256("account:<Name>")[..8]`.+ *+ * Checked on every decode. Without it a caller could hand us any account of the+ * right size and we would read its bytes as a knock.+ */+function accountDiscriminator(name) {+ return sha256(`account:${name}`).subarray(0, 8);+}++const programKey = () => new PublicKey(KNOCK_ESCROW_PROGRAM_ID);++/** The singleton config PDA. */+export function configPda() {+ return PublicKey.findProgramAddressSync([CONFIG_SEED], programKey())[0];+}++/** A door PDA, from the owner's wallet and the door id. */+export function doorPda(ownerWallet, id) {+ return PublicKey.findProgramAddressSync(+ [DOOR_SEED, new PublicKey(ownerWallet).toBuffer(), Buffer.from(id)],+ programKey(),+ )[0];+}++/** A single knock's PDA. `nonce` is what lets one sender knock twice. */+export function knockPda(door, sender, nonce) {+ const n = Buffer.alloc(8);+ n.writeBigUInt64LE(BigInt(nonce));+ return PublicKey.findProgramAddressSync(+ [KNOCK_SEED, new PublicKey(door).toBuffer(), new PublicKey(sender).toBuffer(), n],+ programKey(),+ )[0];+}++/** The vault token account holding one knock's escrowed payment. */+export function vaultPda(knock) {+ return PublicKey.findProgramAddressSync(+ [VAULT_SEED, new PublicKey(knock).toBuffer()],+ programKey(),+ )[0];+}++/** Read a pubkey out of an account buffer. */+const pubkeyAt = (buf, offset) => new PublicKey(buf.subarray(offset, offset + 32)).toBase58();++/**+ * Decode a `Door` account.+ *+ * Offsets are the program's borsh layout after the 8-byte discriminator:+ * owner 32 | mint 32 | door_id 32 | price 8 | reply_window 8 | open 1 |+ * knocks 8 | answered 8 | refunded 8 | earned 8 | bump 1.+ */+export function decodeDoor(data) {+ const buf = Buffer.from(data);+ if (buf.length < 154) throw new Error('door account is too small to decode');+ if (!buf.subarray(0, 8).equals(accountDiscriminator('Door'))) {+ throw new Error('account is not a knock_escrow Door');+ }+ return {+ owner: pubkeyAt(buf, 8),+ mint: pubkeyAt(buf, 40),+ doorId: Buffer.from(buf.subarray(72, 104)).toString('hex'),+ price: buf.readBigUInt64LE(104),+ replyWindow: Number(buf.readBigInt64LE(112)),+ open: buf[120] === 1,+ knocks: buf.readBigUInt64LE(121),+ answered: buf.readBigUInt64LE(129),+ refunded: buf.readBigUInt64LE(137),+ earned: buf.readBigUInt64LE(145),+ };+}++/**+ * Decode a `KnockRecord` account.+ *+ * door 32 | sender 32 | mint 32 | amount 8 | fee_bps 2 | nonce 8 |+ * message_hash 32 | reply_hash 32 | created_at 8 | expires_at 8 | state 1 |+ * bump 1 | vault_bump 1.+ */+export function decodeKnock(data) {+ const buf = Buffer.from(data);+ if (buf.length < 205) throw new Error('knock account is too small to decode');+ if (!buf.subarray(0, 8).equals(accountDiscriminator('KnockRecord'))) {+ throw new Error('account is not a knock_escrow KnockRecord');+ }+ const state = buf[202];+ return {+ door: pubkeyAt(buf, 8),+ sender: pubkeyAt(buf, 40),+ mint: pubkeyAt(buf, 72),+ amount: buf.readBigUInt64LE(104),+ feeBps: buf.readUInt16LE(112),+ nonce: buf.readBigUInt64LE(114),+ messageHash: Buffer.from(buf.subarray(122, 154)).toString('hex'),+ replyHash: Buffer.from(buf.subarray(154, 186)).toString('hex'),+ createdAt: Number(buf.readBigInt64LE(186)),+ expiresAt: Number(buf.readBigInt64LE(194)),+ state,+ stateName: KNOCK_STATE_NAME[state] || 'unknown',+ };+}++/**+ * Why a knock could not be accepted, in the sender's words rather than the+ * chain's. Each of these is a real thing a caller can do wrong, and each needs+ * to say what to do instead, because the money is already committed on-chain by+ * the time we are looking.+ */+export class EscrowRejected extends Error {+ constructor(code, message, detail = {}) {+ super(message);+ this.name = 'EscrowRejected';+ this.code = code;+ this.detail = detail;+ }+}++/**+ * Verify that an escrowed knock really exists on-chain and matches the message+ * about to be delivered.+ *+ * `connection` is a web3.js Connection (callers get one through+ * `rpcFallbackFromEnv().withFallback`, so this inherits the provider failover+ * rather than pinning one RPC).+ *+ * Returns the decoded knock plus the derived addresses. Throws `EscrowRejected`+ * when the chain disagrees with the request in any way that matters:+ *+ * - the knock account does not exist (nothing was paid);+ * - it is not for this door (paid at somebody else's door);+ * - the message hash differs (paid for a different message than the one being+ * delivered, which is the substitution this hash exists to prevent);+ * - it already settled (replay of a knock that was answered or refunded);+ * - it is already past its window (the sender is owed a refund, so accepting+ * the message would take attention the recipient can no longer be paid for);+ * - it is under the door's asking price.+ */+export async function verifyEscrowedKnock(+ connection,+ { ownerWallet, handle, sender, nonce, message, minPriceAtomics = 0n, now = null },+) {+ const id = doorId(handle);+ const door = doorPda(ownerWallet, id);+ const knock = knockPda(door, sender, nonce);++ const info = await connection.getAccountInfo(new PublicKey(knock));+ if (!info) {+ throw new EscrowRejected(+ 'knock_not_found',+ 'no escrowed knock exists on-chain for that door, sender and nonce',+ { knock: knock.toBase58(), door: door.toBase58() },+ );+ }+ if (info.owner?.toBase58?.() !== KNOCK_ESCROW_PROGRAM_ID) {+ throw new EscrowRejected('wrong_program', 'that account is not owned by the knock escrow program', {+ knock: knock.toBase58(),+ });+ }++ const record = decodeKnock(info.data);+ if (record.door !== door.toBase58()) {+ throw new EscrowRejected('wrong_door', 'that knock was paid at a different door', {+ expected: door.toBase58(),+ actual: record.door,+ });+ }+ if (record.state !== KNOCK_STATE.PENDING) {+ throw new EscrowRejected('already_settled', `that knock was already ${record.stateName}`, {+ state: record.stateName,+ });+ }++ const expected = sha256(message).toString('hex');+ if (record.messageHash !== expected) {+ throw new EscrowRejected(+ 'message_mismatch',+ 'the escrowed knock was paid for a different message than the one being delivered',+ { expected, actual: record.messageHash },+ );+ }++ const nowSeconds = now ?? Math.floor(Date.now() / 1000);+ if (nowSeconds > record.expiresAt) {+ throw new EscrowRejected(+ 'window_closed',+ 'that knock has expired and the sender is owed a refund; knock again to reach this door',+ { expires_at: record.expiresAt },+ );+ }+ if (minPriceAtomics && record.amount < BigInt(minPriceAtomics)) {+ throw new EscrowRejected('underpaid', 'the escrowed amount is below this door\'s price', {+ escrowed: String(record.amount),+ price: String(minPriceAtomics),+ });+ }++ return {+ ...record,+ knock: knock.toBase58(),+ doorPda: door.toBase58(),+ vault: vaultPda(knock).toBase58(),+ expiresInSeconds: record.expiresAt - nowSeconds,+ };+}diff --git a/contracts/program-tests/tests/knock_escrow_pda.rs b/contracts/program-tests/tests/knock_escrow_pda.rsnew file mode 100644index 000000000..8d650df1c--- /dev/null+++ b/contracts/program-tests/tests/knock_escrow_pda.rs@@ -0,0 +1,68 @@+//! Address conformance between the `knock_escrow` program and its JS client.+//!+//! The client in `api/_lib/knock/escrow.js` re-derives these PDAs to read a+//! knock back off the chain. If either side changes a seed, an account name, or+//! the program id, it reads the wrong account: the API would report "no+//! escrowed knock exists" for money that was really paid, or decode a stranger's+//! account as a knock. Nothing about that failure is visible to a test that only+//! talks to its own side, so both sides pin the SAME fixtures, and this file is+//! the authoritative one because it derives from the program's real constants.+//!+//! The JS half is `tests/knock-escrow-pda.test.js`. Change a seed and both fail.++use program_tests::*;+use solana_pubkey::Pubkey;+use std::str::FromStr;++const PROGRAM: &str = "uVX46U6sGUs6PD3339ZXbTpMyhZwkQhBLPxnvRX9ps7";+/// Fixed, secret-free inputs. Any valid pubkey works; these are well-known ones+/// so the fixture can be regenerated by anybody without a keypair.+const OWNER: &str = "11111111111111111111111111111111";+const SENDER: &str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";+const HANDLE: &[u8] = b"nirholas";+const NONCE: u64 = 7;++const EXPECT_DOOR_ID: &str = "b3d92abfa95658f0d35e6b20752e8ca9ba4fad9e9bbc62352c999c75853fb53d";+const EXPECT_CONFIG: &str = "7jAKSyTgRC8aGAjdYkMjQMPv7uh3uJX869GRXkBTUPkZ";+const EXPECT_DOOR: &str = "DMDKj3mSoM5rjsftGAhSbLbrAWMwmFxEkHDLsx997vk8";+const EXPECT_KNOCK: &str = "8WvZ64SL6JNss232BC78aapB2M6MjE95f9LtWfYYRn5t";+const EXPECT_VAULT: &str = "8LLgeTjcL4ZiU1MwoFWR4DkTkYnXruBsorMG7MKWbSwv";+const EXPECT_DISC_DOOR: &str = "541e65686ab2068c";+const EXPECT_DISC_KNOCK: &str = "f9c621b06c558191";++fn hex(bytes: &[u8]) -> String {+ bytes.iter().map(|b| format!("{b:02x}")).collect()+}++#[test]+fn pda_derivation_is_stable_and_matches_the_js_client() {+ let program = Pubkey::from_str(PROGRAM).unwrap();+ let owner = Pubkey::from_str(OWNER).unwrap();+ let sender = Pubkey::from_str(SENDER).unwrap();++ let door_id = sha256(HANDLE);+ assert_eq!(hex(&door_id), EXPECT_DOOR_ID, "door id is sha256 of the handle");++ let config = Pubkey::find_program_address(&[b"config"], &program).0;+ let door =+ Pubkey::find_program_address(&[b"door", owner.as_ref(), door_id.as_ref()], &program).0;+ let knock = Pubkey::find_program_address(+ &[b"knock", door.as_ref(), sender.as_ref(), &NONCE.to_le_bytes()],+ &program,+ )+ .0;+ let vault = Pubkey::find_program_address(&[b"vault", knock.as_ref()], &program).0;++ assert_eq!(config.to_string(), EXPECT_CONFIG);+ assert_eq!(door.to_string(), EXPECT_DOOR);+ assert_eq!(knock.to_string(), EXPECT_KNOCK);+ assert_eq!(vault.to_string(), EXPECT_VAULT);+}++#[test]+fn account_discriminators_match_the_js_decoder() {+ // Anchor's account discriminator is sha256("account:<Name>")[..8]. The JS+ // decoder checks these before it reads a single field.+ assert_eq!(hex(&sha256(b"account:Door")[..8]), EXPECT_DISC_DOOR);+ assert_eq!(hex(&sha256(b"account:KnockRecord")[..8]), EXPECT_DISC_KNOCK);+}diff --git a/tests/knock-escrow-pda.test.js b/tests/knock-escrow-pda.test.jsnew file mode 100644index 000000000..2e675e838--- /dev/null+++ b/tests/knock-escrow-pda.test.js@@ -0,0 +1,213 @@+// Cross-language conformance for the knock escrow client.+//+// The JS client derives the same PDAs the Rust program derives, or it reads the+// wrong account and every downstream check is meaningless: a wrong door seed+// makes `verifyEscrowedKnock` report "no escrowed knock exists" for a knock that+// was really paid, and a wrong discriminator would let it decode somebody else's+// account as a knock. Neither failure is visible in a unit test that only talks+// to itself, so the fixtures below are the values the PROGRAM produced, printed+// from contracts/program-tests against fixed inputs and pasted here.+//+// If a seed, an account name, or the program id changes on either side, this+// test fails. Regenerate the fixtures from the Rust side, never by running the+// JS and copying what it happens to produce.++import { describe, it, expect } from 'vitest';+import { PublicKey } from '@solana/web3.js';+import {+ KNOCK_ESCROW_PROGRAM_ID,+ KNOCK_STATE,+ configPda,+ decodeDoor,+ decodeKnock,+ doorId,+ doorPda,+ knockPda,+ sha256,+ vaultPda,+ verifyEscrowedKnock,+ EscrowRejected,+} from '../api/_lib/knock/escrow.js';++// Fixed inputs, identical to contracts/program-tests/tests/knock_escrow_pda.rs.+const OWNER = '11111111111111111111111111111111';+const SENDER = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';+const HANDLE = 'nirholas';+const NONCE = 7;++// Produced by the Rust program's own find_program_address calls.+const EXPECT = {+ doorIdHex: 'b3d92abfa95658f0d35e6b20752e8ca9ba4fad9e9bbc62352c999c75853fb53d',+ config: '7jAKSyTgRC8aGAjdYkMjQMPv7uh3uJX869GRXkBTUPkZ',+ door: 'DMDKj3mSoM5rjsftGAhSbLbrAWMwmFxEkHDLsx997vk8',+ knock: '8WvZ64SL6JNss232BC78aapB2M6MjE95f9LtWfYYRn5t',+ vault: '8LLgeTjcL4ZiU1MwoFWR4DkTkYnXruBsorMG7MKWbSwv',+ discDoor: '541e65686ab2068c',+ discKnock: 'f9c621b06c558191',+};++describe('knock escrow PDA derivation matches the program', () => {+ it('derives the door id the program hashes', () => {+ expect(doorId(HANDLE).toString('hex')).toBe(EXPECT.doorIdHex);+ });++ it('normalizes the handle so one door is not two doors on-chain', () => {+ expect(doorId('NirHolas').toString('hex')).toBe(EXPECT.doorIdHex);+ expect(doorId(' nirholas ').toString('hex')).toBe(EXPECT.doorIdHex);+ });++ it('derives the config, door, knock and vault addresses', () => {+ const door = doorPda(OWNER, doorId(HANDLE));+ const knock = knockPda(door, SENDER, NONCE);+ expect(configPda().toBase58()).toBe(EXPECT.config);+ expect(door.toBase58()).toBe(EXPECT.door);+ expect(knock.toBase58()).toBe(EXPECT.knock);+ expect(vaultPda(knock).toBase58()).toBe(EXPECT.vault);+ });++ it('separates knocks by nonce, so one sender can knock twice', () => {+ const door = doorPda(OWNER, doorId(HANDLE));+ expect(knockPda(door, SENDER, 8).toBase58()).not.toBe(EXPECT.knock);+ });+});++// ── account decoding ────────────────────────────────────────────────────────++/** Build a byte-accurate `KnockRecord` the way the program lays one out. */+function encodeKnock({+ door = EXPECT.door,+ sender = SENDER,+ mint = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ amount = 50_000n,+ feeBps = 250,+ nonce = NONCE,+ messageHash = Buffer.alloc(32),+ replyHash = Buffer.alloc(32),+ createdAt = 1_767_225_600,+ expiresAt = 1_767_312_000,+ state = KNOCK_STATE.PENDING,+} = {}) {+ const buf = Buffer.alloc(205);+ Buffer.from(EXPECT.discKnock, 'hex').copy(buf, 0);+ new PublicKey(door).toBuffer().copy(buf, 8);+ new PublicKey(sender).toBuffer().copy(buf, 40);+ new PublicKey(mint).toBuffer().copy(buf, 72);+ buf.writeBigUInt64LE(amount, 104);+ buf.writeUInt16LE(feeBps, 112);+ buf.writeBigUInt64LE(BigInt(nonce), 114);+ Buffer.from(messageHash).copy(buf, 122);+ Buffer.from(replyHash).copy(buf, 154);+ buf.writeBigInt64LE(BigInt(createdAt), 186);+ buf.writeBigInt64LE(BigInt(expiresAt), 194);+ buf[202] = state;+ return buf;+}++describe('account decoding', () => {+ it('reads back every field of a knock record', () => {+ const messageHash = sha256('hello there');+ const got = decodeKnock(encodeKnock({ messageHash }));+ expect(got.sender).toBe(SENDER);+ expect(got.amount).toBe(50_000n);+ expect(got.feeBps).toBe(250);+ expect(got.nonce).toBe(7n);+ expect(got.messageHash).toBe(messageHash.toString('hex'));+ expect(got.expiresAt).toBe(1_767_312_000);+ expect(got.stateName).toBe('pending');+ });++ it('refuses an account that is not a knock record', () => {+ const wrong = encodeKnock();+ wrong.writeUInt8(0, 0); // corrupt the discriminator+ expect(() => decodeKnock(wrong)).toThrow(/not a knock_escrow KnockRecord/);+ });++ it('refuses a truncated account rather than reading past its end', () => {+ expect(() => decodeKnock(encodeKnock().subarray(0, 100))).toThrow(/too small/);+ expect(() => decodeDoor(Buffer.alloc(20))).toThrow(/too small/);+ });+});++// ── verification ────────────────────────────────────────────────────────────++/** A stub connection returning one account, standing in for the RPC. */+function connectionServing(data) {+ return {+ async getAccountInfo() {+ if (!data) return null;+ return { data, owner: { toBase58: () => KNOCK_ESCROW_PROGRAM_ID } };+ },+ };+}++const NOW = 1_767_225_600;+const base = { ownerWallet: OWNER, handle: HANDLE, sender: SENDER, nonce: NONCE, now: NOW };++describe('verifyEscrowedKnock', () => {+ const message = 'two questions about the facilitator';++ it('accepts a live knock whose hash matches the message', async () => {+ const conn = connectionServing(encodeKnock({ messageHash: sha256(message) }));+ const got = await verifyEscrowedKnock(conn, { ...base, message, minPriceAtomics: 50_000n });+ expect(got.knock).toBe(EXPECT.knock);+ expect(got.vault).toBe(EXPECT.vault);+ expect(got.stateName).toBe('pending');+ expect(got.expiresInSeconds).toBe(86_400);+ });++ it('rejects a knock that was never made', async () => {+ await expect(+ verifyEscrowedKnock(connectionServing(null), { ...base, message }),+ ).rejects.toMatchObject({ code: 'knock_not_found' });+ });++ it('rejects a message the sender did not pay for', async () => {+ const conn = connectionServing(encodeKnock({ messageHash: sha256('a different message') }));+ await expect(verifyEscrowedKnock(conn, { ...base, message })).rejects.toMatchObject({+ code: 'message_mismatch',+ });+ });++ it('rejects a knock that already settled, so an answer cannot be replayed', async () => {+ for (const state of [KNOCK_STATE.ANSWERED, KNOCK_STATE.REFUNDED, KNOCK_STATE.REFUSED]) {+ const conn = connectionServing(encodeKnock({ messageHash: sha256(message), state }));+ await expect(verifyEscrowedKnock(conn, { ...base, message })).rejects.toMatchObject({+ code: 'already_settled',+ });+ }+ });++ it('rejects a knock past its window, because that money is owed back', async () => {+ const conn = connectionServing(encodeKnock({ messageHash: sha256(message) }));+ await expect(+ verifyEscrowedKnock(conn, { ...base, message, now: 1_767_312_001 }),+ ).rejects.toMatchObject({ code: 'window_closed' });+ });++ it('rejects an escrow below the door price', async () => {+ const conn = connectionServing(encodeKnock({ messageHash: sha256(message), amount: 10_000n }));+ await expect(+ verifyEscrowedKnock(conn, { ...base, message, minPriceAtomics: 50_000n }),+ ).rejects.toMatchObject({ code: 'underpaid' });+ });++ it('rejects an account owned by some other program', async () => {+ const conn = {+ async getAccountInfo() {+ return {+ data: encodeKnock({ messageHash: sha256(message) }),+ owner: { toBase58: () => '11111111111111111111111111111111' },+ };+ },+ };+ await expect(verifyEscrowedKnock(conn, { ...base, message })).rejects.toMatchObject({+ code: 'wrong_program',+ });+ });++ it('reports rejections as EscrowRejected with a code a caller can branch on', async () => {+ const err = await verifyEscrowedKnock(connectionServing(null), { ...base, message }).catch((e) => e);+ expect(err).toBeInstanceOf(EscrowRejected);+ expect(err.detail.knock).toBe(EXPECT.knock);+ });+});