//! 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. //! //! 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 candid = @import("candid.zig"); const principal = @import("principal.zig"); 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 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 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, .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; /// 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 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()); } fn postUpgrade() !void { try node.revive(gpa, &stable, sessionRoot(""), try designator()); } const Verb = enum { start, deliver }; /// The anonymous principal's one byte. const anonymous = 0x04; 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 canisterPostUpgrade() callconv(.c) void { postUpgrade() catch |err| trapWith("post_upgrade", err); } fn canisterStart() callconv(.c) void { exchange(.start) catch |err| trapWith("start", err); } fn canisterDeliver() callconv(.c) void { 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" }); }