feat: homes per caller and counters that survive upgrades
Nodes on a canister's subnet can read its state, so no authority rests
on swiss numbers. fetch("home") answers the caller principal's own
durable store of named objects (init, get), found through Loam's name
index and made on first use; fetch("makeCounter") answers the public
maker. Homes, counters, and the CapTP identity live in Loam over the
stable-memory log, reopened in post_upgrade; sessions end with the heap.
The canister installs from 32 bytes of entropy passed as its argument
and refuses the anonymous principal. The client takes a key file, so a
caller can come back to its home, and sends string and reference
arguments.
Generated-by: Claude Code (claude-opus-5-5)
This commit is contained in:
1 parent
eb15a05668
commit
b717ccaedf
11 files changed
+782
-233
No files matched your search
+100
-88
@@ -1,21 +1,19 @@
|
||||
//! 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 canister that hosts a counter maker and a home per caller 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. The anonymous principal is refused: it would share one home.
|
||||
//!
|
||||
//! 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.
|
||||
//! Install with 32 bytes of fresh entropy as the argument (one Candid
|
||||
//! `blob`). Homes, counters, and the peer's identity then live in stable
|
||||
//! memory and survive upgrades; sessions do not.
|
||||
//!
|
||||
//! A trap rolls back the whole message, heap and stable memory alike.
|
||||
|
||||
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;
|
||||
const Node = @import("node.zig").Node(Stable);
|
||||
|
||||
/// The Internet Computer System API, for 32-bit Wasm.
|
||||
/// @see https://docs.internetcomputer.org/references/ic-interface-spec/#system-api
|
||||
@@ -29,10 +27,35 @@ const ic0 = struct {
|
||||
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 stable64_size() u64;
|
||||
extern "ic0" fn stable64_grow(new_pages: u64) u64;
|
||||
extern "ic0" fn stable64_read(dst: u64, offset: u64, size: u64) void;
|
||||
extern "ic0" fn stable64_write(offset: u64, src: u64, size: u64) void;
|
||||
extern "ic0" fn trap(src: u32, size: u32) noreturn;
|
||||
extern "ic0" fn debug_print(src: u32, size: u32) void;
|
||||
};
|
||||
|
||||
/// Stable memory, addressed in bytes.
|
||||
const Stable = struct {
|
||||
const page = 64 * 1024;
|
||||
|
||||
pub fn size(_: *const Stable) u64 {
|
||||
return ic0.stable64_size() * page;
|
||||
}
|
||||
pub fn grow(_: *Stable, min_size: u64) !void {
|
||||
const pages = std.math.divCeil(u64, min_size, page) catch unreachable;
|
||||
const have = ic0.stable64_size();
|
||||
if (pages <= have) return;
|
||||
if (ic0.stable64_grow(pages - have) == std.math.maxInt(u64)) return error.StableMemoryFull;
|
||||
}
|
||||
pub fn read(_: *const Stable, offset: u64, out: []u8) void {
|
||||
ic0.stable64_read(@intFromPtr(out.ptr), offset, out.len);
|
||||
}
|
||||
pub fn write(_: *Stable, offset: u64, bytes: []const u8) void {
|
||||
ic0.stable64_write(offset, @intFromPtr(bytes.ptr), bytes.len);
|
||||
}
|
||||
};
|
||||
|
||||
pub const std_options: std.Options = .{
|
||||
.logFn = log,
|
||||
.enable_segfault_handler = false,
|
||||
@@ -59,100 +82,89 @@ fn trapWith(comptime what: []const u8, err: anyerror) noreturn {
|
||||
}
|
||||
|
||||
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;
|
||||
/// The Node lives here, at an address that never moves, until an upgrade.
|
||||
var node: Node = undefined;
|
||||
var stable: Stable = .{};
|
||||
var self_text: [64]u8 = undefined;
|
||||
|
||||
fn copied(comptime size: fn () callconv(.c) u32, comptime copy: fn (u32, u32, u32) callconv(.c) void) ![]u8 {
|
||||
const len = size();
|
||||
const bytes = try gpa.alloc(u8, len);
|
||||
copy(@intFromPtr(bytes.ptr), 0, len);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// The canister's principal, as text: its OCapN designator.
|
||||
fn designator() ![]const u8 {
|
||||
const id = try copied(ic0.canister_self_size, ic0.canister_self_copy);
|
||||
defer gpa.free(id);
|
||||
return principal.text(id, &self_text);
|
||||
}
|
||||
|
||||
/// Seeds this run's session keys from `nonce` and the time. Not secret, but
|
||||
/// sessions end with the run, and each run's root differs.
|
||||
fn sessionRoot(nonce: []const u8) [32]u8 {
|
||||
var root: [32]u8 = undefined;
|
||||
var kdf = std.crypto.hash.Blake3.initKdf("icp-ocapn-counter session root v1", .{});
|
||||
kdf.update(nonce);
|
||||
kdf.update(std.mem.asBytes(&ic0.time()));
|
||||
kdf.final(&root);
|
||||
return root;
|
||||
}
|
||||
|
||||
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);
|
||||
const arg = try copied(ic0.msg_arg_data_size, ic0.msg_arg_data_copy);
|
||||
defer gpa.free(arg);
|
||||
const entropy = candid.decodeBlob(arg) catch return error.InstallWith32BytesOfEntropy;
|
||||
if (entropy.len != 32) return error.InstallWith32BytesOfEntropy;
|
||||
try node.create(gpa, &stable, entropy[0..32].*, sessionRoot(entropy), try designator());
|
||||
}
|
||||
|
||||
// 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);
|
||||
fn postUpgrade() !void {
|
||||
try node.revive(gpa, &stable, sessionRoot(""), try designator());
|
||||
}
|
||||
|
||||
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, .{});
|
||||
const Verb = enum { start, deliver };
|
||||
/// The anonymous principal's one byte.
|
||||
const anonymous = 0x04;
|
||||
|
||||
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 exchange(comptime verb: Verb) !void {
|
||||
const caller = try copied(ic0.msg_caller_size, ic0.msg_caller_copy);
|
||||
defer gpa.free(caller);
|
||||
if (std.mem.eql(u8, caller, &.{anonymous})) return error.AnonymousCaller;
|
||||
const arg = try copied(ic0.msg_arg_data_size, ic0.msg_arg_data_copy);
|
||||
defer gpa.free(arg);
|
||||
const frames = try candid.decodeBlob(arg);
|
||||
var out: std.ArrayList(u8) = .empty;
|
||||
defer out.deinit(gpa);
|
||||
switch (verb) {
|
||||
.start => try node.start(caller, frames, &out),
|
||||
.deliver => try node.deliver(caller, frames, &out),
|
||||
}
|
||||
var reply: std.ArrayList(u8) = .empty;
|
||||
defer reply.deinit(gpa);
|
||||
try candid.encodeBlob(gpa, out.items, &reply);
|
||||
ic0.msg_reply_data_append(@intFromPtr(reply.items.ptr), reply.items.len);
|
||||
ic0.msg_reply();
|
||||
}
|
||||
|
||||
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 canisterPostUpgrade() callconv(.c) void {
|
||||
postUpgrade() catch |err| trapWith("post_upgrade", err);
|
||||
}
|
||||
|
||||
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);
|
||||
exchange(.start) catch |err| trapWith("start", err);
|
||||
}
|
||||
|
||||
fn canisterDeliver() callconv(.c) void {
|
||||
deliver() catch |err| trapWith("deliver", err);
|
||||
exchange(.deliver) catch |err| trapWith("deliver", err);
|
||||
}
|
||||
|
||||
comptime {
|
||||
@export(&canisterInit, .{ .name = "canister_init" });
|
||||
@export(&canisterPostUpgrade, .{ .name = "canister_post_upgrade" });
|
||||
@export(&canisterStart, .{ .name = "canister_update start" });
|
||||
@export(&canisterDeliver, .{ .name = "canister_update deliver" });
|
||||
}
|
||||
Reference in new issue
Block a user