From 9db91b1b9c2b8f819ded8aade743b6622b3ef4a6 Mon Sep 17 00:00:00 2001 From: Dan Connolly Date: Wed, 18 Nov 2026 06:40:09 -0600 Subject: [PATCH] feat: Alice buys a widget from Bob, from the JS client shop.mjs runs the ERTP story step by step as the principal of a key file; connect.js holds the session setup it shares with counter.mjs. The client stages any number of string, integer, and reference arguments, and reports why an answer broke. A new start from a caller closes that caller's old session, so a client can come back with the same key. Generated-by: Claude Code (claude-opus-5-5) --- README.md | 35 ++++++++++++++-- client/connect.js | 58 ++++++++++++++++++++++++++ client/counter.mjs | 47 +-------------------- client/peer.js | 24 ++++++----- client/shop.mjs | 102 +++++++++++++++++++++++++++++++++++++++++++++ src/client.zig | 86 +++++++++++++++++++++++++++----------- src/node.zig | 11 +++-- src/pair_test.zig | 10 +++++ 8 files changed, 287 insertions(+), 86 deletions(-) create mode 100644 client/connect.js create mode 100644 client/shop.mjs diff --git a/README.md b/README.md index bcf11c9..d8776dd 100644 --- a/README.md +++ b/README.md @@ -40,12 +40,40 @@ value 2 With another key file, `use c1` breaks: that home is someone else's. `icp network stop` stops the local network. `zig build test` runs the same story in memory. +## Alice buys a widget from Bob + +[ertp.zig](src/ertp.zig) is a small [ERTP](https://docs.agoric.com/guides/ertp/): mints, issuers, purses, payments, and a shop that sells one unit of stock for an exact price. A sale moves the payment, the proceeds, and the stock in one Loam transaction. With the network and canister from above: + +```sh +shop() { node client/shop.mjs http://127.0.0.1:4960 $ID "$@"; } +shop alice.key mint # moola: 10 into Alice's wallet; issuer on the board +shop bob.key open # widgets: 1 in stock; shop on the board at 3 moola +shop alice.key buy +shop alice.key buy # sold out: the payment goes back to the wallet +icp canister install counter --mode upgrade -y +shop alice.key balances +shop bob.key balances +``` + +``` +bought 1 widget into closet +refunded 3 moola to wallet +Error: answer 5 broke: SoldOut +Canister counter installed successfully +wallet 7 +closet 1 +proceeds 3 +``` + +(Update-call lines omitted. Alice's `balances` also reports `proceeds none`, and Bob's reports no wallet or closet: each home holds only its own.) + ## Homes, not swiss numbers Nodes on a canister's subnet can read its state, so a canister can't keep a swiss number secret. Authority here starts instead with the caller principal, whose signature the Internet Computer checks: - `fetch("home")` answers the caller's own home, a durable store of named objects: `init(name, object)` and `get(name)`. It's made the first time the caller asks. -- `fetch("makeCounter")` answers the one public maker; `make()` answers a fresh counter at zero. +- `fetch("board")` answers a home every caller shares, where Alice and Bob post issuers and the shop. +- `fetch("makeCounter")`, `fetch("makeIssuerKit")`, and `fetch("makeShop")` answer public makers; each one's `make(...)` answers what it makes. - The anonymous principal is refused, since everyone who uses it would share one home. Homes, counters, and the canister's CapTP identity live in a [Loam](https://github.com/glowcap-org/glowcap) store whose engine ([stable_log.zig](src/stable_log.zig)) appends each committed transaction to stable memory, the part of a canister's state that survives an upgrade; `post_upgrade` replays it. CapTP sessions live in the heap, so an upgrade ends them, and a client starts a new one and fetches its home again. @@ -70,7 +98,8 @@ Homes, counters, and the canister's CapTP identity live in a [Loam](https://gith ## Known gaps - **The entropy is not secret** from the subnet's nodes, nor from whoever installs; nothing rests on it but the CapTP keys. A real deployment would draw it from `raw_rand` in a first call after install. -- **One session per principal.** A second `start` from the same caller traps until an upgrade clears sessions; a client that loses its session can't reconnect with the same key. -- **No removal or collection.** A home holds 8 names and can't drop one; Loam garbage collection never runs. +- **One session per principal.** A new `start` from a caller closes the caller's old session. +- **Not offer-safe.** A buyer hands over a payment and trusts the shop's code, which is right here because it's in the same vat; across vats this needs Zoe's escrow. The board is init-only, but anyone may post any name first. +- **No removal or collection.** A home holds 8 names and can't drop one; spent payments keep their records; Loam garbage collection never runs. - **The canister pays for every call** and admits any signed caller; it should refuse strangers before doing work (`canister_inspect_message`). - **Third-party handoffs** need gift ids from entropy and dials to other peers; the canister refuses both. diff --git a/client/connect.js b/client/connect.js new file mode 100644 index 0000000..2bb1ab7 --- /dev/null +++ b/client/connect.js @@ -0,0 +1,58 @@ +/** + * @file Open a CapTP session to the canister as the principal of a key file. + */ +import { readFile, writeFile } from 'node:fs/promises'; +import { HttpAgent, Actor } from '@icp-sdk/core/agent'; +import { Ed25519KeyIdentity } from '@icp-sdk/core/identity'; +import { openPeer } from './peer.js'; + +/** The Candid interface in counter.did. */ +const idlFactory = ({ IDL }) => { + const Frames = IDL.Vec(IDL.Nat8); + return IDL.Service({ + start: IDL.Func([Frames], [Frames], []), + deliver: IDL.Func([Frames], [Frames], []), + }); +}; + +/** The seed in `path`, or a fresh one written there. */ +const keySeed = async path => { + try { + return new Uint8Array(await readFile(path)); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + const seed = crypto.getRandomValues(new Uint8Array(32)); + await writeFile(path, seed, { mode: 0o600, flag: 'wx' }); + return seed; + } +}; + +/** + * Open a session to `canisterId` at `host` as the principal whose Ed25519 + * seed is in `keyFile` (32 bytes, made if missing), logging each update call. + * + * @param {string} host the replica, e.g. https://icp-api.io + * @param {string} canisterId + * @param {string} keyFile + */ +export const connect = async (host, canisterId, keyFile) => { + const { hostname } = new URL(host); + const agent = await HttpAgent.create({ + host, + identity: Ed25519KeyIdentity.generate(await keySeed(keyFile)), + // A local replica's root key is its own; mainnet's is built in. + shouldFetchRootKey: hostname === '127.0.0.1' || hostname === 'localhost', + }); + const actor = Actor.createActor(idlFactory, { agent, canisterId }); + const carry = async (method, frames) => { + const t0 = performance.now(); + const reply = await actor[method](frames); + console.error(` ${method} ${frames.length}B -> ${reply.length}B in ${Math.round(performance.now() - t0)}ms`); + return reply; + }; + const module = await WebAssembly.compile( + await readFile(new URL('../zig-out/bin/client.wasm', import.meta.url)), + ); + const seed = crypto.getRandomValues(new Uint8Array(64)); + return openPeer({ module, seed, carry }, canisterId); +}; diff --git a/client/counter.mjs b/client/counter.mjs index 981fd2e..fb10e3a 100644 --- a/client/counter.mjs +++ b/client/counter.mjs @@ -17,31 +17,7 @@ Each run's sends are pipelined: one update call after the handshake, plus one for init. HOST is the replica, e.g. http://127.0.0.1:4960, or https://icp-api.io.`; -import { readFile, writeFile } from 'node:fs/promises'; -import { HttpAgent, Actor } from '@icp-sdk/core/agent'; -import { Ed25519KeyIdentity } from '@icp-sdk/core/identity'; -import { openPeer } from './peer.js'; - -/** The Candid interface in counter.did. */ -const idlFactory = ({ IDL }) => { - const Frames = IDL.Vec(IDL.Nat8); - return IDL.Service({ - start: IDL.Func([Frames], [Frames], []), - deliver: IDL.Func([Frames], [Frames], []), - }); -}; - -/** The seed in `path`, or a fresh one written there. */ -const keySeed = async path => { - try { - return new Uint8Array(await readFile(path)); - } catch (err) { - if (err.code !== 'ENOENT') throw err; - const seed = crypto.getRandomValues(new Uint8Array(32)); - await writeFile(path, seed, { mode: 0o600, flag: 'wx' }); - return seed; - } -}; +import { connect } from './connect.js'; const main = async ([host, canisterId, keyFile, command, name, ...verbs]) => { if (!name || !['init', 'use'].includes(command)) { @@ -49,26 +25,7 @@ const main = async ([host, canisterId, keyFile, command, name, ...verbs]) => { process.exitCode = 2; return; } - const { hostname } = new URL(host); - const agent = await HttpAgent.create({ - host, - identity: Ed25519KeyIdentity.generate(await keySeed(keyFile)), - // A local replica's root key is its own; mainnet's is built in. - shouldFetchRootKey: hostname === '127.0.0.1' || hostname === 'localhost', - }); - const actor = Actor.createActor(idlFactory, { agent, canisterId }); - const carry = async (method, frames) => { - const t0 = performance.now(); - const reply = await actor[method](frames); - console.error(` ${method} ${frames.length}B -> ${reply.length}B in ${Math.round(performance.now() - t0)}ms`); - return reply; - }; - const module = await WebAssembly.compile( - await readFile(new URL('../zig-out/bin/client.wasm', import.meta.url)), - ); - const seed = crypto.getRandomValues(new Uint8Array(64)); - - const peer = await openPeer({ module, seed, carry }, canisterId); + const peer = await connect(host, canisterId, keyFile); console.log('session open'); const home = peer.fetch('home'); /** Send each verb without waiting, then print each answer. */ diff --git a/client/peer.js b/client/peer.js index b3025d3..01d85dc 100644 --- a/client/peer.js +++ b/client/peer.js @@ -78,7 +78,10 @@ export const openPeer = async ({ module, seed, carry }, canisterId) => { const valueOf = slot => { const kind = wasm.client_result_kind(slot); if (kind === 0) throw Error(`answer ${slot} still pending after the canister went quiet`); - if (kind === 3) throw Error(`answer ${slot} broke`); + if (kind === 3) { + check(wasm.client_result_broken(slot), 'broken'); + throw Error(`answer ${slot} broke: ${decoder.decode(staged())}`); + } if (kind === 4) return undefined; return kind === 2 ? Number(wasm.client_result_integer(slot)) : { slot }; }; @@ -94,22 +97,21 @@ export const openPeer = async ({ module, seed, carry }, canisterId) => { /** @returns {Answer} the capability published as `name` */ fetch: name => ({ slot: slotOf(withBytes(encoder.encode(name), (p, n) => wasm.client_fetch(p, n)), 'fetch') }), /** - * Send `verb` to `target` with the arguments in `args`: at most one - * string, then at most one settled reference. + * Send `verb` to `target`, without waiting for it to settle. * * @param {Answer} target * @param {string} verb - * @param {...(string | Answer)} args + * @param {...(string | bigint | Answer)} args strings, integers, and + * answers that have settled to references * @returns {Answer} `target`'s answer */ send: (target, verb, ...args) => { - const text = args.find(arg => typeof arg === 'string'); - const object = args.find(arg => typeof arg === 'object'); - const status = withBytes(encoder.encode(verb), (verbPtr, verbLen) => - withBytes(encoder.encode(text ?? ''), (textPtr, textLen) => - wasm.client_send(target.slot, verbPtr, verbLen, textPtr, text === undefined ? -1 : textLen, object ? object.slot : -1), - ), - ); + for (const arg of args) { + if (typeof arg === 'string') check(withBytes(encoder.encode(arg), wasm.client_arg_text), 'argument'); + else if (typeof arg === 'bigint') check(wasm.client_arg_integer(arg), 'argument'); + else check(wasm.client_arg_reference(arg.slot), 'argument'); + } + const status = withBytes(encoder.encode(verb), (p, n) => wasm.client_send(target.slot, p, n)); return { slot: slotOf(status, 'send') }; }, flush, diff --git a/client/shop.mjs b/client/shop.mjs new file mode 100644 index 0000000..efd6596 --- /dev/null +++ b/client/shop.mjs @@ -0,0 +1,102 @@ +#!/usr/bin/env node +/** + * @file Alice buys a widget from Bob, over ERTP in the canister. + */ +const HELP = `usage: shop.mjs HOST CANISTER_ID KEY_FILE STEP + +Each STEP runs as the principal whose key is in KEY_FILE (made if missing): + + mint issue moola, mint 10 into a purse kept at home as "wallet", + and post the moola issuer on the board + open issue widgets, stock one, and post a shop selling it for 3 + moola, paid into a purse kept at home as "proceeds" + buy pay 3 moola from "wallet" for the widget, and keep it in a + purse at home as "closet" + balances show each purse kept at home + +Run mint and buy as Alice, open as Bob.`; + +import { connect } from './connect.js'; + +const steps = { + async mint(peer, home, board) { + const mint = peer.send(peer.fetch('makeIssuerKit'), 'make', 'moola'); + const moola = peer.send(mint, 'getIssuer'); + const wallet = peer.send(moola, 'makeEmptyPurse'); + const minted = peer.send(mint, 'mintPayment', 10n); + await peer.flush(); + const deposited = peer.send(wallet, 'deposit', minted); + peer.send(home, 'init', 'wallet', wallet); + peer.send(board, 'init', 'moola', moola); + await peer.flush(); + console.log('minted', peer.valueOf(deposited), 'moola into wallet'); + }, + async open(peer, home, board) { + const mint = peer.send(peer.fetch('makeIssuerKit'), 'make', 'widget'); + const widgets = peer.send(mint, 'getIssuer'); + const stock = peer.send(widgets, 'makeEmptyPurse'); + const widget = peer.send(mint, 'mintPayment', 1n); + const proceeds = peer.send(peer.send(board, 'get', 'moola'), 'makeEmptyPurse'); + await peer.flush(); + const stocked = peer.send(stock, 'deposit', widget); + const shop = peer.send(peer.fetch('makeShop'), 'make', 3n, proceeds, stock); + peer.send(home, 'init', 'proceeds', proceeds); + peer.send(board, 'init', 'widget', widgets); + await peer.flush(); + peer.send(board, 'init', 'bobs-shop', shop); + await peer.flush(); + console.log('stocked', peer.valueOf(stocked), 'widget; shop open at 3 moola'); + }, + async buy(peer, home, board) { + const wallet = peer.send(home, 'get', 'wallet'); + const pay = peer.send(wallet, 'withdraw', 3n); + const shop = peer.send(board, 'get', 'bobs-shop'); + await peer.flush(); + const goods = peer.send(shop, 'buy', pay); + await peer.flush(); + try { + peer.valueOf(goods); + } catch (err) { + // The shop refused; the payment still holds what was withdrawn. + const back = peer.send(wallet, 'deposit', pay); + await peer.flush(); + console.log('refunded', peer.valueOf(back), 'moola to wallet'); + throw err; + } + const closet = peer.send(peer.send(board, 'get', 'widget'), 'makeEmptyPurse'); + await peer.flush(); + const got = peer.send(closet, 'deposit', goods); + peer.send(home, 'init', 'closet', closet); + await peer.flush(); + console.log('bought', peer.valueOf(got), 'widget into closet'); + }, + async balances(peer, home) { + const names = ['wallet', 'closet', 'proceeds']; + const amounts = names.map(name => peer.send(peer.send(home, 'get', name), 'getCurrentAmount')); + await peer.flush(); + names.forEach((name, i) => { + let amount; + try { + amount = peer.valueOf(amounts[i]); + } catch (err) { + amount = `none (${err.message})`; + } + console.log(name, amount); + }); + }, +}; + +const main = async ([host, canisterId, keyFile, step]) => { + if (!Object.hasOwn(steps, step ?? '')) { + console.error(HELP); + process.exitCode = 2; + return; + } + const peer = await connect(host, canisterId, keyFile); + await steps[step](peer, peer.fetch('home'), peer.fetch('board')); +}; + +main(process.argv.slice(2)).catch(err => { + console.error(err); + process.exitCode = 1; +}); diff --git a/src/client.zig b/src/client.zig index 11d36b6..22c76e8 100644 --- a/src/client.zig +++ b/src/client.zig @@ -41,7 +41,8 @@ const Result = union(enum) { pending, reference: model.Reference, integer: i64, - broken, + /// Why, as the canister said, or as this peer saw it. + broken: []const u8, void, }; @@ -57,9 +58,10 @@ fn record(ctx: ?*anyopaque, resolution: actors.Resolution) void { .reference => |ref| .{ .reference = ref }, .integer => |n| .{ .integer = n }, .void => .void, - else => .broken, + else => .{ .broken = "unexpected value" }, }, - .broken, .give => .broken, + .broken => |reason| .{ .broken = gpa.dupe(u8, reason.detail) catch "out of memory" }, + .give => .{ .broken = "unexpected give" }, }; } @@ -146,28 +148,54 @@ export fn client_fetch(name: [*]const u8, len: usize) i32 { return watch(vow) catch |err| failSlot(err); } -/// Send `verb` to what slot `target` holds: a settled reference, or a -/// pending answer, in which case the send rides the promise without waiting -/// for it. The arguments are the string `text`, if `text_len` is not -/// negative, then the reference slot `object` holds, if `object` is not -/// negative. Returns the answer's slot. -export fn client_send(target: u32, verb: [*]const u8, len: usize, text: [*]const u8, text_len: i32, object: i32) i32 { +/// Arguments for the next `client_send`, staged by the `client_arg_*` +/// exports. Strings are copied, and freed when the next send begins. +var args: [8]model.Argument = undefined; +var arg_count: usize = 0; +var arg_texts: [8][]u8 = undefined; +var text_count: usize = 0; + +fn stageArg(arg: model.Argument) u32 { + if (arg_count == args.len) return fail(error.TooManyArguments); + args[arg_count] = arg; + arg_count += 1; + return 0; +} + +/// Stage a string argument. +export fn client_arg_text(text: [*]const u8, len: usize) u32 { + if (text_count == arg_texts.len) return fail(error.TooManyArguments); + const copy = gpa.dupe(u8, text[0..len]) catch |err| return fail(err); + arg_texts[text_count] = copy; + text_count += 1; + return stageArg(.{ .string = copy }); +} + +/// Stage an integer argument. +export fn client_arg_integer(n: i64) u32 { + return stageArg(.{ .integer = n }); +} + +/// Stage the settled reference slot `object` holds as an argument. +export fn client_arg_reference(object: u32) u32 { + if (object >= slot_count) return fail(error.NoSuchSlot); + return switch (results[object]) { + .reference => |ref| stageArg(.{ .reference = ref }), + else => fail(error.NotAReference), + }; +} + +/// Send `verb`, with the staged arguments, to what slot `target` holds: a +/// settled reference, or a pending answer, in which case the send rides the +/// promise without waiting for it. Returns the answer's slot. +export fn client_send(target: u32, verb: [*]const u8, len: usize) i32 { + defer { + for (arg_texts[0..text_count]) |text| gpa.free(text); + text_count = 0; + arg_count = 0; + } if (target >= slot_count) return failSlot(error.NoSuchSlot); - var args: [2]model.Argument = undefined; - var count: usize = 0; - if (text_len >= 0) { - args[count] = .{ .string = text[0..@intCast(text_len)] }; - count += 1; - } - if (object >= 0) { - if (object >= slot_count) return failSlot(error.NoSuchSlot); - args[count] = switch (results[@intCast(object)]) { - .reference => |ref| .{ .reference = ref }, - else => return failSlot(error.NotAReference), - }; - count += 1; - } - const msg: actors.Message = .{ .verb = verb[0..len], .args = args[0..count] }; + const msg: actors.Message = .{ .verb = verb[0..len], .args = args[0..arg_count] }; const vow = switch (results[target]) { .reference => |ref| host.send(session.?, ref, msg), .pending => host.vowSend(vows[target], msg), @@ -187,3 +215,13 @@ export fn client_result_integer(slot: u32) i64 { else => 0, }; } + +/// Stage why the answer in `slot` broke, for `client_out_ptr`. +export fn client_result_broken(slot: u32) u32 { + out.clearRetainingCapacity(); + switch (results[slot]) { + .broken => |why| out.appendSlice(gpa, why) catch |err| return fail(err), + else => {}, + } + return 0; +} diff --git a/src/node.zig b/src/node.zig index abd14b0..f329172 100644 --- a/src/node.zig +++ b/src/node.zig @@ -278,10 +278,15 @@ pub fn Node(comptime Memory: type) type { self.sessions.deinit(self.gpa); } - /// Open `caller`'s session with its `op:start-session` and append the - /// canister's frames to `reply`. + /// Open `caller`'s session with its `op:start-session`, closing any + /// it had, and append the canister's frames to `reply`. pub fn start(self: *Self, caller: []const u8, frames: []const u8, reply: *std.ArrayList(u8)) !void { - if (self.sessions.contains(caller)) return error.SessionAlreadyStarted; + if (self.sessions.fetchRemove(caller)) |old| { + defer self.gpa.free(old.key); + try self.host.transportClosed(old.value, "replaced by a new start"); + try link.settle(&self.host, .flush); + try self.host.releaseSession(old.value); + } const key = try self.gpa.dupe(u8, caller); errdefer self.gpa.free(key); const session = try self.host.openAcceptedAdvertised(link.transport); diff --git a/src/pair_test.zig b/src/pair_test.zig index 1072b4e..9898159 100644 --- a/src/pair_test.zig +++ b/src/pair_test.zig @@ -181,6 +181,16 @@ test "a caller's home keeps a counter across an upgrade; sessions start over" { try std.testing.expectEqual(@as(usize, 1), try again.flush(gpa, &node, Settled{ .answers = answers[0..2] })); try expectCounts(&.{ 3, 3 }, &answers); + // A new start from Alice closes her old session and opens another. + var third: Client = undefined; + try third.open(gpa, 0x63, "alice"); + defer third.host.deinit(); + try std.testing.expectEqual(@as(usize, 1), try third.flush(gpa, &node, Opened{})); + answers = @splat(.{}); + try third.sendAll(try send(&third, try third.host.fetch(third.session, "home"), "get", &.{.{ .string = "c1" }}), &.{"incr"}, &answers); + _ = try third.flush(gpa, &node, Settled{ .answers = answers[0..1] }); + try expectCounts(&.{4}, &answers); + // Bob's home is his own: nothing under "c1" there. var bob: Client = undefined; try bob.open(gpa, 0x71, "bob");