feat: Counter canister and a Node client, over OCapN on a local replica
The canister is freestanding wasm32 importing only ic0. Each caller principal gets a CapTP session: start carries op:start-session, deliver carries later frames, and each reply carries the canister's frames. The client peer is wasm too, driven from Node by @icp-sdk/core. It holds answer releases so they ride ahead of the next call instead of costing an update call of their own: handshake, fetch, and each send are one update call apiece. Generated-by: Claude Code (claude-opus-5-5)
This commit is contained in:
1 parent
6348422012
commit
1177fc86b6
13 files changed
+787
-14
No files matched your search
@@ -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" });
|
||||
}
|
||||
Reference in new issue
Block a user