Compare commits
2
Commits
b717ccaedf
...
9db91b1b9c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9db91b1b9c | ||
|
|
ed7d662d56 |
No files matched your search
@@ -40,12 +40,40 @@ value 2
|
||||
|
||||
With another key file, `use c1` breaks: that home is someone else's. `icp network stop` stops the local network. `zig build test` runs the same story in memory.
|
||||
|
||||
## Alice buys a widget from Bob
|
||||
|
||||
[ertp.zig](src/ertp.zig) is a small [ERTP](https://docs.agoric.com/guides/ertp/): mints, issuers, purses, payments, and a shop that sells one unit of stock for an exact price. A sale moves the payment, the proceeds, and the stock in one Loam transaction. With the network and canister from above:
|
||||
|
||||
```sh
|
||||
shop() { node client/shop.mjs http://127.0.0.1:4960 $ID "$@"; }
|
||||
shop alice.key mint # moola: 10 into Alice's wallet; issuer on the board
|
||||
shop bob.key open # widgets: 1 in stock; shop on the board at 3 moola
|
||||
shop alice.key buy
|
||||
shop alice.key buy # sold out: the payment goes back to the wallet
|
||||
icp canister install counter --mode upgrade -y
|
||||
shop alice.key balances
|
||||
shop bob.key balances
|
||||
```
|
||||
|
||||
```
|
||||
bought 1 widget into closet
|
||||
refunded 3 moola to wallet
|
||||
Error: answer 5 broke: SoldOut
|
||||
Canister counter installed successfully
|
||||
wallet 7
|
||||
closet 1
|
||||
proceeds 3
|
||||
```
|
||||
|
||||
(Update-call lines omitted. Alice's `balances` also reports `proceeds none`, and Bob's reports no wallet or closet: each home holds only its own.)
|
||||
|
||||
## Homes, not swiss numbers
|
||||
|
||||
Nodes on a canister's subnet can read its state, so a canister can't keep a swiss number secret. Authority here starts instead with the caller principal, whose signature the Internet Computer checks:
|
||||
|
||||
- `fetch("home")` answers the caller's own home, a durable store of named objects: `init(name, object)` and `get(name)`. It's made the first time the caller asks.
|
||||
- `fetch("makeCounter")` answers the one public maker; `make()` answers a fresh counter at zero.
|
||||
- `fetch("board")` answers a home every caller shares, where Alice and Bob post issuers and the shop.
|
||||
- `fetch("makeCounter")`, `fetch("makeIssuerKit")`, and `fetch("makeShop")` answer public makers; each one's `make(...)` answers what it makes.
|
||||
- The anonymous principal is refused, since everyone who uses it would share one home.
|
||||
|
||||
Homes, counters, and the canister's CapTP identity live in a [Loam](https://github.com/glowcap-org/glowcap) store whose engine ([stable_log.zig](src/stable_log.zig)) appends each committed transaction to stable memory, the part of a canister's state that survives an upgrade; `post_upgrade` replays it. CapTP sessions live in the heap, so an upgrade ends them, and a client starts a new one and fetches its home again.
|
||||
@@ -70,7 +98,8 @@ Homes, counters, and the canister's CapTP identity live in a [Loam](https://gith
|
||||
## Known gaps
|
||||
|
||||
- **The entropy is not secret** from the subnet's nodes, nor from whoever installs; nothing rests on it but the CapTP keys. A real deployment would draw it from `raw_rand` in a first call after install.
|
||||
- **One session per principal.** A second `start` from the same caller traps until an upgrade clears sessions; a client that loses its session can't reconnect with the same key.
|
||||
- **No removal or collection.** A home holds 8 names and can't drop one; Loam garbage collection never runs.
|
||||
- **One session per principal.** A new `start` from a caller closes the caller's old session.
|
||||
- **Not offer-safe.** A buyer hands over a payment and trusts the shop's code, which is right here because it's in the same vat; across vats this needs Zoe's escrow. The board is init-only, but anyone may post any name first.
|
||||
- **No removal or collection.** A home holds 8 names and can't drop one; spent payments keep their records; Loam garbage collection never runs.
|
||||
- **The canister pays for every call** and admits any signed caller; it should refuse strangers before doing work (`canister_inspect_message`).
|
||||
- **Third-party handoffs** need gift ids from entropy and dials to other peers; the canister refuses both.
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* @file Open a CapTP session to the canister as the principal of a key file.
|
||||
*/
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { HttpAgent, Actor } from '@icp-sdk/core/agent';
|
||||
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], []),
|
||||
});
|
||||
};
|
||||
|
||||
/** The seed in `path`, or a fresh one written there. */
|
||||
const keySeed = async path => {
|
||||
try {
|
||||
return new Uint8Array(await readFile(path));
|
||||
} catch (err) {
|
||||
if (err.code !== 'ENOENT') throw err;
|
||||
const seed = crypto.getRandomValues(new Uint8Array(32));
|
||||
await writeFile(path, seed, { mode: 0o600, flag: 'wx' });
|
||||
return seed;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Open a session to `canisterId` at `host` as the principal whose Ed25519
|
||||
* seed is in `keyFile` (32 bytes, made if missing), logging each update call.
|
||||
*
|
||||
* @param {string} host the replica, e.g. https://icp-api.io
|
||||
* @param {string} canisterId
|
||||
* @param {string} keyFile
|
||||
*/
|
||||
export const connect = async (host, canisterId, keyFile) => {
|
||||
const { hostname } = new URL(host);
|
||||
const agent = await HttpAgent.create({
|
||||
host,
|
||||
identity: Ed25519KeyIdentity.generate(await keySeed(keyFile)),
|
||||
// A local replica's root key is its own; mainnet's is built in.
|
||||
shouldFetchRootKey: hostname === '127.0.0.1' || hostname === 'localhost',
|
||||
});
|
||||
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));
|
||||
return openPeer({ module, seed, carry }, canisterId);
|
||||
};
|
||||
+2
-45
@@ -17,31 +17,7 @@ Each run's sends are pipelined: one update call after the handshake, plus
|
||||
one for init. HOST is the replica, e.g. http://127.0.0.1:4960, or
|
||||
https://icp-api.io.`;
|
||||
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { HttpAgent, Actor } from '@icp-sdk/core/agent';
|
||||
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], []),
|
||||
});
|
||||
};
|
||||
|
||||
/** The seed in `path`, or a fresh one written there. */
|
||||
const keySeed = async path => {
|
||||
try {
|
||||
return new Uint8Array(await readFile(path));
|
||||
} catch (err) {
|
||||
if (err.code !== 'ENOENT') throw err;
|
||||
const seed = crypto.getRandomValues(new Uint8Array(32));
|
||||
await writeFile(path, seed, { mode: 0o600, flag: 'wx' });
|
||||
return seed;
|
||||
}
|
||||
};
|
||||
import { connect } from './connect.js';
|
||||
|
||||
const main = async ([host, canisterId, keyFile, command, name, ...verbs]) => {
|
||||
if (!name || !['init', 'use'].includes(command)) {
|
||||
@@ -49,26 +25,7 @@ const main = async ([host, canisterId, keyFile, command, name, ...verbs]) => {
|
||||
process.exitCode = 2;
|
||||
return;
|
||||
}
|
||||
const { hostname } = new URL(host);
|
||||
const agent = await HttpAgent.create({
|
||||
host,
|
||||
identity: Ed25519KeyIdentity.generate(await keySeed(keyFile)),
|
||||
// A local replica's root key is its own; mainnet's is built in.
|
||||
shouldFetchRootKey: hostname === '127.0.0.1' || hostname === 'localhost',
|
||||
});
|
||||
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);
|
||||
const peer = await connect(host, canisterId, keyFile);
|
||||
console.log('session open');
|
||||
const home = peer.fetch('home');
|
||||
/** Send each verb without waiting, then print each answer. */
|
||||
|
||||
+13
-11
@@ -78,7 +78,10 @@ export const openPeer = async ({ module, seed, carry }, canisterId) => {
|
||||
const valueOf = slot => {
|
||||
const kind = wasm.client_result_kind(slot);
|
||||
if (kind === 0) throw Error(`answer ${slot} still pending after the canister went quiet`);
|
||||
if (kind === 3) throw Error(`answer ${slot} broke`);
|
||||
if (kind === 3) {
|
||||
check(wasm.client_result_broken(slot), 'broken');
|
||||
throw Error(`answer ${slot} broke: ${decoder.decode(staged())}`);
|
||||
}
|
||||
if (kind === 4) return undefined;
|
||||
return kind === 2 ? Number(wasm.client_result_integer(slot)) : { slot };
|
||||
};
|
||||
@@ -94,22 +97,21 @@ export const openPeer = async ({ module, seed, carry }, canisterId) => {
|
||||
/** @returns {Answer} the capability published as `name` */
|
||||
fetch: name => ({ slot: slotOf(withBytes(encoder.encode(name), (p, n) => wasm.client_fetch(p, n)), 'fetch') }),
|
||||
/**
|
||||
* Send `verb` to `target` with the arguments in `args`: at most one
|
||||
* string, then at most one settled reference.
|
||||
* Send `verb` to `target`, without waiting for it to settle.
|
||||
*
|
||||
* @param {Answer} target
|
||||
* @param {string} verb
|
||||
* @param {...(string | Answer)} args
|
||||
* @param {...(string | bigint | Answer)} args strings, integers, and
|
||||
* answers that have settled to references
|
||||
* @returns {Answer} `target`'s answer
|
||||
*/
|
||||
send: (target, verb, ...args) => {
|
||||
const text = args.find(arg => typeof arg === 'string');
|
||||
const object = args.find(arg => typeof arg === 'object');
|
||||
const status = withBytes(encoder.encode(verb), (verbPtr, verbLen) =>
|
||||
withBytes(encoder.encode(text ?? ''), (textPtr, textLen) =>
|
||||
wasm.client_send(target.slot, verbPtr, verbLen, textPtr, text === undefined ? -1 : textLen, object ? object.slot : -1),
|
||||
),
|
||||
);
|
||||
for (const arg of args) {
|
||||
if (typeof arg === 'string') check(withBytes(encoder.encode(arg), wasm.client_arg_text), 'argument');
|
||||
else if (typeof arg === 'bigint') check(wasm.client_arg_integer(arg), 'argument');
|
||||
else check(wasm.client_arg_reference(arg.slot), 'argument');
|
||||
}
|
||||
const status = withBytes(encoder.encode(verb), (p, n) => wasm.client_send(target.slot, p, n));
|
||||
return { slot: slotOf(status, 'send') };
|
||||
},
|
||||
flush,
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* @file Alice buys a widget from Bob, over ERTP in the canister.
|
||||
*/
|
||||
const HELP = `usage: shop.mjs HOST CANISTER_ID KEY_FILE STEP
|
||||
|
||||
Each STEP runs as the principal whose key is in KEY_FILE (made if missing):
|
||||
|
||||
mint issue moola, mint 10 into a purse kept at home as "wallet",
|
||||
and post the moola issuer on the board
|
||||
open issue widgets, stock one, and post a shop selling it for 3
|
||||
moola, paid into a purse kept at home as "proceeds"
|
||||
buy pay 3 moola from "wallet" for the widget, and keep it in a
|
||||
purse at home as "closet"
|
||||
balances show each purse kept at home
|
||||
|
||||
Run mint and buy as Alice, open as Bob.`;
|
||||
|
||||
import { connect } from './connect.js';
|
||||
|
||||
const steps = {
|
||||
async mint(peer, home, board) {
|
||||
const mint = peer.send(peer.fetch('makeIssuerKit'), 'make', 'moola');
|
||||
const moola = peer.send(mint, 'getIssuer');
|
||||
const wallet = peer.send(moola, 'makeEmptyPurse');
|
||||
const minted = peer.send(mint, 'mintPayment', 10n);
|
||||
await peer.flush();
|
||||
const deposited = peer.send(wallet, 'deposit', minted);
|
||||
peer.send(home, 'init', 'wallet', wallet);
|
||||
peer.send(board, 'init', 'moola', moola);
|
||||
await peer.flush();
|
||||
console.log('minted', peer.valueOf(deposited), 'moola into wallet');
|
||||
},
|
||||
async open(peer, home, board) {
|
||||
const mint = peer.send(peer.fetch('makeIssuerKit'), 'make', 'widget');
|
||||
const widgets = peer.send(mint, 'getIssuer');
|
||||
const stock = peer.send(widgets, 'makeEmptyPurse');
|
||||
const widget = peer.send(mint, 'mintPayment', 1n);
|
||||
const proceeds = peer.send(peer.send(board, 'get', 'moola'), 'makeEmptyPurse');
|
||||
await peer.flush();
|
||||
const stocked = peer.send(stock, 'deposit', widget);
|
||||
const shop = peer.send(peer.fetch('makeShop'), 'make', 3n, proceeds, stock);
|
||||
peer.send(home, 'init', 'proceeds', proceeds);
|
||||
peer.send(board, 'init', 'widget', widgets);
|
||||
await peer.flush();
|
||||
peer.send(board, 'init', 'bobs-shop', shop);
|
||||
await peer.flush();
|
||||
console.log('stocked', peer.valueOf(stocked), 'widget; shop open at 3 moola');
|
||||
},
|
||||
async buy(peer, home, board) {
|
||||
const wallet = peer.send(home, 'get', 'wallet');
|
||||
const pay = peer.send(wallet, 'withdraw', 3n);
|
||||
const shop = peer.send(board, 'get', 'bobs-shop');
|
||||
await peer.flush();
|
||||
const goods = peer.send(shop, 'buy', pay);
|
||||
await peer.flush();
|
||||
try {
|
||||
peer.valueOf(goods);
|
||||
} catch (err) {
|
||||
// The shop refused; the payment still holds what was withdrawn.
|
||||
const back = peer.send(wallet, 'deposit', pay);
|
||||
await peer.flush();
|
||||
console.log('refunded', peer.valueOf(back), 'moola to wallet');
|
||||
throw err;
|
||||
}
|
||||
const closet = peer.send(peer.send(board, 'get', 'widget'), 'makeEmptyPurse');
|
||||
await peer.flush();
|
||||
const got = peer.send(closet, 'deposit', goods);
|
||||
peer.send(home, 'init', 'closet', closet);
|
||||
await peer.flush();
|
||||
console.log('bought', peer.valueOf(got), 'widget into closet');
|
||||
},
|
||||
async balances(peer, home) {
|
||||
const names = ['wallet', 'closet', 'proceeds'];
|
||||
const amounts = names.map(name => peer.send(peer.send(home, 'get', name), 'getCurrentAmount'));
|
||||
await peer.flush();
|
||||
names.forEach((name, i) => {
|
||||
let amount;
|
||||
try {
|
||||
amount = peer.valueOf(amounts[i]);
|
||||
} catch (err) {
|
||||
amount = `none (${err.message})`;
|
||||
}
|
||||
console.log(name, amount);
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
const main = async ([host, canisterId, keyFile, step]) => {
|
||||
if (!Object.hasOwn(steps, step ?? '')) {
|
||||
console.error(HELP);
|
||||
process.exitCode = 2;
|
||||
return;
|
||||
}
|
||||
const peer = await connect(host, canisterId, keyFile);
|
||||
await steps[step](peer, peer.fetch('home'), peer.fetch('board'));
|
||||
};
|
||||
|
||||
main(process.argv.slice(2)).catch(err => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
+62
-24
@@ -41,7 +41,8 @@ const Result = union(enum) {
|
||||
pending,
|
||||
reference: model.Reference,
|
||||
integer: i64,
|
||||
broken,
|
||||
/// Why, as the canister said, or as this peer saw it.
|
||||
broken: []const u8,
|
||||
void,
|
||||
};
|
||||
|
||||
@@ -57,9 +58,10 @@ fn record(ctx: ?*anyopaque, resolution: actors.Resolution) void {
|
||||
.reference => |ref| .{ .reference = ref },
|
||||
.integer => |n| .{ .integer = n },
|
||||
.void => .void,
|
||||
else => .broken,
|
||||
else => .{ .broken = "unexpected value" },
|
||||
},
|
||||
.broken, .give => .broken,
|
||||
.broken => |reason| .{ .broken = gpa.dupe(u8, reason.detail) catch "out of memory" },
|
||||
.give => .{ .broken = "unexpected give" },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -146,28 +148,54 @@ export fn client_fetch(name: [*]const u8, len: usize) i32 {
|
||||
return watch(vow) catch |err| failSlot(err);
|
||||
}
|
||||
|
||||
/// Send `verb` to what slot `target` holds: a settled reference, or a
|
||||
/// pending answer, in which case the send rides the promise without waiting
|
||||
/// for it. The arguments are the string `text`, if `text_len` is not
|
||||
/// negative, then the reference slot `object` holds, if `object` is not
|
||||
/// negative. Returns the answer's slot.
|
||||
export fn client_send(target: u32, verb: [*]const u8, len: usize, text: [*]const u8, text_len: i32, object: i32) i32 {
|
||||
/// Arguments for the next `client_send`, staged by the `client_arg_*`
|
||||
/// exports. Strings are copied, and freed when the next send begins.
|
||||
var args: [8]model.Argument = undefined;
|
||||
var arg_count: usize = 0;
|
||||
var arg_texts: [8][]u8 = undefined;
|
||||
var text_count: usize = 0;
|
||||
|
||||
fn stageArg(arg: model.Argument) u32 {
|
||||
if (arg_count == args.len) return fail(error.TooManyArguments);
|
||||
args[arg_count] = arg;
|
||||
arg_count += 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// Stage a string argument.
|
||||
export fn client_arg_text(text: [*]const u8, len: usize) u32 {
|
||||
if (text_count == arg_texts.len) return fail(error.TooManyArguments);
|
||||
const copy = gpa.dupe(u8, text[0..len]) catch |err| return fail(err);
|
||||
arg_texts[text_count] = copy;
|
||||
text_count += 1;
|
||||
return stageArg(.{ .string = copy });
|
||||
}
|
||||
|
||||
/// Stage an integer argument.
|
||||
export fn client_arg_integer(n: i64) u32 {
|
||||
return stageArg(.{ .integer = n });
|
||||
}
|
||||
|
||||
/// Stage the settled reference slot `object` holds as an argument.
|
||||
export fn client_arg_reference(object: u32) u32 {
|
||||
if (object >= slot_count) return fail(error.NoSuchSlot);
|
||||
return switch (results[object]) {
|
||||
.reference => |ref| stageArg(.{ .reference = ref }),
|
||||
else => fail(error.NotAReference),
|
||||
};
|
||||
}
|
||||
|
||||
/// Send `verb`, with the staged arguments, to what slot `target` holds: a
|
||||
/// settled reference, or a pending answer, in which case the send rides the
|
||||
/// promise without waiting for it. Returns the answer's slot.
|
||||
export fn client_send(target: u32, verb: [*]const u8, len: usize) i32 {
|
||||
defer {
|
||||
for (arg_texts[0..text_count]) |text| gpa.free(text);
|
||||
text_count = 0;
|
||||
arg_count = 0;
|
||||
}
|
||||
if (target >= slot_count) return failSlot(error.NoSuchSlot);
|
||||
var args: [2]model.Argument = undefined;
|
||||
var count: usize = 0;
|
||||
if (text_len >= 0) {
|
||||
args[count] = .{ .string = text[0..@intCast(text_len)] };
|
||||
count += 1;
|
||||
}
|
||||
if (object >= 0) {
|
||||
if (object >= slot_count) return failSlot(error.NoSuchSlot);
|
||||
args[count] = switch (results[@intCast(object)]) {
|
||||
.reference => |ref| .{ .reference = ref },
|
||||
else => return failSlot(error.NotAReference),
|
||||
};
|
||||
count += 1;
|
||||
}
|
||||
const msg: actors.Message = .{ .verb = verb[0..len], .args = args[0..count] };
|
||||
const msg: actors.Message = .{ .verb = verb[0..len], .args = args[0..arg_count] };
|
||||
const vow = switch (results[target]) {
|
||||
.reference => |ref| host.send(session.?, ref, msg),
|
||||
.pending => host.vowSend(vows[target], msg),
|
||||
@@ -187,3 +215,13 @@ export fn client_result_integer(slot: u32) i64 {
|
||||
else => 0,
|
||||
};
|
||||
}
|
||||
|
||||
/// Stage why the answer in `slot` broke, for `client_out_ptr`.
|
||||
export fn client_result_broken(slot: u32) u32 {
|
||||
out.clearRetainingCapacity();
|
||||
switch (results[slot]) {
|
||||
.broken => |why| out.appendSlice(gpa, why) catch |err| return fail(err),
|
||||
else => {},
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
+208
@@ -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;
|
||||
}
|
||||
+54
-31
@@ -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.
|
||||
@@ -261,10 +278,15 @@ pub fn Node(comptime Memory: type) type {
|
||||
self.sessions.deinit(self.gpa);
|
||||
}
|
||||
|
||||
/// Open `caller`'s session with its `op:start-session` and append the
|
||||
/// canister's frames to `reply`.
|
||||
/// Open `caller`'s session with its `op:start-session`, closing any
|
||||
/// it had, and append the canister's frames to `reply`.
|
||||
pub fn start(self: *Self, caller: []const u8, frames: []const u8, reply: *std.ArrayList(u8)) !void {
|
||||
if (self.sessions.contains(caller)) return error.SessionAlreadyStarted;
|
||||
if (self.sessions.fetchRemove(caller)) |old| {
|
||||
defer self.gpa.free(old.key);
|
||||
try self.host.transportClosed(old.value, "replaced by a new start");
|
||||
try link.settle(&self.host, .flush);
|
||||
try self.host.releaseSession(old.value);
|
||||
}
|
||||
const key = try self.gpa.dupe(u8, caller);
|
||||
errdefer self.gpa.free(key);
|
||||
const session = try self.host.openAcceptedAdvertised(link.transport);
|
||||
@@ -302,10 +324,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 +351,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 +368,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 +383,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 +392,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)) {
|
||||
|
||||
@@ -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 {
|
||||
@@ -164,6 +181,16 @@ test "a caller's home keeps a counter across an upgrade; sessions start over" {
|
||||
try std.testing.expectEqual(@as(usize, 1), try again.flush(gpa, &node, Settled{ .answers = answers[0..2] }));
|
||||
try expectCounts(&.{ 3, 3 }, &answers);
|
||||
|
||||
// A new start from Alice closes her old session and opens another.
|
||||
var third: Client = undefined;
|
||||
try third.open(gpa, 0x63, "alice");
|
||||
defer third.host.deinit();
|
||||
try std.testing.expectEqual(@as(usize, 1), try third.flush(gpa, &node, Opened{}));
|
||||
answers = @splat(.{});
|
||||
try third.sendAll(try send(&third, try third.host.fetch(third.session, "home"), "get", &.{.{ .string = "c1" }}), &.{"incr"}, &answers);
|
||||
_ = try third.flush(gpa, &node, Settled{ .answers = answers[0..1] });
|
||||
try expectCounts(&.{4}, &answers);
|
||||
|
||||
// Bob's home is his own: nothing under "c1" there.
|
||||
var bob: Client = undefined;
|
||||
try bob.open(gpa, 0x71, "bob");
|
||||
@@ -174,3 +201,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));
|
||||
}
|
||||
}
|
||||
+110
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user