diff --git a/build.zig b/build.zig index 004a723..af2f37d 100644 --- a/build.zig +++ b/build.zig @@ -5,13 +5,46 @@ pub fn build(b: *std.Build) void { const optimize = b.standardOptimizeOption(.{}); const glowcap = b.dependency("glowcap", .{ .target = target, .optimize = optimize }); + const test_step = b.step("test", "Run the unit tests and the in-memory client/canister round trip"); + for ([_][]const u8{ "src/pair_test.zig", "src/candid.zig", "src/principal.zig" }) |root| { + const t = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path(root), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "glowcap", .module = glowcap.module("glowcap") }}, + }) }); + test_step.dependOn(&b.addRunArtifact(t).step); + } - const pair_test = b.addTest(.{ .root_module = b.createModule(.{ - .root_source_file = b.path("src/pair_test.zig"), - .target = target, - .optimize = optimize, - .imports = &.{.{ .name = "glowcap", .module = glowcap.module("glowcap") }}, - }) }); - const test_step = b.step("test", "Run the in-memory client/canister round trip"); - test_step.dependOn(&b.addRunArtifact(pair_test).step); + // The canister: freestanding 32-bit Wasm whose only imports are `ic0`. + const wasm32 = b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .freestanding }); + const canister_glowcap = b.dependency("glowcap", .{ .target = wasm32, .optimize = .ReleaseSmall }); + const canister = b.addExecutable(.{ + .name = "counter", + .root_module = b.createModule(.{ + .root_source_file = b.path("src/canister.zig"), + .target = wasm32, + .optimize = .ReleaseSmall, + .imports = &.{.{ .name = "glowcap", .module = canister_glowcap.module("glowcap") }}, + }), + }); + canister.entry = .disabled; + canister.root_module.export_symbol_names = &.{ "canister_init", "canister_update start", "canister_update deliver" }; + const canister_step = b.step("canister", "Build the canister to zig-out/bin/counter.wasm"); + canister_step.dependOn(&b.addInstallArtifact(canister, .{}).step); + + // The client peer, for a JavaScript host to drive. + const client = b.addExecutable(.{ + .name = "client", + .root_module = b.createModule(.{ + .root_source_file = b.path("src/client.zig"), + .target = wasm32, + .optimize = .ReleaseSmall, + .imports = &.{.{ .name = "glowcap", .module = canister_glowcap.module("glowcap") }}, + }), + }); + client.entry = .disabled; + client.rdynamic = true; + const client_step = b.step("client", "Build the client peer to zig-out/bin/client.wasm"); + client_step.dependOn(&b.addInstallArtifact(client, .{}).step); } diff --git a/client/counter.mjs b/client/counter.mjs new file mode 100644 index 0000000..c1ec00c --- /dev/null +++ b/client/counter.mjs @@ -0,0 +1,64 @@ +#!/usr/bin/env node +/** + * @file Call the Counter canister over OCapN. + */ +const HELP = `usage: counter.mjs HOST CANISTER_ID [VERB...] + +Open a CapTP session to the canister, fetch "counter", and send each VERB +(incr, decr, value; default: incr incr decr), printing each answer. +HOST is the replica, e.g. http://127.0.0.1:4959, or https://icp-api.io. +A fresh Ed25519 identity makes each run its own caller, so its own session.`; + +import { readFile } from 'node:fs/promises'; +import { HttpAgent, Actor } from '@icp-sdk/core/agent'; +import { IDL } from '@icp-sdk/core/candid'; +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], []), + }); +}; + +const main = async ([host, canisterId, ...verbs]) => { + if (!host || !canisterId) { + console.error(HELP); + process.exitCode = 2; + return; + } + const local = new URL(host).hostname === '127.0.0.1' || new URL(host).hostname === 'localhost'; + const agent = await HttpAgent.create({ + host, + identity: Ed25519KeyIdentity.generate(), + // A local replica's root key is its own; mainnet's is built in. + shouldFetchRootKey: local, + }); + 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); + console.log('session open'); + await peer.fetch('counter'); + console.log('fetched counter'); + for (const verb of verbs.length ? verbs : ['incr', 'incr', 'decr']) { + console.log(verb, await peer.send(verb)); + } +}; + +main(process.argv.slice(2)).catch(err => { + console.error(err); + process.exitCode = 1; +}); diff --git a/client/package-lock.json b/client/package-lock.json new file mode 100644 index 0000000..d8c3423 --- /dev/null +++ b/client/package-lock.json @@ -0,0 +1,133 @@ +{ + "name": "icp-ocapn-counter-client", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "icp-ocapn-counter-client", + "dependencies": { + "@icp-sdk/core": "6.1.1" + } + }, + "node_modules/@dfinity/cbor": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@dfinity/cbor/-/cbor-0.2.3.tgz", + "integrity": "sha512-5GX+9tAf29r94Pxv8nCzrv2/t+AkOfem/c/G61+FA2Wadq7THvc5cvr/AVLH0LpukVfNSWRRHvl1fkCdiB9MMQ==", + "license": "Apache-2.0" + }, + "node_modules/@icp-sdk/core": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/@icp-sdk/core/-/core-6.1.1.tgz", + "integrity": "sha512-bMRKAJg0zwJyd53feg8D6Qd+ikoxrxzsVrvzmyjxgSwn7znKxBVyCN8GR/NEQ+dYaE+yWuXV0O3C8AiHL2JUqg==", + "license": "Apache-2.0", + "dependencies": { + "@dfinity/cbor": "^0.2.3", + "@noble/curves": "^2.2.0", + "@noble/hashes": "^2.2.0", + "@scure/bip32": "^2.2.0", + "@scure/bip39": "^2.2.0", + "asn1js": "^3.0.7" + } + }, + "node_modules/@noble/curves": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz", + "integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "2.4.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", + "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/base": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-2.4.0.tgz", + "integrity": "sha512-thZ1TuJwFwBblOhgsjDKvvGirBxNp+wSvY/DR6tJBJOTDhdAAcHJ8Vbr2eFnqaxeca4+t0i9KBf+uHYGWwZORg==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-2.4.0.tgz", + "integrity": "sha512-i3DS0CptAocyvqE4n3SUkpzeQK4vJMFwWLofTwRiiKo2aWojBOfyMCgfKw9HVpO6fSY5AK86sHS/Uzn8kK9Few==", + "license": "MIT", + "dependencies": { + "@noble/curves": "2.4.0", + "@noble/hashes": "2.4.0", + "@scure/base": "2.4.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip39": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-2.4.0.tgz", + "integrity": "sha512-82dxFbZUYboyOf0AXiydsQrFQ5Q4h9mX+O2UkE91ROYmsc0BKMGZLwDmy96Jpa2+vrtoxomjUhy1RPIgH/r2nA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "2.4.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/asn1js": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.1.0.tgz", + "integrity": "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA==", + "license": "BSD-3-Clause", + "dependencies": { + "pvtsutils": "^1.3.6", + "pvutils": "^1.2.0", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/pvtsutils": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz", + "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/pvutils": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz", + "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==", + "license": "MIT", + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "license": "0BSD" + } + } +} diff --git a/client/package.json b/client/package.json new file mode 100644 index 0000000..45cce8c --- /dev/null +++ b/client/package.json @@ -0,0 +1,8 @@ +{ + "name": "icp-ocapn-counter-client", + "private": true, + "type": "module", + "dependencies": { + "@icp-sdk/core": "6.1.1" + } +} diff --git a/client/peer.js b/client/peer.js new file mode 100644 index 0000000..c24ea6e --- /dev/null +++ b/client/peer.js @@ -0,0 +1,91 @@ +/** + * @file The client peer (`zig-out/bin/client.wasm`) driven over a canister's + * `start` and `deliver` update calls. + */ + +const { freeze } = Object; + +const decoder = new TextDecoder(); +const encoder = new TextEncoder(); + +/** + * @typedef {(method: 'start' | 'deliver', frames: Uint8Array) => Promise} Carry + * one update call: the frames out, the frames in the reply + */ + +/** + * Instantiate the client peer and open a session to `canisterId`. + * + * @param {object} io + * @param {WebAssembly.Module} io.module the compiled client.wasm + * @param {Uint8Array} io.seed 64 bytes of fresh entropy + * @param {Carry} io.carry + * @param {string} canisterId the canister's principal, as text + */ +export const openPeer = async ({ module, seed, carry }, canisterId) => { + const { exports: wasm } = await WebAssembly.instantiate(module, { + env: { report: (ptr, len) => console.error(readText(ptr, len)) }, + }); + const memory = () => new Uint8Array(wasm.memory.buffer); + const readText = (ptr, len) => decoder.decode(memory().slice(ptr, ptr + len)); + + /** Copy `bytes` into wasm memory for the length of `fn`. */ + const withBytes = (bytes, fn) => { + const ptr = wasm.client_alloc(bytes.length || 1); + memory().set(bytes, ptr); + try { + return fn(ptr, bytes.length); + } finally { + wasm.client_free(ptr, bytes.length || 1); + } + }; + const staged = () => memory().slice(wasm.client_out_ptr(), wasm.client_out_ptr() + wasm.client_out_len()); + const check = (status, what) => { + if (status !== 0) throw Error(`${what}: ${decoder.decode(staged())}`); + }; + + /** + * Carry staged frames until the canister has nothing more to say. The + * first call of a session is `start`. + */ + let method = 'start'; + const pump = async () => { + for (;;) { + const frames = staged(); + if (frames.length === 0) return; + const reply = await carry(method, frames); + method = 'deliver'; + check(withBytes(reply, wasm.client_feed), 'feed'); + check(wasm.client_outbound(), 'outbound'); + } + }; + + check(withBytes(seed, wasm.client_init), 'init'); + check(withBytes(encoder.encode(canisterId), wasm.client_dial), 'dial'); + await pump(); + if (!wasm.client_session_open()) throw Error('session did not open'); + + /** Wait for the pending call's answer, carrying frames as needed. */ + const settle = async () => { + await pump(); + const kind = wasm.client_result_kind(); + if (kind === 0) throw Error('no answer after the canister went quiet'); + if (kind === 3) throw Error('broken'); + return kind; + }; + + return freeze({ + /** Fetch the capability published as `name` and make it the target. */ + async fetch(name) { + check(withBytes(encoder.encode(name), wasm.client_fetch), 'fetch'); + await settle(); + check(wasm.client_adopt(), 'adopt'); + }, + /** Send `verb` to the target; resolve to its integer answer. */ + async send(verb) { + check(withBytes(encoder.encode(verb), wasm.client_send), 'send'); + await settle(); + return Number(wasm.client_result_integer()); + }, + }); +}; diff --git a/counter.did b/counter.did new file mode 100644 index 0000000..f30e4c1 --- /dev/null +++ b/counter.did @@ -0,0 +1,7 @@ +// Each blob is CapTP frames in Syrup byte-string envelopes. +service : { + // Open the caller's session with its `op:start-session`. + start : (blob) -> (blob); + // Carry later frames on the caller's session. + deliver : (blob) -> (blob); +} diff --git a/dfx.json b/dfx.json new file mode 100644 index 0000000..41a33f7 --- /dev/null +++ b/dfx.json @@ -0,0 +1,14 @@ +{ + "version": 1, + "canisters": { + "counter": { + "type": "custom", + "build": "zig build canister", + "wasm": "zig-out/bin/counter.wasm", + "candid": "counter.did" + } + }, + "networks": { + "local": { "bind": "127.0.0.1:4959", "type": "ephemeral" } + } +} diff --git a/src/candid.zig b/src/candid.zig new file mode 100644 index 0000000..3f4d274 --- /dev/null +++ b/src/candid.zig @@ -0,0 +1,52 @@ +//! The one Candid shape the canister speaks: a single `blob` argument or +//! reply, so `dfx canister call` and agent libraries can reach it. +//! @see https://github.com/dfinity/candid/blob/master/spec/Candid.md binary format + +const std = @import("std"); + +/// `DIDL`, one type-table entry `vec nat8`, one argument of that type. +const header = "DIDL\x01\x6d\x7b\x01\x00"; + +pub const DecodeError = error{NotOneBlob}; + +/// The bytes of a Candid message holding exactly one `blob`, borrowed from +/// `message`. +pub fn decodeBlob(message: []const u8) DecodeError![]const u8 { + if (!std.mem.startsWith(u8, message, header)) return error.NotOneBlob; + var reader: std.Io.Reader = .fixed(message[header.len..]); + const len = reader.takeLeb128(u64) catch return error.NotOneBlob; + const rest = message[header.len + reader.seek ..]; + if (rest.len != len) return error.NotOneBlob; + return rest; +} + +/// Append a Candid message holding `bytes` as one `blob`. +pub fn encodeBlob(gpa: std.mem.Allocator, bytes: []const u8, out: *std.ArrayList(u8)) !void { + try out.appendSlice(gpa, header); + var len = bytes.len; + while (true) { + const low: u8 = @intCast(len & 0x7f); + len >>= 7; + if (len == 0) { + try out.append(gpa, low); + break; + } + try out.append(gpa, low | 0x80); + } + try out.appendSlice(gpa, bytes); +} + +test "a blob round-trips, including a length past one LEB128 byte" { + const gpa = std.testing.allocator; + const payload: [300]u8 = @splat('x'); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + try encodeBlob(gpa, &payload, &out); + try std.testing.expectEqualSlices(u8, header ++ "\xac\x02", out.items[0 .. header.len + 2]); + try std.testing.expectEqualSlices(u8, &payload, try decodeBlob(out.items)); +} + +test "anything but one blob is refused" { + try std.testing.expectError(error.NotOneBlob, decodeBlob("DIDL\x00\x00")); + try std.testing.expectError(error.NotOneBlob, decodeBlob(header ++ "\x05abc")); +} diff --git a/src/canister.zig b/src/canister.zig new file mode 100644 index 0000000..5fb4904 --- /dev/null +++ b/src/canister.zig @@ -0,0 +1,158 @@ +//! A canister that hosts a Counter as an OCapN peer. Each caller principal +//! gets one CapTP session: `start` opens it with the caller's +//! `op:start-session`, and `deliver` carries later frames. Each update +//! call's reply carries whatever frames the canister has for that caller. +//! +//! A trap rolls back the whole update, Host state included, so a frame that +//! breaks the session leaves the canister as it was before the call. + +const std = @import("std"); +const glowcap = @import("glowcap"); +const candid = @import("candid.zig"); +const link = @import("link.zig"); +const principal = @import("principal.zig"); +const Counter = @import("counter.zig").Counter; + +const model = glowcap.ocapn.model; +const Host = glowcap.driver.core.Host; +const HostSession = glowcap.driver.core.HostSession; + +/// The Internet Computer System API, for 32-bit Wasm. +/// @see https://docs.internetcomputer.org/references/ic-interface-spec/#system-api +const ic0 = struct { + extern "ic0" fn msg_arg_data_size() u32; + extern "ic0" fn msg_arg_data_copy(dst: u32, offset: u32, size: u32) void; + extern "ic0" fn msg_caller_size() u32; + extern "ic0" fn msg_caller_copy(dst: u32, offset: u32, size: u32) void; + extern "ic0" fn msg_reply_data_append(src: u32, size: u32) void; + extern "ic0" fn msg_reply() void; + extern "ic0" fn canister_self_size() u32; + extern "ic0" fn canister_self_copy(dst: u32, offset: u32, size: u32) void; + extern "ic0" fn time() u64; + extern "ic0" fn trap(src: u32, size: u32) noreturn; + extern "ic0" fn debug_print(src: u32, size: u32) void; +}; + +pub const std_options: std.Options = .{ + .logFn = log, + .enable_segfault_handler = false, + .signal_stack_size = null, +}; + +fn log(comptime level: std.log.Level, comptime scope: @EnumLiteral(), comptime format: []const u8, args: anytype) void { + var buf: [512]u8 = undefined; + const text = std.fmt.bufPrint(&buf, "[" ++ @tagName(level) ++ "] (" ++ @tagName(scope) ++ ") " ++ format, args) catch buf[0..]; + ic0.debug_print(@intFromPtr(text.ptr), text.len); +} + +pub const panic = std.debug.FullPanic(trapPanic); + +fn trapPanic(msg: []const u8, first_trace_addr: ?usize) noreturn { + _ = first_trace_addr; + ic0.trap(@intFromPtr(msg.ptr), msg.len); +} + +fn trapWith(comptime what: []const u8, err: anyerror) noreturn { + var buf: [256]u8 = undefined; + const text = std.fmt.bufPrint(&buf, what ++ ": {s}", .{@errorName(err)}) catch what; + ic0.trap(@intFromPtr(text.ptr), text.len); +} + +const gpa = std.heap.wasm_allocator; +const frame_cap = 64 * 1024; + +/// The Host lives here, at an address that never moves, for the canister's +/// lifetime; canister memory persists between calls (not across upgrades). +var host: Host = undefined; +var sessions: std.StringHashMapUnmanaged(*HostSession) = .empty; + +fn init() !void { + const self_len = ic0.canister_self_size(); + const self_id = try gpa.alloc(u8, self_len); + ic0.canister_self_copy(@intFromPtr(self_id.ptr), 0, self_len); + + // Not secret: every replica, and anyone who knows the install time, can + // derive these. A real deployment would draw them from `raw_rand`. + var durable_seed: [32]u8 = undefined; + var session_root: [32]u8 = undefined; + var kdf = std.crypto.hash.Blake3.initKdf("icp-ocapn-counter durable seed v0", .{}); + kdf.update(self_id); + kdf.update(std.mem.asBytes(&ic0.time())); + kdf.final(&durable_seed); + kdf = std.crypto.hash.Blake3.initKdf("icp-ocapn-counter session root v0", .{}); + kdf.update(&durable_seed); + kdf.final(&session_root); + + host = try Host.init(gpa, durable_seed, session_root, Host.Options.init(.unchecked, frame_cap)); + _ = try host.defineTransport(link.profile); + _ = try host.publish("counter", Counter, .{}); + + var text: [64]u8 = undefined; + const designator = try principal.text(self_id, &text); + try host.setAdvertisedLocator(.{ .transport = link.transport, .designator = designator, .hints = model.Hints.emptyFalse() }); +} + +fn canisterInit() callconv(.c) void { + init() catch |err| trapWith("init", err); +} + +fn argBlob() ![]u8 { + const len = ic0.msg_arg_data_size(); + const message = try gpa.alloc(u8, len); + ic0.msg_arg_data_copy(@intFromPtr(message.ptr), 0, len); + return message; +} + +fn caller() ![]u8 { + const len = ic0.msg_caller_size(); + const id = try gpa.alloc(u8, len); + ic0.msg_caller_copy(@intFromPtr(id.ptr), 0, len); + return id; +} + +/// Feed the caller's frames to `session`, then reply with what it has queued. +fn exchange(session: *HostSession, message: []const u8) !void { + try host.feedBytes(session, try candid.decodeBlob(message)); + try link.settle(&host, .flush); + var frames: std.ArrayList(u8) = .empty; + defer frames.deinit(gpa); + try link.drainOutbound(gpa, session, &frames); + var reply: std.ArrayList(u8) = .empty; + defer reply.deinit(gpa); + try candid.encodeBlob(gpa, frames.items, &reply); + ic0.msg_reply_data_append(@intFromPtr(reply.items.ptr), reply.items.len); + ic0.msg_reply(); +} + +fn start() !void { + const who = try caller(); + const entry = try sessions.getOrPut(gpa, who); + if (entry.found_existing) return error.SessionAlreadyStarted; + entry.value_ptr.* = try host.openAcceptedAdvertised(link.transport); + const message = try argBlob(); + defer gpa.free(message); + try exchange(entry.value_ptr.*, message); +} + +fn deliver() !void { + const who = try caller(); + defer gpa.free(who); + const session = sessions.get(who) orelse return error.NoSessionForCaller; + const message = try argBlob(); + defer gpa.free(message); + try exchange(session, message); +} + +fn canisterStart() callconv(.c) void { + start() catch |err| trapWith("start", err); +} + +fn canisterDeliver() callconv(.c) void { + deliver() catch |err| trapWith("deliver", err); +} + +comptime { + @export(&canisterInit, .{ .name = "canister_init" }); + @export(&canisterStart, .{ .name = "canister_update start" }); + @export(&canisterDeliver, .{ .name = "canister_update deliver" }); +} diff --git a/src/client.zig b/src/client.zig new file mode 100644 index 0000000..a6d286f --- /dev/null +++ b/src/client.zig @@ -0,0 +1,159 @@ +//! An OCapN client peer for JavaScript hosts (Node or a browser), as +//! freestanding 32-bit Wasm. JavaScript owns the I/O: it carries the bytes +//! `glowcap_client_outbound` stages to the canister and feeds the reply back +//! with `glowcap_client_feed`. Entropy arrives as the seed passed to +//! `client_init`, so the module itself reaches nothing. +//! +//! Each export returns 0 on success; on failure it returns 1 after staging +//! the error name where `client_out_ptr`/`client_out_len` point. + +const std = @import("std"); +const glowcap = @import("glowcap"); +const link = @import("link.zig"); + +const actors = glowcap.actors; +const model = glowcap.ocapn.model; +const Host = glowcap.driver.core.Host; +const HostSession = glowcap.driver.core.HostSession; + +const env = struct { + /// Show `len` bytes at `ptr` as one log line. + extern "env" fn report(ptr: [*]const u8, len: usize) void; +}; + +pub const panic = std.debug.FullPanic(reportPanic); + +fn reportPanic(msg: []const u8, first_trace_addr: ?usize) noreturn { + _ = first_trace_addr; + env.report(msg.ptr, msg.len); + @trap(); +} + +const gpa = std.heap.wasm_allocator; +const frame_cap = 64 * 1024; + +var host: Host = undefined; +var session: ?*HostSession = null; +var out: std.ArrayList(u8) = .empty; + +/// What the last call settled to, read with `client_result_*`. +const Result = union(enum) { + pending, + reference: model.Reference, + integer: i64, + broken, +}; +var result: Result = .pending; + +fn record(ctx: ?*anyopaque, resolution: actors.Resolution) void { + _ = ctx; + result = switch (resolution) { + .fulfilled => |value| switch (value) { + .reference => |ref| .{ .reference = ref }, + .integer => |n| .{ .integer = n }, + else => .broken, + }, + .broken, .give => .broken, + }; +} + +fn fail(err: anyerror) u32 { + out.clearRetainingCapacity(); + out.appendSlice(gpa, @errorName(err)) catch {}; + return 1; +} + +export fn client_alloc(len: usize) ?[*]u8 { + const buf = gpa.alloc(u8, len) catch return null; + return buf.ptr; +} + +export fn client_free(ptr: [*]u8, len: usize) void { + gpa.free(ptr[0..len]); +} + +export fn client_out_ptr() [*]const u8 { + return out.items.ptr; +} + +export fn client_out_len() usize { + return out.items.len; +} + +/// Start the Host from 64 bytes of fresh entropy: its durable seed, then +/// its session root. +export fn client_init(seed: *const [64]u8) u32 { + host = Host.init(gpa, seed[0..32].*, seed[32..64].*, Host.Options.init(.unchecked, frame_cap)) catch |err| return fail(err); + _ = host.defineTransport(link.profile) catch |err| return fail(err); + host.ensureAdvertisedLocator(link.transport) catch |err| return fail(err); + return 0; +} + +/// Open a session to the canister whose principal is `designator`, staging +/// its `op:start-session`. +export fn client_dial(designator: [*]const u8, len: usize) u32 { + const locator: model.PeerLocator = .{ .transport = link.transport, .designator = designator[0..len], .hints = model.Hints.emptyFalse() }; + session = host.openDialedLocator(locator) catch |err| return fail(err); + return client_outbound(); +} + +/// Stage every frame queued for the canister. +export fn client_outbound() u32 { + out.clearRetainingCapacity(); + link.settle(&host, .hold) catch |err| return fail(err); + link.drainOutbound(gpa, session.?, &out) catch |err| return fail(err); + return 0; +} + +/// Feed the frames of a canister's reply. +export fn client_feed(bytes: [*]const u8, len: usize) u32 { + host.feedBytes(session.?, bytes[0..len]) catch |err| return fail(err); + link.settle(&host, .hold) catch |err| return fail(err); + return 0; +} + +export fn client_session_open() bool { + return session.?.sessionOpen(); +} + +/// Ask the canister's bootstrap object for the capability it publishes as +/// `name`; the reference settles into the result. +export fn client_fetch(name: [*]const u8, len: usize) u32 { + result = .pending; + const vow = host.fetch(session.?, name[0..len]) catch |err| return fail(err); + host.vowOn(vow, .{ .ctx = null, .func = record }) catch |err| return fail(err); + return client_outbound(); +} + +var counter: ?model.Reference = null; + +/// Keep the fetched reference as the target of `client_send`. +export fn client_adopt() u32 { + counter = switch (result) { + .reference => |ref| ref, + else => return fail(error.NotAReference), + }; + return 0; +} + +/// Send `verb`, with no arguments, to the adopted reference; its answer +/// settles into the result. +export fn client_send(verb: [*]const u8, len: usize) u32 { + result = .pending; + const target = counter orelse return fail(error.NothingAdopted); + const vow = host.send(session.?, target, .{ .verb = verb[0..len], .args = &.{} }) catch |err| return fail(err); + host.vowOn(vow, .{ .ctx = null, .func = record }) catch |err| return fail(err); + return client_outbound(); +} + +/// 0 pending, 1 a reference, 2 an integer, 3 broken. +export fn client_result_kind() u32 { + return @intFromEnum(std.meta.activeTag(result)); +} + +export fn client_result_integer() i64 { + return switch (result) { + .integer => |n| n, + else => 0, + }; +} diff --git a/src/link.zig b/src/link.zig index 9fadb5d..b9a9078 100644 --- a/src/link.zig +++ b/src/link.zig @@ -41,13 +41,20 @@ pub const SettleError = error{ DialUnsupported, }; +/// When answer releases (`op:gc-answer`) the Host holds leave. +pub const Releases = enum { + /// Now, as a reply carries them at no extra cost. + flush, + /// Ahead of the next message, so they don't cost an update call of their own. + hold, +}; + /// Run `host`'s queued actions until it is quiet. A flush needs no work here, /// because the caller drains every session it fed after this returns. -pub fn settle(host: *Host) !void { +pub fn settle(host: *Host, releases: Releases) !void { while (true) { const action = (try host.nextAction()) orelse { - // Held answer releases leave at a park; this is the park. - if (try host.flushHeldReleases()) continue; + if (releases == .flush and try host.flushHeldReleases()) continue; return; }; switch (action) { diff --git a/src/pair_test.zig b/src/pair_test.zig index 577ae2d..b850bd6 100644 --- a/src/pair_test.zig +++ b/src/pair_test.zig @@ -22,18 +22,18 @@ fn locator() model.PeerLocator { fn roundTrip(gpa: std.mem.Allocator, client: *Host, dialed: *HostSession, server: *Host, accepted: *HostSession) !bool { var request: std.ArrayList(u8) = .empty; defer request.deinit(gpa); - try link.settle(client); + try link.settle(client, .hold); try link.drainOutbound(gpa, dialed, &request); if (request.items.len == 0) return false; try server.feedBytes(accepted, request.items); - try link.settle(server); + try link.settle(server, .flush); var reply: std.ArrayList(u8) = .empty; defer reply.deinit(gpa); try link.drainOutbound(gpa, accepted, &reply); try client.feedBytes(dialed, reply.items); - try link.settle(client); + try link.settle(client, .hold); return true; } diff --git a/src/principal.zig b/src/principal.zig new file mode 100644 index 0000000..b001fec --- /dev/null +++ b/src/principal.zig @@ -0,0 +1,47 @@ +//! Principals, the Internet Computer's names for canisters and users. + +const std = @import("std"); + +/// The textual form of a principal: CRC-32 then the bytes, base32 without +/// padding, lowercase, in dash-separated groups of five. +pub fn text(bytes: []const u8, out: []u8) ![]const u8 { + var raw: [33]u8 = undefined; + if (bytes.len > 29) return error.PrincipalTooLong; + std.mem.writeInt(u32, raw[0..4], std.hash.Crc32.hash(bytes), .big); + @memcpy(raw[4..][0..bytes.len], bytes); + const data = raw[0 .. 4 + bytes.len]; + const alphabet = "abcdefghijklmnopqrstuvwxyz234567"; + var plain: [64]u8 = undefined; + var n: usize = 0; + var acc: u16 = 0; + var bits: u4 = 0; + for (data) |byte| { + acc = (acc << 8) | byte; + bits += 8; + while (bits >= 5) { + bits -= 5; + plain[n] = alphabet[(acc >> bits) & 31]; + n += 1; + } + } + if (bits > 0) { + plain[n] = alphabet[(acc << (5 - bits)) & 31]; + n += 1; + } + var w: usize = 0; + for (plain[0..n], 0..) |c, i| { + if (i > 0 and i % 5 == 0) { + out[w] = '-'; + w += 1; + } + out[w] = c; + w += 1; + } + return out[0..w]; +} + +test "a canister id in its textual form" { + var buf: [64]u8 = undefined; + try std.testing.expectEqualStrings("rrkah-fqaaa-aaaaa-aaaaq-cai", try text(&.{ 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 }, &buf)); + try std.testing.expectEqualStrings("aaaaa-aa", try text(&.{}, &buf)); +}