diff --git a/src/ertp.zig b/src/ertp.zig new file mode 100644 index 0000000..254d1ff --- /dev/null +++ b/src/ertp.zig @@ -0,0 +1,208 @@ +//! A small ERTP (Electronic Rights Transfer Protocol) in Loam: mints, +//! issuers, purses, payments, and a shop that sells goods for a price. +//! Amounts are whole numbers of one kind of thing; an issuer's record is its +//! brand, so two assets are the same kind when their issuer edges match. +//! +//! Each purse, payment, and the shop's two purses are Loam records, so a +//! deposit or a purchase moves amounts between records in one transaction: +//! all of it commits, or none. +//! @see https://docs.agoric.com/guides/ertp/ + +const std = @import("std"); +const glowcap = @import("glowcap"); +const staged = @import("staged.zig"); + +const core = glowcap.loam.core; +const hosting = glowcap.loam.hosting; +const driver = glowcap.driver.core; + +pub const issuer_schema = 4; +pub const mint_schema = 5; +pub const purse_schema = 6; +pub const payment_schema = 7; +pub const shop_schema = 8; +const max_name = 16; + +pub const schemas = [_]core.Schema{ + .{ .id = issuer_schema, .version = 1, .max_payload = max_name, .max_edges = 0 }, + .{ .id = mint_schema, .version = 1, .max_payload = 0, .max_edges = 1 }, + .{ .id = purse_schema, .version = 1, .max_payload = 8, .max_edges = 1 }, + .{ .id = payment_schema, .version = 1, .max_payload = 8, .max_edges = 1 }, + .{ .id = shop_schema, .version = 1, .max_payload = 8, .max_edges = 2 }, +}; + +pub const behaviors = [_]hosting.Behavior{ + .{ .schema = issuer_schema, .invoke = issuer }, + .{ .schema = mint_schema, .invoke = mint }, + .{ .schema = purse_schema, .prepare = preparePurse, .invoke = purse }, + .{ .schema = payment_schema, .invoke = payment }, + .{ .schema = shop_schema, .prepare = prepareShop, .invoke = shop }, +}; + +/// `makeIssuerKit(name)`: a new kind of asset; answers its mint, which +/// alone can make more, and whose `getIssuer()` anyone may be given. +pub fn makeIssuerKit(call: *hosting.Call, args: []const driver.Value) !driver.Value { + if (args.len != 1 or args[0] != .string) return error.InvalidArguments; + if (args[0].string.len == 0 or args[0].string.len > max_name) return error.InvalidName; + return staged.stageWith(struct { + name: []const u8, + pub fn stage(self: *@This(), c: *hosting.Call, store: *core.Store) !driver.Value { + const brand = try store.allocateId(); + try store.putCopying(.{ .id = brand, .revision = 0, .schema = issuer_schema, .payload = self.name }, null); + const id = try store.allocateId(); + try store.putCopying(.{ .id = id, .revision = 0, .schema = mint_schema, .payload = &.{}, .edges = &.{.{ .target = brand }} }, null); + return .{ .capability = try c.propose(id) }; + } + }, call, .{ .name = try call.arena().dupe(u8, args[0].string) }); +} + +/// `makeShop(price, proceeds, stock)`: a shop that sells one unit from the +/// `stock` purse for exactly `price`, paid into the `proceeds` purse. +pub fn makeShop(call: *hosting.Call, args: []const driver.Value) !driver.Value { + if (args.len != 3 or args[0] != .integer or args[0].integer <= 0) return error.InvalidArguments; + return staged.stageWith(struct { + price: i64, + proceeds: core.ObjectId, + stock: core.ObjectId, + pub fn stage(self: *@This(), c: *hosting.Call, store: *core.Store) !driver.Value { + const id = try store.allocateId(); + const price = try staged.amountBytes(c.arena(), self.price); + try store.putCopying(.{ .id = id, .revision = 0, .schema = shop_schema, .payload = price, .edges = &.{ .{ .target = self.proceeds }, .{ .target = self.stock } } }, null); + return .{ .capability = try c.propose(id) }; + } + }, call, .{ .price = args[0].integer, .proceeds = try staged.target(call, args[1]), .stock = try staged.target(call, args[2]) }); +} + +/// A new payment of `amount` of the asset whose issuer is `brand`. +fn stagePayment(call: *hosting.Call, store: *core.Store, brand: core.ObjectId, amount: i64) !driver.Value { + const id = try store.allocateId(); + try store.putCopying(.{ .id = id, .revision = 0, .schema = payment_schema, .payload = try staged.amountBytes(call.arena(), amount), .edges = &.{.{ .target = brand }} }, null); + return .{ .capability = try call.propose(id) }; +} + +fn brandOf(view: core.RecordView) !core.ObjectId { + return (try view.edgeAt(0)).target; +} + +/// An issuer: `makeEmptyPurse()`. +fn issuer(call: *hosting.Call, state: core.RecordView, verb: []const u8, args: []const driver.Value) !driver.Value { + if (args.len != 0) return error.InvalidArguments; + if (!std.mem.eql(u8, verb, "makeEmptyPurse")) return error.NoSuchMethod; + return staged.stageWith(struct { + brand: core.ObjectId, + pub fn stage(self: *@This(), c: *hosting.Call, store: *core.Store) !driver.Value { + const id = try store.allocateId(); + try store.putCopying(.{ .id = id, .revision = 0, .schema = purse_schema, .payload = &@as([8]u8, @splat(0)), .edges = &.{.{ .target = self.brand }} }, null); + return .{ .capability = try c.propose(id) }; + } + }, call, .{ .brand = state.id }); +} + +/// A mint: `getIssuer()`, and `mintPayment(amount)`. +fn mint(call: *hosting.Call, state: core.RecordView, verb: []const u8, args: []const driver.Value) !driver.Value { + if (std.mem.eql(u8, verb, "getIssuer")) { + if (args.len != 0) return error.InvalidArguments; + return .{ .capability = try call.edge(0) }; + } else if (std.mem.eql(u8, verb, "mintPayment")) { + if (args.len != 1 or args[0] != .integer or args[0].integer <= 0) return error.InvalidArguments; + return staged.stageWith(struct { + brand: core.ObjectId, + amount: i64, + pub fn stage(self: *@This(), c: *hosting.Call, store: *core.Store) !driver.Value { + return stagePayment(c, store, self.brand, self.amount); + } + }, call, .{ .brand = try brandOf(state), .amount = args[0].integer }); + } else return error.NoSuchMethod; +} + +/// A payment holds its amount until deposited; it has no methods of its own. +fn payment(_: *hosting.Call, _: core.RecordView, _: []const u8, _: []const driver.Value) !driver.Value { + return error.NoSuchMethod; +} + +fn preparePurse(call: *hosting.Call, verb: []const u8, args: []const driver.Value) !hosting.Preparation { + const ids: []const core.ObjectId = if (std.mem.eql(u8, verb, "deposit") and args.len == 1) &.{try staged.target(call, args[0])} else &.{}; + return staged.Leases.prepare(call, ids); +} + +/// A purse: `getCurrentAmount()`, `withdraw(amount)` answering a payment, +/// and `deposit(payment)` answering the amount deposited. +fn purse(call: *hosting.Call, state: core.RecordView, verb: []const u8, args: []const driver.Value) !driver.Value { + const balance = try staged.amountOf(state); + if (std.mem.eql(u8, verb, "getCurrentAmount")) { + if (args.len != 0) return error.InvalidArguments; + return .{ .integer = balance }; + } else if (std.mem.eql(u8, verb, "withdraw")) { + if (args.len != 1 or args[0] != .integer or args[0].integer <= 0) return error.InvalidArguments; + if (args[0].integer > balance) return error.InsufficientFunds; + return staged.stageWith(struct { + amount: i64, + pub fn stage(self: *@This(), c: *hosting.Call, store: *core.Store) !driver.Value { + const view = c.view; + try staged.rewrite(store, c.arena(), view, try staged.amountBytes(c.arena(), try staged.amountOf(view) - self.amount)); + return stagePayment(c, store, try brandOf(view), self.amount); + } + }, call, .{ .amount = args[0].integer }); + } else if (std.mem.eql(u8, verb, "deposit")) { + if (args.len != 1) return error.InvalidArguments; + try checkPayment(try staged.Leases.view(call, 0), try brandOf(state)); + return staged.stageWith(struct { + pub fn stage(_: *@This(), c: *hosting.Call, store: *core.Store) !driver.Value { + const paid = try staged.Leases.view(c, 0); + const amount = try staged.amountOf(paid); + try spend(store, c.arena(), paid); + try staged.rewrite(store, c.arena(), c.view, try staged.amountBytes(c.arena(), try staged.amountOf(c.view) + amount)); + return .{ .integer = amount }; + } + }, call, .{}); + } else return error.NoSuchMethod; +} + +/// Refuse anything but an unspent payment of `brand`. +fn checkPayment(paid: core.RecordView, brand: core.ObjectId) !void { + if (paid.schema != payment_schema) return error.NotAPayment; + if (!std.meta.eql(try brandOf(paid), brand)) return error.WrongBrand; + if (try staged.amountOf(paid) == 0) return error.PaymentSpent; +} + +/// A spent payment keeps its record, with nothing in it. +fn spend(store: *core.Store, arena: std.mem.Allocator, paid: core.RecordView) !void { + try staged.rewrite(store, arena, paid, try staged.amountBytes(arena, 0)); +} + +fn prepareShop(call: *hosting.Call, verb: []const u8, args: []const driver.Value) !hosting.Preparation { + if (!std.mem.eql(u8, verb, "buy") or args.len != 1) return staged.Leases.prepare(call, &.{}); + const view = call.view; + return staged.Leases.prepare(call, &.{ try staged.target(call, args[0]), (try view.edgeAt(0)).target, (try view.edgeAt(1)).target }); +} + +/// A shop: `getPrice()`, and `buy(payment)` answering a payment of one unit +/// of the goods. The payment must be exactly the price. +fn shop(call: *hosting.Call, state: core.RecordView, verb: []const u8, args: []const driver.Value) !driver.Value { + const price = try staged.amountOf(state); + if (std.mem.eql(u8, verb, "getPrice")) { + if (args.len != 0) return error.InvalidArguments; + return .{ .integer = price }; + } else if (std.mem.eql(u8, verb, "buy")) { + if (args.len != 1) return error.InvalidArguments; + const paid = try staged.Leases.view(call, 0); + const proceeds = try staged.Leases.view(call, 1); + const stock = try staged.Leases.view(call, 2); + try checkPayment(paid, try brandOf(proceeds)); + if (try staged.amountOf(paid) != price) return error.WrongPrice; + if (try staged.amountOf(stock) < 1) return error.SoldOut; + return staged.stageWith(struct { + price: i64, + pub fn stage(self: *@This(), c: *hosting.Call, store: *core.Store) !driver.Value { + const arena = c.arena(); + const p = try staged.Leases.view(c, 0); + const in = try staged.Leases.view(c, 1); + const out = try staged.Leases.view(c, 2); + try spend(store, arena, p); + try staged.rewrite(store, arena, in, try staged.amountBytes(arena, try staged.amountOf(in) + self.price)); + try staged.rewrite(store, arena, out, try staged.amountBytes(arena, try staged.amountOf(out) - 1)); + return stagePayment(c, store, try brandOf(out), 1); + } + }, call, .{ .price = price }); + } else return error.NoSuchMethod; +} diff --git a/src/node.zig b/src/node.zig index 559d871..abd14b0 100644 --- a/src/node.zig +++ b/src/node.zig @@ -1,9 +1,10 @@ //! The canister's OCapN peer, apart from the Internet Computer's System API. //! Each caller principal has a home: a durable store of named objects in //! Loam on stable memory, which `fetch("home")` answers on that caller's -//! session. `fetch("makeCounter")` answers the one public counter maker. -//! Homes, counters, and the peer's identity survive an upgrade; CapTP -//! sessions live in the heap and do not. +//! session. Anyone may fetch the public `board`, a home all callers share, +//! and the makers `makeCounter`, `makeIssuerKit`, and `makeShop` (ertp.zig). +//! Homes and what they hold, and the peer's identity, survive an upgrade; +//! CapTP sessions live in the heap and do not. //! //! Nothing in a canister is secret from its subnet's nodes, so no authority //! here rests on an unguessable name: a home is reached only through the @@ -16,6 +17,7 @@ const std = @import("std"); const glowcap = @import("glowcap"); const link = @import("link.zig"); const StableLog = @import("stable_log.zig").StableLog; +const ertp = @import("ertp.zig"); const model = glowcap.ocapn.model; const core = glowcap.loam.core; @@ -29,12 +31,24 @@ const frame_cap = 64 * 1024; /// What `fetch` names to get the caller's home. pub const home_name = "home"; -/// What `fetch` names to get the counter maker. -pub const maker_name = "makeCounter"; -const maker_key: [16]u8 = blk: { - var key: [16]u8 = @splat(0); - @memcpy(key[0..maker_name.len], maker_name); - break :blk key; + +/// An object anyone may fetch by `name`: the record of `schema` indexed +/// under `name`, made the first time someone asks. +const Public = struct { + name: []const u8, + schema: u64, + + fn key(self: Public) [16]u8 { + var bytes: [16]u8 = @splat(0); + @memcpy(bytes[0..self.name.len], self.name); + return bytes; + } +}; +const public = [_]Public{ + .{ .name = "board", .schema = home_schema }, + .{ .name = "makeCounter", .schema = maker_schema }, + .{ .name = "makeIssuerKit", .schema = maker_schema }, + .{ .name = "makeShop", .schema = maker_schema }, }; const Header = extern struct { @@ -53,7 +67,7 @@ const max_name = 32; /// A home's payload: the 16-byte index key of its principal, then each name /// as a length byte and its bytes; edge `i` is the object named `i`th. const home_max_payload = 16 + max_names * (1 + max_name); -const schemas = [_]core.Schema{ +const schemas = ertp.schemas ++ [_]core.Schema{ .{ .id = counter_schema, .version = 1, .max_payload = 8, .max_edges = 0 }, .{ .id = home_schema, .version = 1, .max_payload = home_max_payload, .max_edges = max_names, .name_offset = 0 }, .{ .id = maker_schema, .version = 1, .max_payload = 16, .max_edges = 0, .name_offset = 0 }, @@ -66,7 +80,7 @@ const limits: core.Store.Limits = .{ .max_changes = 8, .staging_bytes = 8 * 1024, }; -const behaviors = [_]hosting.Behavior{ +const behaviors = ertp.behaviors ++ [_]hosting.Behavior{ .{ .schema = counter_schema, .invoke = counter }, .{ .schema = home_schema, .invoke = home }, .{ .schema = maker_schema, .invoke = maker }, @@ -151,10 +165,14 @@ const Keeping = struct { } }; -/// The maker: `make()` answers a new counter at zero. -fn maker(call: *hosting.Call, _: core.RecordView, verb: []const u8, args: []const driver.Value) !driver.Value { - if (args.len != 0) return error.InvalidArguments; +/// A public maker, which its index key names: `make(...)` answers what +/// `makeCounter`, `ertp.makeIssuerKit`, or `ertp.makeShop` makes. +fn maker(call: *hosting.Call, state: core.RecordView, verb: []const u8, args: []const driver.Value) !driver.Value { if (!std.mem.eql(u8, verb, "make")) return error.NoSuchMethod; + if (std.mem.eql(u8, state.payload, &public[2].key())) return ertp.makeIssuerKit(call, args); + if (std.mem.eql(u8, state.payload, &public[3].key())) return ertp.makeShop(call, args); + if (!std.mem.eql(u8, state.payload, &public[1].key())) return error.UnknownMaker; + if (args.len != 0) return error.InvalidArguments; const making = try call.arena().create(Making); making.* = .{ .call = call }; call.transaction = .{ .context = making, .stage = Making.stage }; @@ -186,7 +204,8 @@ pub fn Node(comptime Memory: type) type { return struct { const Self = @This(); const Log = StableLog(Memory); - const Fetched = enum { home, maker }; + /// The caller's home, or one of `public`. + const Fetched = union(enum) { home, public: Public }; const Waiting = struct { fetch: Host.PublicationFetch, what: Fetched }; gpa: std.mem.Allocator, @@ -197,13 +216,13 @@ pub fn Node(comptime Memory: type) type { attachment: *hosting.Attachment, /// Each caller's session, by principal. sessions: std.StringHashMapUnmanaged(*HostSession) = .empty, - /// Answers `fetch` of `home_name` and `maker_name`, once storage is - /// free to. + /// Answers `fetch` of `home_name` and of each of `public`, once + /// storage is free to. homes: Host.PublicationLookup, waiting: [8]?Waiting = @splat(null), lookups: u64 = 0, - /// Install: record the durable seed, make the maker, then serve. `designator` is the + /// Install: record the durable seed, then serve. `designator` is the /// canister's principal as text; `session_root` seeds this run's /// session keys. pub fn create(self: *Self, gpa: std.mem.Allocator, memory: *Memory, durable_seed: [32]u8, session_root: [32]u8, designator: []const u8) !void { @@ -211,8 +230,6 @@ pub fn Node(comptime Memory: type) type { const header: Header = .{ .durable_seed = durable_seed, .store_id = std.mem.readInt(u64, durable_seed[0..8], .little) }; memory.write(0, std.mem.asBytes(&header)); try self.open(gpa, memory, header, session_root, designator); - errdefer self.deinit(); - _ = try self.makeIndexed(maker_schema, maker_key); } /// After an upgrade: reopen what `create` recorded. @@ -302,10 +319,12 @@ pub fn Node(comptime Memory: type) type { return true; } - /// Take a fetch of `home_name` or `maker_name` to answer between turns. + /// Take a fetch of `home_name` or one of `public` to answer between turns. fn admit(context: *anyopaque, name: []const u8, fetch: Host.PublicationFetch) Host.PublicationLookup.Admission { const self: *Self = @ptrCast(@alignCast(context)); - const what: Fetched = if (std.mem.eql(u8, name, home_name)) .home else if (std.mem.eql(u8, name, maker_name)) .maker else return .unhandled; + const what: Fetched = if (std.mem.eql(u8, name, home_name)) .home else for (public) |item| { + if (std.mem.eql(u8, name, item.name)) break .{ .public = item }; + } else return .unhandled; for (&self.waiting) |*slot| if (slot.* == null) { slot.* = .{ .fetch = fetch, .what = what }; return .accepted; @@ -327,14 +346,13 @@ pub fn Node(comptime Memory: type) type { }; } - /// Answer each waiting fetch: the maker, or the caller's home, made - /// first if the caller has none. + /// Answer each waiting fetch with its record, made first if need be. fn answerHomes(self: *Self) !void { for (&self.waiting) |*slot| if (slot.*) |*waiting| { if (self.store.phase != .idle) return; const fetch = &waiting.fetch; const key = switch (waiting.what) { - .maker => maker_key, + .public => |item| item.key(), .home => homeKey(switch (fetch.origin()) { .peer => |peer| self.callerOf(peer), .local => null, @@ -345,7 +363,7 @@ pub fn Node(comptime Memory: type) type { }), }; const ref = try self.restoreIndexed(switch (waiting.what) { - .maker => maker_schema, + .public => |item| item.schema, .home => home_schema, }, key); defer self.host.releaseCapabilityTerminal(ref, null); @@ -360,7 +378,7 @@ pub fn Node(comptime Memory: type) type { return null; } - /// The record indexed under `key`, restored; a home is made on first use. + /// The record indexed under `key`, restored, and made on first use. fn restoreIndexed(self: *Self, schema: u64, key: [16]u8) !driver.Capability { const meta = self.store.metadata; self.lookups += 1; @@ -369,7 +387,7 @@ pub fn Node(comptime Memory: type) type { .name = .{ .schema = schema, .bytes = key }, })) { .found => |id| id, - .missing => if (schema == home_schema) try self.makeIndexed(schema, key) else return error.NotInstalled, + .missing => try self.makeIndexed(schema, key), .failed => |err| return err, }; const lease = switch (try self.store.acquire(id)) { diff --git a/src/pair_test.zig b/src/pair_test.zig index b681174..1072b4e 100644 --- a/src/pair_test.zig +++ b/src/pair_test.zig @@ -63,6 +63,9 @@ const Client = struct { session: *HostSession, caller: []const u8, started: bool = false, + /// Answers watched with `watch`, in order. + watched: [32]Answer = undefined, + watch_count: usize = 0, fn open(self: *Client, gpa: std.mem.Allocator, seed: u8, caller: []const u8) !void { self.* = .{ .host = try Host.init(gpa, @splat(seed), @splat(seed +% 1), Host.Options.init(.unchecked, frame_cap)), .session = undefined, .caller = caller }; @@ -97,6 +100,20 @@ const Client = struct { return calls; } + /// Watch `vow`'s answer. + fn watch(self: *Client, vow: u64) !*Answer { + const answer = &self.watched[self.watch_count]; + answer.* = .{}; + self.watch_count += 1; + try self.host.vowOn(vow, .{ .ctx = answer, .func = Answer.record }); + return answer; + } + + /// Carry frames until every watched answer settles, in one update call. + fn settle(self: *Client, gpa: std.mem.Allocator, node: *Node) !void { + try std.testing.expectEqual(@as(usize, 1), try self.flush(gpa, node, Settled{ .answers = self.watched[0..self.watch_count] })); + } + /// Send each verb, without waiting, to what `target` will settle to; /// watch each answer in `answers`. fn sendAll(self: *Client, target: u64, verbs: []const []const u8, answers: []Answer) !void { @@ -174,3 +191,111 @@ test "a caller's home keeps a counter across an upgrade; sessions start over" { _ = try bob.flush(gpa, &node, Settled{ .answers = answers[0..1] }); try std.testing.expect(answers[0].value == .broken); } + +/// `answer`'s reference, as an argument. +fn argRef(answer: *const Answer) !model.Argument { + return switch (answer.value) { + .reference => |r| .{ .reference = r }, + .broken => |why| { + std.debug.print("broken: {s}\n", .{why}); + return error.Broken; + }, + else => error.NotAReference, + }; +} + +fn int(answer: *const Answer) !i64 { + return switch (answer.value) { + .integer => |n| n, + .broken => |why| { + std.debug.print("broken: {s}\n", .{why}); + return error.Broken; + }, + else => error.NotAnInteger, + }; +} + +test "Alice buys a widget from Bob; purses survive an upgrade" { + const gpa = std.testing.allocator; + var memory: stable_log.TestMemory = .{ .gpa = gpa }; + defer memory.bytes.deinit(gpa); + var node: Node = undefined; + try node.create(gpa, &memory, @splat(0x51), @splat(0x52), canister_id); + + // Alice issues moola, mints herself 10, and posts the issuer. + var alice: Client = undefined; + try alice.open(gpa, 0x61, "alice"); + defer alice.host.deinit(); + _ = try alice.flush(gpa, &node, Opened{}); + const a = &alice; + const moola_mint = try send(a, try a.host.fetch(a.session, "makeIssuerKit"), "make", &.{.{ .string = "moola" }}); + const moola = try a.watch(try send(a, moola_mint, "getIssuer", &.{})); + const wallet = try a.watch(try send(a, try send(a, moola_mint, "getIssuer", &.{}), "makeEmptyPurse", &.{})); + const minted = try a.watch(try send(a, moola_mint, "mintPayment", &.{.{ .integer = 10 }})); + try a.settle(gpa, &node); + const a_board = try a.host.fetch(a.session, "board"); + const a_home = try a.host.fetch(a.session, "home"); + _ = try a.watch(try send(a, a_home, "init", &.{ .{ .string = "wallet" }, try argRef(wallet) })); + const filled = try a.watch(try a.host.send(a.session, wallet.value.reference, .{ .verb = "deposit", .args = &.{try argRef(minted)} })); + _ = try a.watch(try send(a, a_board, "init", &.{ .{ .string = "moola" }, try argRef(moola) })); + try a.settle(gpa, &node); + try std.testing.expectEqual(@as(i64, 10), try int(filled)); + + // Bob issues widgets, stocks one, and opens a shop selling it for 3 + // moola, paid into a moola purse he keeps at home. + var bob: Client = undefined; + try bob.open(gpa, 0x71, "bob"); + defer bob.host.deinit(); + _ = try bob.flush(gpa, &node, Opened{}); + const b = &bob; + const b_board = try b.host.fetch(b.session, "board"); + const widget_mint = try send(b, try b.host.fetch(b.session, "makeIssuerKit"), "make", &.{.{ .string = "widget" }}); + const widgets = try b.watch(try send(b, widget_mint, "getIssuer", &.{})); + const stock = try b.watch(try send(b, try send(b, widget_mint, "getIssuer", &.{}), "makeEmptyPurse", &.{})); + const widget = try b.watch(try send(b, widget_mint, "mintPayment", &.{.{ .integer = 1 }})); + const proceeds = try b.watch(try send(b, try send(b, b_board, "get", &.{.{ .string = "moola" }}), "makeEmptyPurse", &.{})); + try b.settle(gpa, &node); + const stocked = try b.watch(try b.host.send(b.session, stock.value.reference, .{ .verb = "deposit", .args = &.{try argRef(widget)} })); + const opened = try b.watch(try send(b, try b.host.fetch(b.session, "makeShop"), "make", &.{ .{ .integer = 3 }, try argRef(proceeds), try argRef(stock) })); + _ = try b.watch(try send(b, try b.host.fetch(b.session, "home"), "init", &.{ .{ .string = "proceeds" }, try argRef(proceeds) })); + _ = try b.watch(try send(b, b_board, "init", &.{ .{ .string = "widget" }, try argRef(widgets) })); + try b.settle(gpa, &node); + try std.testing.expectEqual(@as(i64, 1), try int(stocked)); + _ = try b.watch(try send(b, b_board, "init", &.{ .{ .string = "bobs-shop" }, try argRef(opened) })); + try b.settle(gpa, &node); + + // Alice pays 3 moola from her wallet and keeps the widget she gets. + const pay = try a.watch(try a.host.send(a.session, wallet.value.reference, .{ .verb = "withdraw", .args = &.{.{ .integer = 3 }} })); + const closet = try a.watch(try send(a, try send(a, a_board, "get", &.{.{ .string = "widget" }}), "makeEmptyPurse", &.{})); + const shop = try a.watch(try send(a, a_board, "get", &.{.{ .string = "bobs-shop" }})); + try a.settle(gpa, &node); + const goods = try a.watch(try a.host.send(a.session, shop.value.reference, .{ .verb = "buy", .args = &.{try argRef(pay)} })); + const again = try a.watch(try a.host.send(a.session, shop.value.reference, .{ .verb = "buy", .args = &.{try argRef(pay)} })); + _ = try a.watch(try send(a, a_home, "init", &.{ .{ .string = "closet" }, try argRef(closet) })); + try a.settle(gpa, &node); + try std.testing.expectEqualStrings("PaymentSpent", again.value.broken); + const got = try a.watch(try a.host.send(a.session, closet.value.reference, .{ .verb = "deposit", .args = &.{try argRef(goods)} })); + try a.settle(gpa, &node); + try std.testing.expectEqual(@as(i64, 1), try int(got)); + + // The upgrade: the heap goes, stable memory stays. + node.deinit(); + try node.revive(gpa, &memory, @splat(0x54), canister_id); + defer node.deinit(); + + // Each finds the purses kept at home, with what the sale left in them. + for ([_]struct { []const u8, []const []const u8, []const i64 }{ + .{ "alice", &.{ "wallet", "closet" }, &.{ 7, 1 } }, + .{ "bob", &.{"proceeds"}, &.{3} }, + }, 0..) |case, i| { + const caller, const names, const want = case; + var later: Client = undefined; + try later.open(gpa, 0x81 + @as(u8, @intCast(i)), caller); + defer later.host.deinit(); + _ = try later.flush(gpa, &node, Opened{}); + const home = try later.host.fetch(later.session, "home"); + for (names) |name| _ = try later.watch(try send(&later, try send(&later, home, "get", &.{.{ .string = name }}), "getCurrentAmount", &.{})); + try later.settle(gpa, &node); + for (want, later.watched[0..want.len]) |n, *balance| try std.testing.expectEqual(n, try int(balance)); + } +} diff --git a/src/staged.zig b/src/staged.zig new file mode 100644 index 0000000..640efdd --- /dev/null +++ b/src/staged.zig @@ -0,0 +1,110 @@ +//! Helpers for Loam behaviors that write more than their own payload: make +//! records, change other records, answer with what they made. + +const std = @import("std"); +const glowcap = @import("glowcap"); + +const core = glowcap.loam.core; +const hosting = glowcap.loam.hosting; +const driver = glowcap.driver.core; + +/// Have `plan.stage(call, store)` run in Loam's batch for `call`, and answer +/// what it returns. Records and capabilities can be made only there, so an +/// invocation that makes them returns `void` and this answers for it. +pub fn stageWith(comptime Plan: type, call: *hosting.Call, plan: Plan) !driver.Value { + const Holder = struct { + call: *hosting.Call, + plan: Plan, + answer: ?driver.Value = null, + + fn stage(context: *anyopaque, store: *core.Store) !void { + const self: *@This() = @ptrCast(@alignCast(context)); + self.answer = try self.plan.stage(self.call, store); + } + + fn result(c: *hosting.Call) !driver.Value { + const self: *@This() = @ptrCast(@alignCast(c.context.?)); + return self.answer orelse error.NotStaged; + } + }; + const holder = try call.arena().create(Holder); + holder.* = .{ .call = call, .plan = plan }; + call.transaction = .{ .context = holder, .stage = Holder.stage }; + call.result = Holder.result; + call.context = holder; + return .{ .void = {} }; +} + +/// A preparation that leases the records with these ids before invocation. +pub const Leases = struct { + pub const max = 4; + store: *core.Store, + ids: [max]core.ObjectId = undefined, + leases: [max]?core.Lease = @splat(null), + count: usize = 0, + + /// Lease `ids` for `call`; `view(call, i)` then reads the `i`th. + pub fn prepare(call: *hosting.Call, ids: []const core.ObjectId) !hosting.Preparation { + if (ids.len > max) return error.TooManyRecords; + const self = try call.arena().create(Leases); + self.* = .{ .store = call.attachment.store, .count = ids.len }; + @memcpy(self.ids[0..ids.len], ids); + return .{ .context = self, .advanceFn = advance, .completeFn = complete, .deinitFn = deinit }; + } + + /// The current view of the `index`th record `prepare` leased. + pub fn view(call: *hosting.Call, index: usize) !core.RecordView { + const self: *Leases = @ptrCast(@alignCast((call.preparation orelse return error.Unprepared).context)); + return self.store.currentView(self.leases[index] orelse return error.Unprepared); + } + + fn advance(context: *anyopaque) !hosting.Preparation.Step { + const self: *Leases = @ptrCast(@alignCast(context)); + for (self.ids[0..self.count], self.leases[0..self.count]) |id, *lease| if (lease.* == null) { + switch (try hosting.Preparation.acquire(self.store, id)) { + .ready => |ready| lease.* = ready, + .read => |read| return .{ .read = read }, + .waiting => return .waiting, + } + }; + return .ready; + } + + fn complete(context: *anyopaque, ticket: core.Ticket, result: core.ReadResult) !void { + const self: *Leases = @ptrCast(@alignCast(context)); + try self.store.completeRead(ticket, result); + } + + fn deinit(context: *anyopaque) void { + const self: *Leases = @ptrCast(@alignCast(context)); + for (&self.leases) |*slot| if (slot.*) |lease| { + self.store.release(lease) catch {}; + slot.* = null; + }; + } +}; + +/// The record a durable capability argument designates. +pub fn target(call: *hosting.Call, arg: driver.Value) !core.ObjectId { + if (arg != .capability) return error.InvalidArguments; + return (try call.attachment.capture(arg.capability)).target; +} + +/// A record's payload read as one little-endian i64. +pub fn amountOf(view: core.RecordView) !i64 { + if (view.payload.len != 8) return error.InvalidRecord; + return std.mem.readInt(i64, view.payload[0..8], .little); +} + +pub fn amountBytes(arena: std.mem.Allocator, amount: i64) ![]const u8 { + const bytes = try arena.alloc(u8, 8); + std.mem.writeInt(i64, bytes[0..8], amount, .little); + return bytes; +} + +/// `view` with a new payload, keeping its schema, edges, and rooting. +pub fn rewrite(store: *core.Store, arena: std.mem.Allocator, view: core.RecordView, payload: []const u8) !void { + const edges = try arena.alloc(core.Edge, view.edge_count); + for (edges, 0..) |*edge, i| edge.* = try view.edgeAt(i); + try store.putCopying(.{ .id = view.id, .revision = 0, .schema = view.schema, .schema_version = view.schema_version, .payload = payload, .edges = edges, .rooted = view.rooted }, view.revision); +}