@inversealtruism/cairnx-core 0.2.9 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,56 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.2.11
4
+
5
+ - `isIndex` is exported from the root: a position or height as CONVENTION section 33 takes it, a safe integer >= 0.
6
+ cairnx-replica's Scanner checks a served merkle proof's position with it. `resolve()` is unchanged.
7
+ - `test/vectors/cases-rules.json` grows from 5 to 12 vectors (`conformance/gen-rule-vectors.mjs`; the first 5 keep
8
+ their bytes), for two live rules that no vector, the replay corpus or the fuzz reached: a partial offer's remainder
9
+ below its min is bought by paying exactly the remainder (CONVENTION section 19), and of two reveals of a name with
10
+ one commit height and one position the lower id wins, in both orders of mining, at each of the contest's three
11
+ sites: the V25 reservation, the registration below V25 and the V26 recapture reservation. Both the
12
+ TypeScript resolver and the Python reference replay them (`test/vectors.test.ts`, `conformance/crosscheck-resolve.mjs`).
13
+ `test/preflight.test.ts` compares `previewFill` with the resolver at such a tail. The rules are unchanged.
14
+ - `fillEndorsement` refuses, at a tip at or above `LEGACY_HOLD_SUNSET_HEIGHT` (60,044), a fill of an open CSD offer
15
+ whose target is the offer id. From that height no claim hold made before V28 is live, so `resolve()` refuses every
16
+ such fill (`FILL_WRONG_TARGET` or `FILL_NO_LIVE_CLAIM`) after the payment moved, while `fillEndorsement` endorsed it
17
+ when the served offer showed a hold by the caller without a reservation. Only the answer on fills the chain
18
+ refuses changes: over the 54 cases of cairn-sdk 0.9.1's review (offer shapes at the sunset and at 148,000, a
19
+ reservation's fclaim target with ids in either case, taker-bound offers and a maker's RFQ answer, token wants, a
20
+ name sale, a partial offer's second fill, the last legacy claim below the sunset, and 24 served lies), 16 verdicts
21
+ change, each from endorsed to refused on a fill `resolve()` refuses, and none on a fill it applies
22
+ (`test/preflight.test.ts` checks the rule against `resolve()` at both tips and below the sunset). Consumers that
23
+ carry this rule themselves (cairn-sdk 0.9.1's `preverifyOffer`, the wallet's fill preflight) may drop it once they
24
+ take this version. The deprecated `fillIsSafe` keeps its frozen verdicts.
25
+ - Pins `@inversealtruism/csd-codec` 0.1.19 (`verifyMerkleProof` proves the position).
26
+
27
+ ## 0.2.10
28
+
29
+ - A held replay context: `newReplayContext()` keeps `resolve()`'s fold between tips. `advance(toHeight, events)`
30
+ applies the whole blocks above the context's height, in apply order; `stateAt(t)`, at that height, answers in place.
31
+ It takes an event whose height is a safe integer (`isChainHeight`), whose position is a safe integer >= 0 and whose
32
+ id is a string, as CONVENTION section 33 builds them. For inputs made of plain values (what JSON carries), its answer
33
+ at t is what `resolve()` returns over the same events at t, and an answer handed out earlier does not change later.
34
+ Any other event, and a height or tip outside `isChainHeight`, is refused with a `ReplayContextRefusal` ("domain")
35
+ and the caller replays with `resolve()`. `advance` reads its events once and keeps a one-level copy of each, so a
36
+ write into an event after the call changes no later answer. The other refusals, each thrown before any write:
37
+ "order" (a target below the height, an event at or below it or above the target; a new context stands at -1, so it
38
+ refuses a negative height, which `resolve()` skips below activation), "tip" (an answer off the height), "broken"
39
+ (any call after the replay threw inside `advance` or `stateAt`, where `resolve()` throws too), "sloppy" (a build
40
+ that runs the module in sloppy mode, where a write to a frozen shared part would be dropped instead of throwing). The
41
+ context keeps no earlier state: a reorg that removes an applied block costs one full replay.
42
+ `isChainHeight`, the one domain rule (`Number.isSafeInteger`), is exported and read by `resolve()`'s fold and by the
43
+ context. `resolve()` is unchanged: the seal against 0.2.9 finds its whole result identical over each input of
44
+ 0.2.9's proof, and walks a held context through 26,303 of them, 1,270,287 answers each equal to `resolve()`
45
+ (`CONSENSUS_CHANGES.md`). `test/replay-context.test.ts` compares the context with `resolve()` at every height of the
46
+ sweep streams (D, over 284,000 blocks, at its dense tips; the malformed ones until refused), every event height of
47
+ the replay corpus and the growth streams at 500, with answers re-read after later advances and written over. On the
48
+ replay corpus (1,133 events in 774 blocks), advancing one block and answering at it, 774 times, took 2.81 percent of
49
+ the time of a `resolve()` per block (medians of five interleaved runs on a host at load 30 to 40; the build without
50
+ the copy and the position and id checks measured 4.41 percent in the same runs, and the runs' ranges overlap, so the
51
+ two figures do not rank the builds); those checks and the copy alone take 0.108 ms over the whole corpus.
52
+
53
+ ## 0.2.9
4
54
 
5
55
  - The replay runs as a fold (one step per event, an end at the tip that alone reads the tip) and its expiry sweep
6
56
  applies each expiry at the first height it is due, one batch per such height in ascending order, where 0.2.8 applied
package/CONVENTION.md CHANGED
@@ -252,6 +252,11 @@ times, is outside that statement. Outside the domain the result is not consensus
252
252
  differently (0.2.4 and 0.2.7 on a string height), so a caller checks that event heights and the tip are safe integers
253
253
  before the call.
254
254
 
255
+ A resolver may also hold its replay between tips and answer in place at the last height it applied, as cairnx-core's
256
+ held context does from 0.2.10: inside the domain its answer at t equals a full replay to t, because the answer's sweep
257
+ at `t + 1` is one more sweep height, and the next block's flush and sweep follow it as they would follow the block
258
+ before; outside the domain the heights at which sweeps run matter, so such a resolver replays in full.
259
+
255
260
  **Canonical state (format 2, normative):** the canonical surface is
256
261
  `{tipHeight, tokens, balances, names, offers, bids, feesPaid}`: the event log is excluded.
257
262
  Serialization is **canonical JSON** in the state form of §5.1: object keys sorted in ordinal (code-unit) order at every
package/README.md CHANGED
@@ -322,6 +322,20 @@ For inputs made of plain values (what JSON carries), a release that changes no r
322
322
  what the previous core returned and throws where it threw, and only event heights and a tip that are safe integers,
323
323
  as a chain produces them, are consensus, so check both before the call (`CONVENTION.md` section 5).
324
324
 
325
+ A replica or a server that answers at each new block can hold the replay instead of rebuilding it: `const ctx =
326
+ newReplayContext()`, then at each new height `h`, `ctx.advance(h, events)` with the events of the blocks above
327
+ `ctx.height` up to `h` (only those: an event at or below `ctx.height` is refused), and `ctx.stateAt(h)`. In the scope
328
+ above, its answer at a height is what `resolve()` returns over the same events there, for every event it takes: one
329
+ whose height is a safe integer (`isChainHeight`), whose position is a safe integer >= 0 and whose id is a string, as
330
+ the rule of `CONVENTION.md` section 33 builds them. It refuses any other event, and a height or tip that
331
+ `isChainHeight` rejects, with a `ReplayContextRefusal` before anything is written, and the caller replays with
332
+ `resolve()`. It keeps a copy of each event's own fields, so a later write into an event already given changes no
333
+ answer. A reorg that removes an applied block means a new context. A new context stands at height -1, below the
334
+ chain's first block, so it refuses a negative height ("order"), which `resolve()` skips below activation. It refuses
335
+ to start in a build that runs it in sloppy mode: it shares frozen parts with the answers it returns and relies on a
336
+ write to a frozen part throwing, so that a write the replay makes there breaks the context instead of being dropped
337
+ silently.
338
+
325
339
  ### What a resolver result proves
326
340
 
327
341
  - Display: an answer read from someone's API. It is worth the trust you place in that API.
package/dist/index.cjs CHANGED
@@ -93,6 +93,7 @@ __export(index_exports, {
93
93
  REG_FINALIZE_GRACE_BLOCKS: () => REG_FINALIZE_GRACE_BLOCKS,
94
94
  RESERVED_NAMES: () => RESERVED_NAMES,
95
95
  RecordError: () => RecordError,
96
+ ReplayContextRefusal: () => ReplayContextRefusal,
96
97
  SALT_RE: () => SALT_RE,
97
98
  SCAN_MARGIN: () => SCAN_MARGIN,
98
99
  SCORE_CANCEL: () => SCORE_CANCEL,
@@ -156,6 +157,8 @@ __export(index_exports, {
156
157
  fillTargetId: () => fillTargetId,
157
158
  finalizeWinnerCheck: () => finalizeWinnerCheck,
158
159
  hasLiveClaim: () => hasLiveClaim,
160
+ isChainHeight: () => isChainHeight,
161
+ isIndex: () => isIndex,
159
162
  isName: () => isName,
160
163
  isNameGive: () => isNameGive,
161
164
  isOpenClaimLane: () => isOpenClaimLane,
@@ -173,6 +176,7 @@ __export(index_exports, {
173
176
  nameSet: () => nameSet,
174
177
  nameView: () => nameView,
175
178
  nameXfer: () => nameXfer,
179
+ newReplayContext: () => newReplayContext,
176
180
  offer: () => offer,
177
181
  offerCancelAll: () => offerCancelAll,
178
182
  offerExpiryHeightOf: () => offerExpiryHeightOf,
@@ -206,6 +210,7 @@ var import_csd_codec = require("@inversealtruism/csd-codec");
206
210
  var DOMAIN = "cairnx:v1";
207
211
  var ACTIVATION_HEIGHT = 29860;
208
212
  var beforeActivation = (height) => height < ACTIVATION_HEIGHT;
213
+ var isChainHeight = (height) => Number.isSafeInteger(height);
209
214
  var V11_HEIGHT = 29960;
210
215
  var V12_HEIGHT = 30300;
211
216
  var V13_HEIGHT = 31100;
@@ -2028,7 +2033,7 @@ function replay(events, tipHeight, opts = {}) {
2028
2033
  for (const e of [...events].sort(applyOrder)) fold.apply(e);
2029
2034
  return fold.finish(tipHeight);
2030
2035
  }
2031
- function createFold(opts) {
2036
+ function createFold(opts = {}) {
2032
2037
  const seenIds = /* @__PURE__ */ new Set();
2033
2038
  const store = createStore(opts);
2034
2039
  const c = createContext(store);
@@ -2039,7 +2044,7 @@ function createFold(opts) {
2039
2044
  c.pendingCancels = [];
2040
2045
  };
2041
2046
  const inDomain = (height) => {
2042
- if (!Number.isSafeInteger(height)) store.endSplit();
2047
+ if (!isChainHeight(height)) store.endSplit();
2043
2048
  };
2044
2049
  const apply = (ev) => {
2045
2050
  inDomain(ev.height);
@@ -2185,15 +2190,242 @@ function canonicalState(s) {
2185
2190
  return JSON.stringify(sortKeys(data));
2186
2191
  }
2187
2192
 
2188
- // src/client.ts
2193
+ // src/events.ts
2189
2194
  var import_csd_codec3 = require("@inversealtruism/csd-codec");
2195
+
2196
+ // src/paidto.ts
2197
+ function paidToFromOutputs(outputs) {
2198
+ const m = /* @__PURE__ */ Object.create(null);
2199
+ for (const o of outputs) {
2200
+ if (typeof o.value !== "number" || !Number.isSafeInteger(o.value) || o.value < 0) continue;
2201
+ m[o.addr] = (BigInt(m[o.addr] ?? "0") + BigInt(o.value)).toString();
2202
+ }
2203
+ return m;
2204
+ }
2205
+ function burnedPayment(paidTo, payer, offer2) {
2206
+ const read = (addr) => addr === payer ? 0n : ptAmt(paidTo?.[addr]);
2207
+ let counterparty = 0n;
2208
+ if (offer2) {
2209
+ for (const addr of /* @__PURE__ */ new Set([offer2.seller, offer2.want.payto])) if (addr !== TREASURY_ADDR) counterparty += read(addr);
2210
+ }
2211
+ return { treasury: read(TREASURY_ADDR), counterparty };
2212
+ }
2213
+
2214
+ // src/events.ts
2215
+ var CAIRNX_EVENT_RULE = Object.freeze({ domain: DOMAIN, activationHeight: ACTIVATION_HEIGHT });
2216
+ var fail = (what) => {
2217
+ throw new Error(`events rule: ${what}`);
2218
+ };
2219
+ var isIndex = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
2220
+ function hexOf(v, bytes, what) {
2221
+ const h = typeof v === "string" && v.startsWith("0x") ? v.slice(2) : v;
2222
+ if (typeof h !== "string" || h.length !== bytes * 2 || !/^[0-9a-fA-F]*$/.test(h)) return fail(`${what} is not ${bytes}-byte hex`);
2223
+ return "0x" + h.toLowerCase();
2224
+ }
2225
+ function u64Of(v, what) {
2226
+ if (typeof v === "bigint" && v >= 0n && v < 1n << 64n) return v;
2227
+ if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 2 ** 53) return v;
2228
+ if (typeof v === "number" && Number.isInteger(v) && v > 2 ** 53) return fail(`${what} above 2^53 must be passed as a bigint`);
2229
+ return fail(`${what} is not a u64`);
2230
+ }
2231
+ function u32Of(v, what) {
2232
+ return typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4294967295 ? v : fail(`${what} is not a u32`);
2233
+ }
2234
+ function checkRule(rule) {
2235
+ const d = rule?.domain;
2236
+ if (typeof d !== "string" || d === "" || !(0, import_csd_codec3.isWellFormedUtf16)(d) || d.includes("\0") || d.includes(""))
2237
+ fail("the rule's domain must be non-empty, well-formed text without U+0000 or U+0001");
2238
+ if (!isIndex(rule.activationHeight)) fail("the rule's activation height must be a safe integer >= 0");
2239
+ }
2240
+ var kindOf = (app) => {
2241
+ const t = app?.type;
2242
+ return t === "None" ? "none" : t === "Propose" ? "propose" : t === "Attest" ? "attest" : fail(`unknown app type ${String(t)}`);
2243
+ };
2244
+ var domainOf = (app) => typeof app.domain === "string" ? app.domain : fail("a Propose domain is not text");
2245
+ function paidToOf(outputs) {
2246
+ if (!Array.isArray(outputs)) fail("outputs is not a list");
2247
+ const counted = [];
2248
+ for (const o of outputs) {
2249
+ const addr = hexOf(o?.scriptPubkey, 20, "script_pubkey"), value = u64Of(o?.value, "output value");
2250
+ if (value <= Number.MAX_SAFE_INTEGER) counted.push({ addr, value: Number(value) });
2251
+ }
2252
+ return paidToFromOutputs(counted);
2253
+ }
2254
+ function eventOfTx(t, height, author, rule = CAIRNX_EVENT_RULE) {
2255
+ checkRule(rule);
2256
+ if (!isIndex(height)) fail("height is not a safe integer >= 0");
2257
+ if (!isIndex(t?.pos)) fail("pos is not a safe integer >= 0");
2258
+ const txid = hexOf(t.txid, 32, "txid");
2259
+ const app = t.tx?.app;
2260
+ const kind = kindOf(app);
2261
+ if (kind === "none" || height < rule.activationHeight) return null;
2262
+ if (t.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2263
+ if (kind === "propose" && domainOf(app) !== rule.domain) return null;
2264
+ const paidTo = paidToOf(t.tx.outputs), who = hexOf(author, 20, "author");
2265
+ if (kind === "propose") {
2266
+ const p = app;
2267
+ const uri = p.uri;
2268
+ if (typeof uri !== "string" || !(0, import_csd_codec3.isWellFormedUtf16)(uri)) return fail("uri is not well-formed text");
2269
+ const e = u64Of(p.expiresEpoch, "expiresEpoch");
2270
+ return {
2271
+ kind: "propose",
2272
+ id: txid,
2273
+ proposer: who,
2274
+ uri: uri.replaceAll("\0", ""),
2275
+ payloadHash: hexOf(p.payloadHash, 32, "payloadHash"),
2276
+ expiresEpoch: e <= Number.MAX_SAFE_INTEGER ? Number(e) : 2 ** 53,
2277
+ height,
2278
+ pos: t.pos,
2279
+ paidTo
2280
+ };
2281
+ }
2282
+ const a = app;
2283
+ return {
2284
+ kind: "attest",
2285
+ txid,
2286
+ proposalId: hexOf(a.proposalId, 32, "proposalId"),
2287
+ attester: who,
2288
+ score: u32Of(a.score, "score"),
2289
+ confidence: u32Of(a.confidence, "confidence"),
2290
+ height,
2291
+ pos: t.pos,
2292
+ paidTo
2293
+ };
2294
+ }
2295
+ function blockMembers(height, txs, sofar, rule = CAIRNX_EVENT_RULE) {
2296
+ checkRule(rule);
2297
+ if (!isIndex(height)) fail("height is not a safe integer >= 0");
2298
+ if (height < rule.activationHeight) return [];
2299
+ if (!Array.isArray(txs)) fail("txs is not a list");
2300
+ const ids = /* @__PURE__ */ new Set(), proposals = /* @__PURE__ */ new Set();
2301
+ const read = [];
2302
+ let last = -1;
2303
+ for (const item of txs) {
2304
+ if (!isIndex(item?.pos) || item.pos <= last) fail("positions are not safe integers >= 0 in strictly increasing order");
2305
+ last = item.pos;
2306
+ const id = hexOf(item.txid, 32, "txid");
2307
+ if (ids.has(id)) fail(`txid ${id} is repeated in the block`);
2308
+ ids.add(id);
2309
+ const kind = kindOf(item.tx?.app);
2310
+ if (kind === "none") continue;
2311
+ if (item.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2312
+ if (kind === "propose") {
2313
+ if (domainOf(item.tx.app) !== rule.domain || sofar.eventIds.has(id)) continue;
2314
+ proposals.add(id);
2315
+ read.push({ item, kind, id });
2316
+ } else read.push({ item, kind, id, proposal: hexOf(item.tx.app.proposalId, 32, "proposalId") });
2317
+ }
2318
+ return read.filter((r) => r.kind === "propose" || !sofar.eventIds.has(r.id) && (sofar.proposeIds.has(r.proposal) || proposals.has(r.proposal))).map((r) => ({ kind: r.kind, item: r.item }));
2319
+ }
2320
+ function blockEvents(height, txs, sofar, authors, rule = CAIRNX_EVENT_RULE) {
2321
+ const members = blockMembers(height, txs, sofar, rule);
2322
+ if (!Array.isArray(authors) || authors.length !== members.length) fail(`the block has ${members.length} members, not ${authors?.length} authors`);
2323
+ const events = members.map((m, i) => eventOfTx(m.item, height, authors[i], rule) ?? fail("a member mapped to no event"));
2324
+ return [...events.filter((e) => e.kind === "propose"), ...events.filter((e) => e.kind === "attest")];
2325
+ }
2326
+
2327
+ // src/replay-context.ts
2328
+ var ReplayContextRefusal = class extends Error {
2329
+ code;
2330
+ constructor(code, message) {
2331
+ super(message);
2332
+ this.name = "ReplayContextRefusal";
2333
+ this.code = code;
2334
+ }
2335
+ };
2336
+ var strictCode = /* @__PURE__ */ (function() {
2337
+ return this === void 0;
2338
+ })();
2339
+ function newReplayContext() {
2340
+ if (!strictCode) throw new ReplayContextRefusal("sloppy", "this build runs cairnx-core in sloppy mode, where a write to a frozen object is ignored");
2341
+ const fold = createFold();
2342
+ let height = -1;
2343
+ let broken = false;
2344
+ const live = () => {
2345
+ if (broken) throw new ReplayContextRefusal("broken", "the replay threw inside advance or stateAt; replay with resolve()");
2346
+ };
2347
+ return {
2348
+ get height() {
2349
+ return height;
2350
+ },
2351
+ advance(toHeight, events) {
2352
+ live();
2353
+ if (!isChainHeight(toHeight)) throw new ReplayContextRefusal("domain", `target height ${String(toHeight)} is not a safe integer`);
2354
+ const batch = [...events].map((e) => ({ ...e }));
2355
+ for (const e of batch) {
2356
+ if (!isChainHeight(e.height)) throw new ReplayContextRefusal("domain", `event height ${String(e.height)} is not a safe integer`);
2357
+ if (!isIndex(e.pos)) throw new ReplayContextRefusal("domain", `event position ${String(e.pos)} is not a safe integer >= 0`);
2358
+ if (typeof eventId(e) !== "string") throw new ReplayContextRefusal("domain", `an event id of type ${typeof eventId(e)}`);
2359
+ }
2360
+ if (toHeight < height) throw new ReplayContextRefusal("order", `target ${toHeight} is below the context's height ${height}`);
2361
+ for (const e of batch) {
2362
+ if (e.height <= height || e.height > toHeight) throw new ReplayContextRefusal("order", `event height ${e.height} is outside (${height}, ${toHeight}]`);
2363
+ }
2364
+ batch.sort(applyOrder);
2365
+ try {
2366
+ for (const e of batch) fold.apply(e);
2367
+ } catch (err) {
2368
+ broken = true;
2369
+ throw err;
2370
+ }
2371
+ height = toHeight;
2372
+ },
2373
+ stateAt(tipHeight) {
2374
+ live();
2375
+ if (tipHeight !== height) throw new ReplayContextRefusal("tip", `an answer at ${String(tipHeight)} from a context at ${height}`);
2376
+ try {
2377
+ return detach(fold.finish(tipHeight));
2378
+ } catch (err) {
2379
+ broken = true;
2380
+ throw err;
2381
+ }
2382
+ }
2383
+ };
2384
+ }
2385
+ var freezeDeep = (v) => {
2386
+ if (v === null || typeof v !== "object" || Object.isFrozen(v)) return;
2387
+ Object.freeze(v);
2388
+ for (const x of Object.values(v)) freezeDeep(x);
2389
+ };
2390
+ var copyRecord = (r) => {
2391
+ const out = {};
2392
+ for (const [k, v] of Object.entries(r)) {
2393
+ if (Array.isArray(v)) {
2394
+ for (const x of v) freezeDeep(x);
2395
+ out[k] = [...v];
2396
+ } else {
2397
+ freezeDeep(v);
2398
+ out[k] = v;
2399
+ }
2400
+ }
2401
+ return out;
2402
+ };
2403
+ function detach(st) {
2404
+ const offers = {};
2405
+ for (const [id, o] of Object.entries(st.offers)) {
2406
+ if (o.status === "open") offers[id] = copyRecord(o);
2407
+ else {
2408
+ freezeDeep(o);
2409
+ offers[id] = o;
2410
+ }
2411
+ }
2412
+ const bids = {};
2413
+ for (const [id, b] of Object.entries(st.bids)) bids[id] = copyRecord(b);
2414
+ for (const n of Object.values(st.names)) freezeDeep(n.profile);
2415
+ const events = st.events.slice();
2416
+ for (const e of events) freezeDeep(e);
2417
+ return { ...st, offers, bids, events };
2418
+ }
2419
+
2420
+ // src/client.ts
2421
+ var import_csd_codec4 = require("@inversealtruism/csd-codec");
2190
2422
  var CLAIM_ATTACKER_Q = 0.2;
2191
2423
  var CLAIM_MIN_DEPTH = 3;
2192
2424
  var COMMIT_REVEAL_MIN_DEPTH = 3;
2193
2425
  function requiredClaimDepth(valueSats, height) {
2194
2426
  const r = CLAIM_ATTACKER_Q / (1 - CLAIM_ATTACKER_Q);
2195
2427
  const V = Number(valueSats);
2196
- const R = (0, import_csd_codec3.blockReward)(height) || import_csd_codec3.INITIAL_REWARD;
2428
+ const R = (0, import_csd_codec4.blockReward)(height) || import_csd_codec4.INITIAL_REWARD;
2197
2429
  const max = claimWindowAt(height) - 5;
2198
2430
  for (let D = CLAIM_MIN_DEPTH; D <= max; D++) {
2199
2431
  if (Math.pow(r, D) * V <= D * R) return { depth: D, reversalPct: Math.pow(r, D) * 100, capped: false };
@@ -2201,6 +2433,27 @@ function requiredClaimDepth(valueSats, height) {
2201
2433
  return { depth: max, reversalPct: Math.pow(r, max) * 100, capped: true };
2202
2434
  }
2203
2435
 
2436
+ // src/holdcount.ts
2437
+ var lastLegacyClaimEnd = V28_HEIGHT - 1 + claimWindowAt(V28_HEIGHT - 1);
2438
+ var LEGACY_HOLD_SUNSET_HEIGHT = lastLegacyClaimEnd + claimGraceOf(lastLegacyClaimEnd);
2439
+ function countOtherHoldsAtGrant(candidates, target, me, closed = /* @__PURE__ */ new Set()) {
2440
+ if (!(Number.isSafeInteger(target.height) && target.height >= LEGACY_HOLD_SUNSET_HEIGHT))
2441
+ return { ok: false, reason: `this reservation was granted at ${target.height}, before block ${LEGACY_HOLD_SUNSET_HEIGHT}, while claims made before V28 could still count against the cap; it cannot be checked here` };
2442
+ const meL = String(me).toLowerCase(), tid = String(target.id).toLowerCase(), toffer = String(target.offer).toLowerCase();
2443
+ const offers = /* @__PURE__ */ new Set();
2444
+ for (const c of candidates) {
2445
+ const cid = String(c.id).toLowerCase();
2446
+ if (cid === tid || closed.has(cid) || String(c.proposer).toLowerCase() !== meL) continue;
2447
+ if (!(c.height < target.height || c.height === target.height && c.pos < target.pos)) continue;
2448
+ if (!(fclaimHoldEnd(Number(c.expiresEpoch)) >= target.height)) continue;
2449
+ const rec = parseRecord(String(c.uri), String(c.payloadHash));
2450
+ if (!rec || rec.t !== "fclaim") continue;
2451
+ const offer2 = String(rec.offer).toLowerCase();
2452
+ if (offer2 !== toffer) offers.add(offer2);
2453
+ }
2454
+ return { ok: true, count: offers.size };
2455
+ }
2456
+
2204
2457
  // src/preflight.ts
2205
2458
  function previewFill(offer2, payRaw) {
2206
2459
  const pay = BigInt(payRaw);
@@ -2309,6 +2562,7 @@ function fillEndorsement(offer2, me, pay, tip, opts) {
2309
2562
  } else if (holdRouted) {
2310
2563
  return refuse("v2.8: a live fclaim hold routes this fill - pass opts.fillTargetId (use fillTargetId(offer, tip)) so the endorsement can verify what your attest targets");
2311
2564
  }
2565
+ if (tip >= LEGACY_HOLD_SUNSET_HEIGHT && isOpenClaimLane(offer2, tip) && !holdRouted) return refuse(`from block ${LEGACY_HOLD_SUNSET_HEIGHT} an open CSD offer is filled only through a reservation: an attest on the offer id is chain-rejected after the payment moved (reserve the offer and attest the fclaim txid)`);
2312
2566
  if (isTokenWant(offer2.want))
2313
2567
  return { verdict: "not-endorsable", reason: "token-priced want - deliverability is the attester's token balance, which a pure record predicate cannot see; NOT an endorsement and NOT a refusal (verify your token balance + proven terms, then proceed)", preview };
2314
2568
  if (!preview.deliverable) {
@@ -2373,7 +2627,7 @@ function nameView(names, name) {
2373
2627
  }
2374
2628
 
2375
2629
  // src/version.ts
2376
- var CAIRNX_CORE_VERSION = "0.2.9";
2630
+ var CAIRNX_CORE_VERSION = "0.2.11";
2377
2631
 
2378
2632
  // src/gates.ts
2379
2633
  var GATE_HEIGHTS = Object.freeze({
@@ -2400,7 +2654,7 @@ var GATE_HEIGHTS = Object.freeze({
2400
2654
  });
2401
2655
 
2402
2656
  // src/verifyfill.ts
2403
- var import_csd_codec4 = require("@inversealtruism/csd-codec");
2657
+ var import_csd_codec5 = require("@inversealtruism/csd-codec");
2404
2658
  var FCLAIM_MAX_HOLD_SPAN = import_csd_codec.EPOCH_LEN * (FCLAIM_MAX_EPOCH_AHEAD + 1) - 1;
2405
2659
  var GAP_NEEDED = FCLAIM_MAX_HOLD_SPAN + CLAIM_COOLDOWN_BLOCKS;
2406
2660
  var SCAN_MARGIN = import_csd_codec.EPOCH_LEN;
@@ -2408,7 +2662,7 @@ var MAX_SCAN = GAP_NEEDED + SCAN_MARGIN;
2408
2662
  function bindRecord(ev) {
2409
2663
  const rec = parseRecord(ev.uri, ev.payloadHash);
2410
2664
  if (!rec) return null;
2411
- if ((0, import_csd_codec4.payloadHash)(rec).toLowerCase() !== String(ev.payloadHash).toLowerCase()) return null;
2665
+ if ((0, import_csd_codec5.payloadHash)(rec).toLowerCase() !== String(ev.payloadHash).toLowerCase()) return null;
2412
2666
  return rec;
2413
2667
  }
2414
2668
  function replayLiveHold(proven, offerId, fclaimTxid, me, evalHeight) {
@@ -2563,138 +2817,6 @@ function bindProvenOffer(offerEv) {
2563
2817
  return { payto, seller, terms: provenOfferTerms(rec, offerEv.height) };
2564
2818
  }
2565
2819
 
2566
- // src/paidto.ts
2567
- function paidToFromOutputs(outputs) {
2568
- const m = /* @__PURE__ */ Object.create(null);
2569
- for (const o of outputs) {
2570
- if (typeof o.value !== "number" || !Number.isSafeInteger(o.value) || o.value < 0) continue;
2571
- m[o.addr] = (BigInt(m[o.addr] ?? "0") + BigInt(o.value)).toString();
2572
- }
2573
- return m;
2574
- }
2575
- function burnedPayment(paidTo, payer, offer2) {
2576
- const read = (addr) => addr === payer ? 0n : ptAmt(paidTo?.[addr]);
2577
- let counterparty = 0n;
2578
- if (offer2) {
2579
- for (const addr of /* @__PURE__ */ new Set([offer2.seller, offer2.want.payto])) if (addr !== TREASURY_ADDR) counterparty += read(addr);
2580
- }
2581
- return { treasury: read(TREASURY_ADDR), counterparty };
2582
- }
2583
-
2584
- // src/events.ts
2585
- var import_csd_codec5 = require("@inversealtruism/csd-codec");
2586
- var CAIRNX_EVENT_RULE = Object.freeze({ domain: DOMAIN, activationHeight: ACTIVATION_HEIGHT });
2587
- var fail = (what) => {
2588
- throw new Error(`events rule: ${what}`);
2589
- };
2590
- var isIndex = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
2591
- function hexOf(v, bytes, what) {
2592
- const h = typeof v === "string" && v.startsWith("0x") ? v.slice(2) : v;
2593
- if (typeof h !== "string" || h.length !== bytes * 2 || !/^[0-9a-fA-F]*$/.test(h)) return fail(`${what} is not ${bytes}-byte hex`);
2594
- return "0x" + h.toLowerCase();
2595
- }
2596
- function u64Of(v, what) {
2597
- if (typeof v === "bigint" && v >= 0n && v < 1n << 64n) return v;
2598
- if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 2 ** 53) return v;
2599
- if (typeof v === "number" && Number.isInteger(v) && v > 2 ** 53) return fail(`${what} above 2^53 must be passed as a bigint`);
2600
- return fail(`${what} is not a u64`);
2601
- }
2602
- function u32Of(v, what) {
2603
- return typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4294967295 ? v : fail(`${what} is not a u32`);
2604
- }
2605
- function checkRule(rule) {
2606
- const d = rule?.domain;
2607
- if (typeof d !== "string" || d === "" || !(0, import_csd_codec5.isWellFormedUtf16)(d) || d.includes("\0") || d.includes(""))
2608
- fail("the rule's domain must be non-empty, well-formed text without U+0000 or U+0001");
2609
- if (!isIndex(rule.activationHeight)) fail("the rule's activation height must be a safe integer >= 0");
2610
- }
2611
- var kindOf = (app) => {
2612
- const t = app?.type;
2613
- return t === "None" ? "none" : t === "Propose" ? "propose" : t === "Attest" ? "attest" : fail(`unknown app type ${String(t)}`);
2614
- };
2615
- var domainOf = (app) => typeof app.domain === "string" ? app.domain : fail("a Propose domain is not text");
2616
- function paidToOf(outputs) {
2617
- if (!Array.isArray(outputs)) fail("outputs is not a list");
2618
- const counted = [];
2619
- for (const o of outputs) {
2620
- const addr = hexOf(o?.scriptPubkey, 20, "script_pubkey"), value = u64Of(o?.value, "output value");
2621
- if (value <= Number.MAX_SAFE_INTEGER) counted.push({ addr, value: Number(value) });
2622
- }
2623
- return paidToFromOutputs(counted);
2624
- }
2625
- function eventOfTx(t, height, author, rule = CAIRNX_EVENT_RULE) {
2626
- checkRule(rule);
2627
- if (!isIndex(height)) fail("height is not a safe integer >= 0");
2628
- if (!isIndex(t?.pos)) fail("pos is not a safe integer >= 0");
2629
- const txid = hexOf(t.txid, 32, "txid");
2630
- const app = t.tx?.app;
2631
- const kind = kindOf(app);
2632
- if (kind === "none" || height < rule.activationHeight) return null;
2633
- if (t.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2634
- if (kind === "propose" && domainOf(app) !== rule.domain) return null;
2635
- const paidTo = paidToOf(t.tx.outputs), who = hexOf(author, 20, "author");
2636
- if (kind === "propose") {
2637
- const p = app;
2638
- const uri = p.uri;
2639
- if (typeof uri !== "string" || !(0, import_csd_codec5.isWellFormedUtf16)(uri)) return fail("uri is not well-formed text");
2640
- const e = u64Of(p.expiresEpoch, "expiresEpoch");
2641
- return {
2642
- kind: "propose",
2643
- id: txid,
2644
- proposer: who,
2645
- uri: uri.replaceAll("\0", ""),
2646
- payloadHash: hexOf(p.payloadHash, 32, "payloadHash"),
2647
- expiresEpoch: e <= Number.MAX_SAFE_INTEGER ? Number(e) : 2 ** 53,
2648
- height,
2649
- pos: t.pos,
2650
- paidTo
2651
- };
2652
- }
2653
- const a = app;
2654
- return {
2655
- kind: "attest",
2656
- txid,
2657
- proposalId: hexOf(a.proposalId, 32, "proposalId"),
2658
- attester: who,
2659
- score: u32Of(a.score, "score"),
2660
- confidence: u32Of(a.confidence, "confidence"),
2661
- height,
2662
- pos: t.pos,
2663
- paidTo
2664
- };
2665
- }
2666
- function blockMembers(height, txs, sofar, rule = CAIRNX_EVENT_RULE) {
2667
- checkRule(rule);
2668
- if (!isIndex(height)) fail("height is not a safe integer >= 0");
2669
- if (height < rule.activationHeight) return [];
2670
- if (!Array.isArray(txs)) fail("txs is not a list");
2671
- const ids = /* @__PURE__ */ new Set(), proposals = /* @__PURE__ */ new Set();
2672
- const read = [];
2673
- let last = -1;
2674
- for (const item of txs) {
2675
- if (!isIndex(item?.pos) || item.pos <= last) fail("positions are not safe integers >= 0 in strictly increasing order");
2676
- last = item.pos;
2677
- const id = hexOf(item.txid, 32, "txid");
2678
- if (ids.has(id)) fail(`txid ${id} is repeated in the block`);
2679
- ids.add(id);
2680
- const kind = kindOf(item.tx?.app);
2681
- if (kind === "none") continue;
2682
- if (item.pos === 0) fail("position 0 is the coinbase, which carries no app payload");
2683
- if (kind === "propose") {
2684
- if (domainOf(item.tx.app) !== rule.domain || sofar.eventIds.has(id)) continue;
2685
- proposals.add(id);
2686
- read.push({ item, kind, id });
2687
- } else read.push({ item, kind, id, proposal: hexOf(item.tx.app.proposalId, 32, "proposalId") });
2688
- }
2689
- return read.filter((r) => r.kind === "propose" || !sofar.eventIds.has(r.id) && (sofar.proposeIds.has(r.proposal) || proposals.has(r.proposal))).map((r) => ({ kind: r.kind, item: r.item }));
2690
- }
2691
- function blockEvents(height, txs, sofar, authors, rule = CAIRNX_EVENT_RULE) {
2692
- const members = blockMembers(height, txs, sofar, rule);
2693
- if (!Array.isArray(authors) || authors.length !== members.length) fail(`the block has ${members.length} members, not ${authors?.length} authors`);
2694
- const events = members.map((m, i) => eventOfTx(m.item, height, authors[i], rule) ?? fail("a member mapped to no event"));
2695
- return [...events.filter((e) => e.kind === "propose"), ...events.filter((e) => e.kind === "attest")];
2696
- }
2697
-
2698
2820
  // src/hashes.ts
2699
2821
  var import_csd_codec6 = require("@inversealtruism/csd-codec");
2700
2822
  var import_sha256 = require("@noble/hashes/sha256");
@@ -2788,27 +2910,6 @@ function myProvenFillClosedOffer(fill, fclaim2, offerEv, me, grantHeight) {
2788
2910
  return need.every((leg) => ptAmt(fill.paidTo?.[lc(leg.to)]) >= leg.value);
2789
2911
  }
2790
2912
 
2791
- // src/holdcount.ts
2792
- var lastLegacyClaimEnd = V28_HEIGHT - 1 + claimWindowAt(V28_HEIGHT - 1);
2793
- var LEGACY_HOLD_SUNSET_HEIGHT = lastLegacyClaimEnd + claimGraceOf(lastLegacyClaimEnd);
2794
- function countOtherHoldsAtGrant(candidates, target, me, closed = /* @__PURE__ */ new Set()) {
2795
- if (!(Number.isSafeInteger(target.height) && target.height >= LEGACY_HOLD_SUNSET_HEIGHT))
2796
- return { ok: false, reason: `this reservation was granted at ${target.height}, before block ${LEGACY_HOLD_SUNSET_HEIGHT}, while claims made before V28 could still count against the cap; it cannot be checked here` };
2797
- const meL = String(me).toLowerCase(), tid = String(target.id).toLowerCase(), toffer = String(target.offer).toLowerCase();
2798
- const offers = /* @__PURE__ */ new Set();
2799
- for (const c of candidates) {
2800
- const cid = String(c.id).toLowerCase();
2801
- if (cid === tid || closed.has(cid) || String(c.proposer).toLowerCase() !== meL) continue;
2802
- if (!(c.height < target.height || c.height === target.height && c.pos < target.pos)) continue;
2803
- if (!(fclaimHoldEnd(Number(c.expiresEpoch)) >= target.height)) continue;
2804
- const rec = parseRecord(String(c.uri), String(c.payloadHash));
2805
- if (!rec || rec.t !== "fclaim") continue;
2806
- const offer2 = String(rec.offer).toLowerCase();
2807
- if (offer2 !== toffer) offers.add(offer2);
2808
- }
2809
- return { ok: true, count: offers.size };
2810
- }
2811
-
2812
2913
  // src/admission.ts
2813
2914
  function provenOfferRefusal(rec, tx) {
2814
2915
  if (tx.domain !== DOMAIN) return `not a ${DOMAIN} Propose (domain ${JSON.stringify(String(tx.domain))})`;
@@ -3014,6 +3115,7 @@ var import_csd_codec7 = require("@inversealtruism/csd-codec");
3014
3115
  REG_FINALIZE_GRACE_BLOCKS,
3015
3116
  RESERVED_NAMES,
3016
3117
  RecordError,
3118
+ ReplayContextRefusal,
3017
3119
  SALT_RE,
3018
3120
  SCAN_MARGIN,
3019
3121
  SCORE_CANCEL,
@@ -3077,6 +3179,8 @@ var import_csd_codec7 = require("@inversealtruism/csd-codec");
3077
3179
  fillTargetId,
3078
3180
  finalizeWinnerCheck,
3079
3181
  hasLiveClaim,
3182
+ isChainHeight,
3183
+ isIndex,
3080
3184
  isName,
3081
3185
  isNameGive,
3082
3186
  isOpenClaimLane,
@@ -3094,6 +3198,7 @@ var import_csd_codec7 = require("@inversealtruism/csd-codec");
3094
3198
  nameSet,
3095
3199
  nameView,
3096
3200
  nameXfer,
3201
+ newReplayContext,
3097
3202
  offer,
3098
3203
  offerCancelAll,
3099
3204
  offerExpiryHeightOf,