zklicensing 0.1.0-beta.2 → 0.1.0-beta.4

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.
Files changed (173) hide show
  1. package/README.md +335 -97
  2. package/build/appsLookup.d.ts +14 -0
  3. package/build/appsLookup.d.ts.map +1 -0
  4. package/build/appsLookup.js +12 -0
  5. package/build/appsLookup.js.map +1 -0
  6. package/build/archiveBootstrap.d.ts +15 -1
  7. package/build/archiveBootstrap.d.ts.map +1 -0
  8. package/build/archiveBootstrap.js +62 -9
  9. package/build/archiveBootstrap.js.map +1 -0
  10. package/build/bindClient.d.ts +51 -0
  11. package/build/bindClient.d.ts.map +1 -0
  12. package/build/bindClient.js +115 -0
  13. package/build/bindClient.js.map +1 -0
  14. package/build/buyClient.d.ts +10 -3
  15. package/build/buyClient.d.ts.map +1 -0
  16. package/build/buyClient.js +33 -15
  17. package/build/buyClient.js.map +1 -0
  18. package/build/contractInterface.d.ts +11 -5
  19. package/build/contractInterface.d.ts.map +1 -0
  20. package/build/contractInterface.js +82 -17
  21. package/build/contractInterface.js.map +1 -0
  22. package/build/countryStats.d.ts +6 -1
  23. package/build/countryStats.d.ts.map +1 -0
  24. package/build/countryStats.js +33 -9
  25. package/build/countryStats.js.map +1 -0
  26. package/build/deployClient.d.ts.map +1 -0
  27. package/build/deployClient.js +1 -1
  28. package/build/deployClient.js.map +1 -0
  29. package/build/deviceIdentity.d.ts +68 -0
  30. package/build/deviceIdentity.d.ts.map +1 -0
  31. package/build/deviceIdentity.js +209 -0
  32. package/build/deviceIdentity.js.map +1 -0
  33. package/build/freezeClient.d.ts.map +1 -0
  34. package/build/freezeClient.js +1 -1
  35. package/build/freezeClient.js.map +1 -0
  36. package/build/generationClient.d.ts +1 -0
  37. package/build/generationClient.d.ts.map +1 -0
  38. package/build/generationClient.js +2 -2
  39. package/build/generationClient.js.map +1 -0
  40. package/build/index.d.ts +27 -37
  41. package/build/index.d.ts.map +1 -0
  42. package/build/index.js +85 -116
  43. package/build/index.js.map +1 -0
  44. package/build/licenseLeaf.d.ts +76 -0
  45. package/build/licenseLeaf.d.ts.map +1 -0
  46. package/build/licenseLeaf.js +189 -0
  47. package/build/licenseLeaf.js.map +1 -0
  48. package/build/licenseRecord.d.ts +20 -1
  49. package/build/licenseRecord.d.ts.map +1 -0
  50. package/build/licenseRecord.js +1 -1
  51. package/build/licenseRecord.js.map +1 -0
  52. package/build/licenseStore.d.ts +17 -2
  53. package/build/licenseStore.d.ts.map +1 -0
  54. package/build/licenseStore.js +167 -7
  55. package/build/licenseStore.js.map +1 -0
  56. package/build/manifestVerify.d.ts.map +1 -0
  57. package/build/manifestVerify.js +8 -3
  58. package/build/manifestVerify.js.map +1 -0
  59. package/build/migrateClient.d.ts +6 -21
  60. package/build/migrateClient.d.ts.map +1 -0
  61. package/build/migrateClient.js +30 -17
  62. package/build/migrateClient.js.map +1 -0
  63. package/build/onChainRoot.d.ts +67 -0
  64. package/build/onChainRoot.d.ts.map +1 -0
  65. package/build/onChainRoot.js +87 -0
  66. package/build/onChainRoot.js.map +1 -0
  67. package/build/ownershipLicenseHash.d.ts +25 -0
  68. package/build/ownershipLicenseHash.d.ts.map +1 -0
  69. package/build/ownershipLicenseHash.js +29 -0
  70. package/build/ownershipLicenseHash.js.map +1 -0
  71. package/build/ownershipSignature.d.ts +122 -0
  72. package/build/ownershipSignature.d.ts.map +1 -0
  73. package/build/ownershipSignature.js +244 -0
  74. package/build/ownershipSignature.js.map +1 -0
  75. package/build/proveErrors.d.ts +35 -0
  76. package/build/proveErrors.d.ts.map +1 -0
  77. package/build/proveErrors.js +49 -0
  78. package/build/proveErrors.js.map +1 -0
  79. package/build/refundClient.d.ts +2 -11
  80. package/build/refundClient.d.ts.map +1 -0
  81. package/build/refundClient.js +35 -17
  82. package/build/refundClient.js.map +1 -0
  83. package/build/renewClient.d.ts +4 -1
  84. package/build/renewClient.d.ts.map +1 -0
  85. package/build/renewClient.js +11 -4
  86. package/build/renewClient.js.map +1 -0
  87. package/build/seatName.d.ts +8 -0
  88. package/build/seatName.d.ts.map +1 -0
  89. package/build/seatName.js +136 -0
  90. package/build/seatName.js.map +1 -0
  91. package/build/statsClient.d.ts +47 -4
  92. package/build/statsClient.d.ts.map +1 -0
  93. package/build/statsClient.js +44 -5
  94. package/build/statsClient.js.map +1 -0
  95. package/build/trustAnchorVerify.d.ts +48 -0
  96. package/build/trustAnchorVerify.d.ts.map +1 -0
  97. package/build/trustAnchorVerify.js +431 -0
  98. package/build/trustAnchorVerify.js.map +1 -0
  99. package/build/trustAnchorVerifyCli.d.ts +35 -0
  100. package/build/trustAnchorVerifyCli.d.ts.map +1 -0
  101. package/build/trustAnchorVerifyCli.js +177 -0
  102. package/build/trustAnchorVerifyCli.js.map +1 -0
  103. package/build/txBroadcastClient.d.ts +26 -0
  104. package/build/txBroadcastClient.d.ts.map +1 -0
  105. package/build/txBroadcastClient.js +20 -0
  106. package/build/txBroadcastClient.js.map +1 -0
  107. package/build/unbindClient.d.ts +56 -0
  108. package/build/unbindClient.d.ts.map +1 -0
  109. package/build/unbindClient.js +113 -0
  110. package/build/unbindClient.js.map +1 -0
  111. package/build/vendorAccountClient.d.ts +56 -0
  112. package/build/vendorAccountClient.d.ts.map +1 -0
  113. package/build/vendorAccountClient.js +47 -0
  114. package/build/vendorAccountClient.js.map +1 -0
  115. package/build/verifyCore.d.ts +1 -1
  116. package/build/verifyCore.d.ts.map +1 -0
  117. package/build/verifyCore.js +11 -4
  118. package/build/verifyCore.js.map +1 -0
  119. package/build/verifyOffline.d.ts +85 -0
  120. package/build/verifyOffline.d.ts.map +1 -0
  121. package/build/verifyOffline.js +139 -0
  122. package/build/verifyOffline.js.map +1 -0
  123. package/build/verifyService.d.ts.map +1 -0
  124. package/build/verifyService.js +582 -455
  125. package/build/verifyService.js.map +1 -0
  126. package/build/verifyWithAncestors.d.ts +18 -0
  127. package/build/verifyWithAncestors.d.ts.map +1 -0
  128. package/build/verifyWithAncestors.js +119 -0
  129. package/build/verifyWithAncestors.js.map +1 -0
  130. package/build/zipToState.d.ts +2 -0
  131. package/build/zipToState.d.ts.map +1 -0
  132. package/build/zipToState.js +94 -0
  133. package/build/zipToState.js.map +1 -0
  134. package/package.json +57 -13
  135. package/src/appsLookup.ts +48 -0
  136. package/src/archiveBootstrap.ts +342 -0
  137. package/src/bindClient.ts +175 -0
  138. package/src/buyClient.ts +304 -0
  139. package/src/contractInterface.d.ts +61 -0
  140. package/src/contractInterface.ts +313 -0
  141. package/src/countryStats.ts +171 -0
  142. package/src/deployClient.ts +388 -0
  143. package/src/deviceIdentity.ts +249 -0
  144. package/src/freezeClient.ts +117 -0
  145. package/src/generationClient.ts +165 -0
  146. package/src/index.ts +329 -0
  147. package/src/licenseLeaf.ts +221 -0
  148. package/src/licenseRecord.ts +108 -0
  149. package/src/licenseStore.ts +538 -0
  150. package/src/manifestVerify.ts +111 -0
  151. package/src/migrateClient.ts +84 -0
  152. package/src/onChainRoot.ts +107 -0
  153. package/src/ownershipLicenseHash.ts +31 -0
  154. package/src/ownershipSignature.ts +354 -0
  155. package/src/proveErrors.ts +70 -0
  156. package/src/refundClient.ts +158 -0
  157. package/src/renewClient.ts +214 -0
  158. package/src/seatName.ts +165 -0
  159. package/src/statsClient.ts +235 -0
  160. package/src/trustAnchorVerify.ts +548 -0
  161. package/src/trustAnchorVerifyCli.ts +179 -0
  162. package/src/txBroadcastClient.ts +48 -0
  163. package/src/unbindClient.ts +149 -0
  164. package/src/vendorAccountClient.ts +110 -0
  165. package/src/verifyCore.ts +92 -0
  166. package/src/verifyOffline.ts +212 -0
  167. package/src/verifyService.ts +969 -0
  168. package/src/verifyWithAncestors.ts +153 -0
  169. package/src/zipToState.ts +94 -0
  170. package/build/licenseProof.d.ts +0 -26
  171. package/build/licenseProof.js +0 -41
  172. package/build/ownership.d.ts +0 -34
  173. package/build/ownership.js +0 -147
package/src/index.ts ADDED
@@ -0,0 +1,329 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * verifyLicense — client SDK.
6
+ *
7
+ * Calls the licensing service's GET /verify until the on-chain refund
8
+ * window for the license has closed; from that point on returns from a
9
+ * local anchor and never touches the network again. The refund-window
10
+ * decision is server-side: the service returns `refundWindowClosed:
11
+ * boolean` on its /verify response, computed from its own record of
12
+ * `purchaseSlot + REFUND_WINDOW_N` against the on-chain `currentSlot`.
13
+ * The SDK gates anchor writes on that boolean and never trusts a
14
+ * `purchaseSlot` supplied by the local proof file, so a user who forges
15
+ * their proof metadata cannot force the offline branch prematurely.
16
+ *
17
+ * Anchor purity: every field persisted in the Anchor derives from the
18
+ * service's /verify response — `anchoredSlot`, `expirySlot`. The only
19
+ * client-supplied input to the offline branch is `proof.expirySlot`,
20
+ * used solely as the loadAnchor binding key. A tampered proof file
21
+ * therefore never gets a wrong answer; it gets no offline branch at all
22
+ * and falls through to the licensing service on every call.
23
+ */
24
+
25
+ import {
26
+ REFUND_WINDOW_N,
27
+ GRACE_PERIOD_N,
28
+ MS_PER_SLOT_N,
29
+ SLOTS_PER_DAY_N,
30
+ } from './contractInterface.js';
31
+
32
+ const MS_PER_SLOT = MS_PER_SLOT_N;
33
+ const SLOTS_PER_DAY = SLOTS_PER_DAY_N;
34
+
35
+ // The one and only verify endpoint. Every issued license routes here
36
+ // regardless of network — the platform verifier resolves devnet vs
37
+ // mainnet from the zkAppAddress (each deployment is unique per network).
38
+ // Tests inject a mock via VerifyOptions.fetcher, not by rewriting this URL.
39
+ export const DEFAULT_VERIFIER_URL = 'https://zklicensing.com/api/verify';
40
+
41
+ // Anchor records are keyed by (zkAppAddress, licenseHash). zkAppAddress
42
+ // is generation-scoped by construction: each hardfork migration deploys
43
+ // the LicensingApp at a fresh address (see keeper's finalizeRedeploy
44
+ // and AppRecord.deploymentHistory[]), so keying on it implicitly
45
+ // captures generation. An anchor written pre-migration is orphaned by
46
+ // the new address on next verify and re-created cleanly — no
47
+ // cross-generation carry-over.
48
+ const ANCHOR_KEY_PREFIX = 'zklic_anchor_';
49
+
50
+ function anchorKey(zkAppAddress: string, licenseHash: string): string {
51
+ return `${ANCHOR_KEY_PREFIX}${zkAppAddress}_${licenseHash}`;
52
+ }
53
+
54
+ export interface Storage {
55
+ getItem(key: string): string | null;
56
+ setItem(key: string, value: string): void;
57
+ }
58
+
59
+ export interface ProofInput {
60
+ licenseHash: string;
61
+ zkAppAddress: string;
62
+ expirySlot: number;
63
+ }
64
+
65
+ export interface VerifyOptions {
66
+ storage?: Storage | null;
67
+ fetcher?: typeof fetch;
68
+ now?: () => number;
69
+ }
70
+
71
+ export interface VerifyResult {
72
+ valid: boolean;
73
+ expirySlot: number;
74
+ // ISO-8601 timestamp of estimated expiry. `null` when the license is
75
+ // unknown / refunded / unreachable. In the offline branch this is
76
+ // estimated from the anchor + local clock.
77
+ expiresAt: string | null;
78
+ // Estimated current Mina slot. From the licensing service in the
79
+ // chain branch; estimated from the anchor + elapsed local time in the
80
+ // offline branch.
81
+ currentSlot: number;
82
+ inGracePeriod: boolean;
83
+ // Whole days until expiry. Negative while in the grace period (down
84
+ // to ~-7) and below that once fully expired. 0 when expirySlot is
85
+ // unknown.
86
+ remainingDays: number;
87
+ reason: string | null;
88
+ source: 'offline' | 'chain';
89
+ }
90
+
91
+ interface Anchor {
92
+ anchoredSlot: number;
93
+ anchoredAtMs: number;
94
+ expirySlot: number;
95
+ }
96
+
97
+ function defaultStorage(): Storage | null {
98
+ if (typeof globalThis !== 'undefined' && (globalThis as any).localStorage) {
99
+ return (globalThis as any).localStorage as Storage;
100
+ }
101
+ return null;
102
+ }
103
+
104
+ function loadAnchor(
105
+ storage: Storage,
106
+ zkAppAddress: string,
107
+ licenseHash: string,
108
+ expirySlot: number,
109
+ ): Anchor | null {
110
+ try {
111
+ const raw = storage.getItem(anchorKey(zkAppAddress, licenseHash));
112
+ if (!raw) return null;
113
+ const a = JSON.parse(raw) as Anchor;
114
+ // `a.expirySlot` is the SERVICE's value captured at anchor time;
115
+ // the `expirySlot` argument is the LOCAL proof file's value. Match
116
+ // ⇒ local file agrees with chain truth as of anchoring ⇒ offline is
117
+ // safe. Mismatch has two honest meanings:
118
+ // - renewal: chain moved, local file updated ⇒ re-anchor via chain check
119
+ // - forgery: local file edited ⇒ every call falls through to the
120
+ // licensing service, which reports truth. The forger gets no
121
+ // offline branch at all.
122
+ if (a.expirySlot !== expirySlot) return null;
123
+ return a;
124
+ } catch {
125
+ return null;
126
+ }
127
+ }
128
+
129
+ function saveAnchor(
130
+ storage: Storage,
131
+ zkAppAddress: string,
132
+ licenseHash: string,
133
+ anchor: Anchor,
134
+ ): void {
135
+ try {
136
+ storage.setItem(anchorKey(zkAppAddress, licenseHash), JSON.stringify(anchor));
137
+ } catch {
138
+ // Storage may be full or read-only; the offline path simply won't activate.
139
+ }
140
+ }
141
+
142
+ function computeRemainingDays(expirySlot: number, currentSlot: number): number {
143
+ if (expirySlot === 0) return 0;
144
+ return Math.floor((expirySlot - currentSlot) / SLOTS_PER_DAY);
145
+ }
146
+
147
+ function offlineCheck(anchor: Anchor, nowMs: number): VerifyResult {
148
+ const elapsedSlots = Math.max(0, Math.floor((nowMs - anchor.anchoredAtMs) / MS_PER_SLOT));
149
+ const estCurrentSlot = anchor.anchoredSlot + elapsedSlots;
150
+ const expired = estCurrentSlot > anchor.expirySlot + GRACE_PERIOD_N;
151
+ const inGracePeriod = !expired && estCurrentSlot > anchor.expirySlot;
152
+ const expiresAt = new Date(nowMs + (anchor.expirySlot - estCurrentSlot) * MS_PER_SLOT).toISOString();
153
+ return {
154
+ valid: !expired,
155
+ expirySlot: anchor.expirySlot,
156
+ expiresAt,
157
+ currentSlot: estCurrentSlot,
158
+ inGracePeriod,
159
+ remainingDays: computeRemainingDays(anchor.expirySlot, estCurrentSlot),
160
+ reason: expired
161
+ ? 'License has expired'
162
+ : inGracePeriod
163
+ ? 'License is in grace period — renew to avoid interruption'
164
+ : null,
165
+ source: 'offline',
166
+ };
167
+ }
168
+
169
+ export async function verifyLicense(
170
+ proof: ProofInput,
171
+ options: VerifyOptions = {}
172
+ ): Promise<VerifyResult> {
173
+ const storage = options.storage === null ? null : options.storage ?? defaultStorage();
174
+ const fetcher = options.fetcher ?? (typeof fetch !== 'undefined' ? fetch : undefined);
175
+ const nowFn = options.now ?? (() => Date.now());
176
+
177
+ if (storage) {
178
+ const anchor = loadAnchor(storage, proof.zkAppAddress, proof.licenseHash, proof.expirySlot);
179
+ if (anchor) return offlineCheck(anchor, nowFn());
180
+ }
181
+
182
+ if (!fetcher) {
183
+ return {
184
+ valid: false,
185
+ expirySlot: proof.expirySlot,
186
+ expiresAt: null,
187
+ currentSlot: 0,
188
+ inGracePeriod: false,
189
+ remainingDays: 0,
190
+ reason: 'No fetch implementation available; cannot verify',
191
+ source: 'chain',
192
+ };
193
+ }
194
+
195
+ const url =
196
+ `${DEFAULT_VERIFIER_URL}` +
197
+ `?licenseHash=${encodeURIComponent(proof.licenseHash)}` +
198
+ `&zkAppAddress=${encodeURIComponent(proof.zkAppAddress)}`;
199
+
200
+ let data: any;
201
+ try {
202
+ const resp = await fetcher(url);
203
+ if (!resp.ok) {
204
+ return {
205
+ valid: false,
206
+ expirySlot: proof.expirySlot,
207
+ expiresAt: null,
208
+ currentSlot: 0,
209
+ inGracePeriod: false,
210
+ remainingDays: 0,
211
+ reason: `Verification request failed (HTTP ${resp.status})`,
212
+ source: 'chain',
213
+ };
214
+ }
215
+ data = await resp.json();
216
+ } catch (err: any) {
217
+ return {
218
+ valid: false,
219
+ expirySlot: proof.expirySlot,
220
+ expiresAt: null,
221
+ currentSlot: 0,
222
+ inGracePeriod: false,
223
+ remainingDays: 0,
224
+ reason: err?.message ?? 'Verification request errored',
225
+ source: 'chain',
226
+ };
227
+ }
228
+
229
+ // Service's authoritative expiry, or null if the response omits it.
230
+ // Only the null-safe form may be written into the anchor; the
231
+ // chain-result display value below falls back to the local proof file
232
+ // for user-facing fields, which is safe (display only).
233
+ const respExpirySlotStrict: number | null =
234
+ typeof data.expirySlot === 'number' ? data.expirySlot : null;
235
+ const respExpirySlot: number = respExpirySlotStrict ?? proof.expirySlot;
236
+ const respCurrentSlot: number = typeof data.currentSlot === 'number' ? data.currentSlot : 0;
237
+ const result: VerifyResult = {
238
+ valid: !!data.valid,
239
+ expirySlot: respExpirySlot,
240
+ expiresAt: typeof data.expiresAt === 'string' ? data.expiresAt : null,
241
+ currentSlot: respCurrentSlot,
242
+ inGracePeriod: !!data.inGracePeriod,
243
+ remainingDays: typeof data.remainingDays === 'number'
244
+ ? data.remainingDays
245
+ : computeRemainingDays(respExpirySlot, respCurrentSlot),
246
+ reason: data.reason ?? null,
247
+ source: 'chain',
248
+ };
249
+
250
+ // Anchor gate uses the service's own refund-window decision. The
251
+ // service knows the true purchaseSlot (stored in its LicenseRecord)
252
+ // and the true currentSlot; the SDK never trusts a purchaseSlot or
253
+ // expirySlot supplied by the local proof file, since that file is
254
+ // client-writable and could be forged. If the service omits
255
+ // `expirySlot`, we fail-closed on the offline path — no anchor
256
+ // written, subsequent calls stay online.
257
+ if (
258
+ storage &&
259
+ result.valid &&
260
+ data.refundWindowClosed === true &&
261
+ typeof data.currentSlot === 'number' &&
262
+ respExpirySlotStrict !== null
263
+ ) {
264
+ saveAnchor(storage, proof.zkAppAddress, proof.licenseHash, {
265
+ anchoredSlot: data.currentSlot,
266
+ anchoredAtMs: nowFn(),
267
+ expirySlot: respExpirySlotStrict,
268
+ });
269
+ }
270
+
271
+ return result;
272
+ }
273
+
274
+ // Re-exported so tests and downstream tooling can reference the same values
275
+ // the SDK uses internally without re-deriving them.
276
+ export { REFUND_WINDOW_N, GRACE_PERIOD_N, MS_PER_SLOT };
277
+
278
+ // Non-custodial device binding surface. Re-exported at the
279
+ // barrel alongside buy / renew / refund so vendor SDK integrators can
280
+ // pull the whole family from a single import path. Each also has its
281
+ // own package subpath (`zklicensing/bind`, `zklicensing/unbind`,
282
+ // `zklicensing/device-identity`) to match the buy / renew / refund
283
+ // convention.
284
+ export { proveBind, confirmBind } from './bindClient.js';
285
+ export type {
286
+ ProveBindRequest,
287
+ ProveBindResponse,
288
+ ConfirmBindRequest,
289
+ } from './bindClient.js';
290
+ export { proveUnbind, confirmUnbind } from './unbindClient.js';
291
+ export type {
292
+ ProveUnbindRequest,
293
+ ProveUnbindResponse,
294
+ ConfirmUnbindRequest,
295
+ } from './unbindClient.js';
296
+ export {
297
+ getOrCreateDeviceIdentity,
298
+ computeDeviceCommitment,
299
+ } from './deviceIdentity.js';
300
+ export type { DeviceIdentity } from './deviceIdentity.js';
301
+
302
+ // Offline device-binding verifier. Vendors reconstruct the
303
+ // LicenseLeaf from a synced snapshot, verify the leaf hash against the
304
+ // last-known licensesRoot, and confirm the caller's device commitment
305
+ // appears in `occupied[]`. Also available at the `zklicensing/verify-offline`
306
+ // subpath for callers that want to minimize their imported surface.
307
+ export { verifyOffline, deviceCommitmentFromFields } from './verifyOffline.js';
308
+ export type {
309
+ VerifyOfflineInput,
310
+ VerifyOfflineResult,
311
+ DeviceSlotSnapshot,
312
+ } from './verifyOffline.js';
313
+
314
+ // Non-custodial trust anchor for `verifyOffline`. Reads the live
315
+ // `licensesRoot` (zkapp.appState[0]) directly from Mina — pair it with
316
+ // `verifyOffline` when you do not want to trust the licensing service's
317
+ // reported root. Also available at the `zklicensing/on-chain-root`
318
+ // subpath. o1js is imported lazily so callers that skip this helper
319
+ // don't pay the o1js dep cost at load time.
320
+ export { fetchOnChainLicensesRoot, DEFAULT_MINA_GRAPHQL_URLS } from './onChainRoot.js';
321
+ export type { FetchOnChainLicensesRootInput, NetworkName } from './onChainRoot.js';
322
+
323
+ // Human-readable seat names for the device-binding UI ("Silent Otter",
324
+ // "Curious Panda"). Deterministic in `licenseHash + slotIndex + boundAtSlot`,
325
+ // so every viewer of the same license computes the same name per slot
326
+ // without a naming sidecar. Also available at the `zklicensing/seat-name`
327
+ // subpath.
328
+ export { seatNameFor, SEAT_NAME_COMBINATIONS } from './seatName.js';
329
+ export type { SeatNameInput } from './seatName.js';
@@ -0,0 +1,221 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * licenseLeaf.ts
6
+ *
7
+ * On-chain leaf value stored at every occupied `licensesRoot` slot. Bundles
8
+ * the license expiry with the device-binding state (cap, slot commitments,
9
+ * fill counter) so a single tree lookup returns everything a verifier or a
10
+ * `/prove/bind` call needs.
11
+ *
12
+ * Wire shape (in order of hash preimage):
13
+ * licenseHash Field the tree key, also carried in the leaf
14
+ * so a stolen witness can't be re-pointed
15
+ * at another entry. Doubles as the owner-
16
+ * pubkey commitment — buyLicense asserts
17
+ * licenseHash == Poseidon(pk.x, pk.isOdd)
18
+ * so bind/unbind's ownership check reads
19
+ * the same field as the tree key. Storing
20
+ * them separately would be pure redundancy.
21
+ * expirySlot UInt32→Field UInt32 packed into a Field
22
+ * cap UInt32→Field 0 disables /prove/bind; ≤DEVICE_SLOT_CAP
23
+ * (kept as UInt32 in-circuit because o1js's
24
+ * provable types don't include UInt8)
25
+ * deviceSlotsRoot Field Poseidon fold over the 10 slot fields
26
+ * below (2 fields × DEVICE_SLOT_CAP)
27
+ * deviceSlotsFilled UInt32→Field how many of the DEVICE_SLOT_CAP slots
28
+ * are currently non-empty — carried
29
+ * alongside the fold so `bind()` can do
30
+ * a cheap "cap - filled > 0" check
31
+ * without re-summing the array
32
+ *
33
+ * DEVICE_SLOT_CAP is fixed at 5 so the slot arrays have a size known to the
34
+ * circuit at compile time. `cap` in the leaf may be smaller — it's a
35
+ * per-license limit; slots [cap..DEVICE_SLOT_CAP) must always stay empty
36
+ * (Field(0)) and `bind()` rejects any write to them. `cap = 0` disables
37
+ * binding entirely; `bind()` rejects immediately without ever touching a
38
+ * slot.
39
+ *
40
+ * Slot encoding (fields carried in the fold, per slot i):
41
+ * occupied[i] Field 0 (empty) or Poseidon(devicePubKeyHash)
42
+ * freedAt[i] Field packed (boundAtSlot << 32) | freedAtSlot; both
43
+ * are UInt32-range Mina slot numbers. On a fresh
44
+ * empty slot both halves are 0. On bind, boundAt
45
+ * gets the current slot and freedAt stays 0. On
46
+ * unbind, freedAt gets the current slot (boundAt
47
+ * is preserved for audit / cooldown math).
48
+ *
49
+ * The struct + helpers live in the SDK (not the circuit package) so both
50
+ * the on-chain `@method` bodies AND the off-chain keeper / verifier /
51
+ * dashboards can share a single source of truth for the leaf hash. The
52
+ * circuit re-exports them from `LicensingApp.ts` so existing consumers
53
+ * that import from there keep working.
54
+ */
55
+
56
+ import { Field, Poseidon, Provable, PublicKey, Struct, UInt32 } from 'o1js';
57
+ import type { LicenseRecord } from './licenseRecord.js';
58
+
59
+ // Fixed slot-array width. Per the device-binding-noncustodial plan: 5 is
60
+ // the sweet spot between "enough seats for a normal user" and "witnesses
61
+ // stay small." Changing this is a hardfork migration (would flip every
62
+ // leaf hash) — not a runtime tunable.
63
+ export const DEVICE_SLOT_CAP_N = 5;
64
+ export const DEVICE_SLOT_CAP = UInt32.from(DEVICE_SLOT_CAP_N);
65
+
66
+ // Poseidon-fold of DEVICE_SLOT_CAP × 2 = 10 zero Fields, used as the
67
+ // initial deviceSlotsRoot on every freshly-minted leaf. Precomputed once
68
+ // at module load so `freshLeaf()` doesn't reconstruct it per-call.
69
+ export const EMPTY_DEVICE_SLOTS_ROOT: Field = Poseidon.hash(
70
+ Array.from({ length: DEVICE_SLOT_CAP_N * 2 }, () => Field(0)),
71
+ );
72
+
73
+ // Poseidon-bound identity of the passphrase-derived ownership pubkey.
74
+ // The full PublicKey is (x: Field, isOdd: Bool); Poseidon(x, isOdd.toField())
75
+ // gives a single Field commitment. The buy circuit asserts this equals
76
+ // `licenseHash`, so the leaf carries no separate owner-pubkey field —
77
+ // `licenseHash` IS the on-chain owner-pubkey commitment.
78
+ export function ownerPubKeyHash(pub: PublicKey): Field {
79
+ return Poseidon.hash([pub.x, pub.isOdd.toField()]);
80
+ }
81
+
82
+ // Pack (boundAtSlot, freedAtSlot) into a single Field. Both are Mina
83
+ // slot numbers (UInt32-range, ≤ 2^32-1), so the concatenation fits in 64
84
+ // bits. Layout mirrors packPrices in LicensingApp.ts — low bits first so
85
+ // the more frequently-read half (freedAt, checked by every bind cooldown)
86
+ // unpacks with a single mask.
87
+ const SHIFT_32 = Field(1n << 32n);
88
+
89
+ export function packSlotTimes(boundAtSlot: UInt32, freedAtSlot: UInt32): Field {
90
+ return freedAtSlot.value.add(boundAtSlot.value.mul(SHIFT_32));
91
+ }
92
+
93
+ export function unpackSlotTimes(packed: Field): { boundAtSlot: UInt32; freedAtSlot: UInt32 } {
94
+ // toBits(64) enforces the high 190 bits are zero — belt-and-suspenders
95
+ // since we only ever write via packSlotTimes, but keeps the circuit
96
+ // sound against an adversarially-crafted slot in a future upgrade.
97
+ const bits = packed.toBits(64);
98
+ const freedAtSlot = UInt32.Unsafe.fromField(Field.fromBits(bits.slice(0, 32)));
99
+ const boundAtSlot = UInt32.Unsafe.fromField(Field.fromBits(bits.slice(32, 64)));
100
+ return { boundAtSlot, freedAtSlot };
101
+ }
102
+
103
+ // Fold the parallel slot arrays into `deviceSlotsRoot`. Same order every
104
+ // time — occupied[0], freedAt[0], occupied[1], freedAt[1], ... — so a
105
+ // buyer that reconstructs the fold off-chain (verifier, dashboard) gets
106
+ // the same commitment the circuit computed.
107
+ export function computeDeviceSlotsRoot(
108
+ occupied: Field[],
109
+ freedAt: Field[],
110
+ ): Field {
111
+ if (occupied.length !== DEVICE_SLOT_CAP_N || freedAt.length !== DEVICE_SLOT_CAP_N) {
112
+ throw new Error(
113
+ `computeDeviceSlotsRoot expects exactly ${DEVICE_SLOT_CAP_N} entries in each array ` +
114
+ `(got occupied=${occupied.length}, freedAt=${freedAt.length})`,
115
+ );
116
+ }
117
+ const fields: Field[] = [];
118
+ for (let i = 0; i < DEVICE_SLOT_CAP_N; i++) {
119
+ fields.push(occupied[i], freedAt[i]);
120
+ }
121
+ return Poseidon.hash(fields);
122
+ }
123
+
124
+ // Per-slot payload. The Struct wrapper is what lets o1js serialize this
125
+ // inside larger provable structures — it also gives us a fixed
126
+ // two-Field width so DeviceSlots.slots can be a `Provable.Array` of a
127
+ // well-known type instead of a bag of loose Fields.
128
+ //
129
+ // Same `const X: any = Struct(...)` pattern as contractInterface.ts —
130
+ // annotating as `any` sidesteps TS2742 (o1js sits outside the package
131
+ // rootDir under npm hoisting, so tsc can't emit portable declarations
132
+ // for the inferred Struct class). Instance methods and `static empty()`
133
+ // therefore live as standalone helpers below rather than on the class.
134
+ export const DeviceSlot: any = Struct({
135
+ occupied: Field, // 0 or Poseidon(devicePubKeyHash)
136
+ freedAt: Field, // packSlotTimes(boundAtSlot, freedAtSlot)
137
+ });
138
+ export type DeviceSlot = any;
139
+
140
+ export function emptyDeviceSlot(): DeviceSlot {
141
+ return new DeviceSlot({ occupied: Field(0), freedAt: Field(0) });
142
+ }
143
+
144
+ // Fixed-width slot array. `Provable.Array(DeviceSlot, N)` promises the
145
+ // circuit an exact length so witnesses can address slots by static index.
146
+ export const DeviceSlots: any = Struct({
147
+ slots: Provable.Array(DeviceSlot, DEVICE_SLOT_CAP_N),
148
+ });
149
+ export type DeviceSlots = any;
150
+
151
+ export function emptyDeviceSlots(): DeviceSlots {
152
+ return new DeviceSlots({
153
+ slots: Array.from({ length: DEVICE_SLOT_CAP_N }, () => emptyDeviceSlot()),
154
+ });
155
+ }
156
+
157
+ // In-circuit fold — takes a DeviceSlots value so it composes cleanly
158
+ // inside `@method` bodies. The array length is fixed by the Struct's
159
+ // Provable.Array declaration, so no runtime length guard is needed.
160
+ export function deviceSlotsHash(ds: DeviceSlots): Field {
161
+ const fields: Field[] = [];
162
+ for (const s of ds.slots) {
163
+ fields.push(s.occupied, s.freedAt);
164
+ }
165
+ return Poseidon.hash(fields);
166
+ }
167
+
168
+ // The leaf value itself. `LicensingApp.buyLicense` builds one of these
169
+ // with EMPTY_DEVICE_SLOTS_ROOT and writes leafHash(leaf) into licensesRoot;
170
+ // subsequent mutations (renew, refund, migrate, bind, unbind) each build
171
+ // a new leaf with the appropriate field(s) updated and write its hash.
172
+ export const LicenseLeaf: any = Struct({
173
+ licenseHash: Field,
174
+ expirySlot: UInt32,
175
+ cap: UInt32,
176
+ deviceSlotsRoot: Field,
177
+ deviceSlotsFilled: UInt32,
178
+ });
179
+ export type LicenseLeaf = any;
180
+
181
+ export function leafHash(leaf: LicenseLeaf): Field {
182
+ return Poseidon.hash([
183
+ leaf.licenseHash,
184
+ leaf.expirySlot.value,
185
+ leaf.cap.value,
186
+ leaf.deviceSlotsRoot,
187
+ leaf.deviceSlotsFilled.value,
188
+ ]);
189
+ }
190
+
191
+ // Construct the leaf a fresh buy writes into the tree — no devices bound
192
+ // yet, filled counter at zero, slot-fold at the precomputed empty root.
193
+ export function freshLeaf(
194
+ licenseHash: Field,
195
+ expirySlot: UInt32,
196
+ cap: UInt32,
197
+ ): LicenseLeaf {
198
+ return new LicenseLeaf({
199
+ licenseHash,
200
+ expirySlot,
201
+ cap,
202
+ deviceSlotsRoot: EMPTY_DEVICE_SLOTS_ROOT,
203
+ deviceSlotsFilled: UInt32.zero,
204
+ });
205
+ }
206
+
207
+ // Reconstruct the leaf that lives at `record.licenseHash` in the licensesRoot
208
+ // MerkleMap. `LicenseRecord` optionally persists the device-binding fields;
209
+ // anything missing falls back to the fresh-leaf defaults, matching the state
210
+ // a just-issued license was minted with.
211
+ export function leafFromRecord(record: LicenseRecord): LicenseLeaf {
212
+ return new LicenseLeaf({
213
+ licenseHash: Field(record.licenseHash),
214
+ expirySlot: UInt32.from(record.expirySlot),
215
+ cap: UInt32.from(record.deviceCap ?? 0),
216
+ deviceSlotsRoot: record.deviceSlotsRoot !== undefined
217
+ ? Field(record.deviceSlotsRoot)
218
+ : EMPTY_DEVICE_SLOTS_ROOT,
219
+ deviceSlotsFilled: UInt32.from(record.deviceSlotsFilled ?? 0),
220
+ });
221
+ }
@@ -0,0 +1,108 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * licenseRecord.ts
6
+ *
7
+ * The `LicenseRecord` shape and related pure types/constants. Split out from
8
+ * licenseStore.ts (which pulls in Node `fs`) so browser-side modules — the
9
+ * buy client, the stats client, the country-stats computation — can consume
10
+ * the same type without dragging in filesystem code. licenseStore.ts
11
+ * re-exports these to keep existing Node imports working.
12
+ */
13
+
14
+ // MINA→fiat rate snapshot captured at the moment a business event happens
15
+ // (registration, purchase, renewal). Immutable — the value at time of event
16
+ // is what tax authorities want, so the keeper snapshots against the same
17
+ // 5-minute CoinGecko cache used by receipts and never re-fetches. Records
18
+ // created before the very first successful CoinGecko response get no
19
+ // snapshot; dashboards render fiat as `—` for those.
20
+ export type FiatRateSnapshot = {
21
+ minaEurRate: number;
22
+ minaUsdRate: number;
23
+ minaGbpRate: number;
24
+ recordedAt: string;
25
+ };
26
+
27
+ export type LicenseRecord = {
28
+ zkAppAddress: string; // REQUIRED — composite key with licenseHash
29
+ licenseHash: string; // Poseidon([pk.x, pk.isOdd.toField()]) over the buyer's passphrase-derived Pallas Schnorr pubkey — see ownershipLicenseHash.ts
30
+ expirySlot: number; // 0 = refunded / empty
31
+ purchaseSlot: number; // block slot when purchased (0 after escrow released/refunded)
32
+ purchaseAmount: string; // nanomina paid (as string to avoid BigInt serialisation issues)
33
+ txHash: string;
34
+ createdAt: string;
35
+ // The three fields below reconstruct the on-chain LicenseLeaf so the keeper
36
+ // can rebuild licensesRoot and produce witnesses for renew/refund/migrate.
37
+ // (The leaf's owner-pubkey commitment lives in `licenseHash` itself —
38
+ // buyLicense asserts licenseHash == Poseidon(pk.x, pk.isOdd) — so there is
39
+ // no separate ownerPubKeyHash field.)
40
+ deviceCap?: number; // per-license device cap (0 = binding disabled)
41
+ deviceSlotsRoot?: string; // Poseidon fold over the fixed-width slot array
42
+ deviceSlotsFilled?: number; // count of currently-occupied slots
43
+ // Populated by eventSyncLoop from DeviceBound/DeviceUnbound events — array
44
+ // position IS slotIndex, absent entries or entries with `deviceCommitment === '0'`
45
+ // are empty. Source of truth is on-chain; this mirror is for the API surface.
46
+ devices?: Array<{
47
+ slotIndex: number;
48
+ deviceCommitment: string; // "0" = empty slot; otherwise Poseidon(devicePubKeyHash)
49
+ boundAtSlot: number; // 0 for empty
50
+ freedAtSlot: number; // 0 for pristine; the slot when last unbind fired
51
+ }>;
52
+ buyerAddress?: string; // buyer's public key (B62q...) — required for escrow commitment
53
+ buyerCountry?: string; // ISO 3166-1 alpha-2 self-declared buyer jurisdiction (required at buy time; optional here for backward-compat with pre-existing records)
54
+ buyerZip?: string; // Buyer-declared postal code — required at buy time only when buyerCountry === 'US' (state-level sales-tax attribution). Optional here for backward-compat and non-US buyers.
55
+ pending?: boolean; // true if staged at prove-time but not yet confirmed by chain events
56
+ provedAtSlot?: number; // slot at which prove succeeded — used by reaper to drop unsubmitted records
57
+ // Captured at licenseIssued and never mutated by renewal. Lets stats decide
58
+ // who's past their first paid period without re-walking events.
59
+ initialExpirySlot?: number;
60
+ // Back-derived from (initialExpirySlot - purchaseSlot) at issue time. Lets
61
+ // licensesByTier roll up active counts without keeping the issued slot.
62
+ tier?: 'monthly' | 'yearly' | 'fiveYear' | 'perpetual';
63
+ // True after a licenseRenewed event has been observed. Lets the stats
64
+ // accumulator detect the FIRST renewal per license without re-counting.
65
+ renewedAtLeastOnce?: boolean;
66
+ // True after a refundIssued event. Distinct from expirySlot=0 for legacy
67
+ // records that lacked refund tracking.
68
+ refunded?: boolean;
69
+ // True after a fundsReleased event. Distinct from purchaseAmount=0 so stats
70
+ // can compute released revenue without re-walking events.
71
+ released?: boolean;
72
+ releaseSlot?: number;
73
+ // Tx hash of the fundsReleased broadcast. Persisted so the vendor's
74
+ // transaction feed can link the release row to the explorer. Optional for
75
+ // backward-compat: pre-tracking records and archive-replayed events
76
+ // (which don't carry the tx hash) simply omit it.
77
+ releaseTxHash?: string;
78
+ // Each renewal pushes { slot, amount, newExpiry, txHash?, fiatSnapshot? }
79
+ // where amount is the nanomina paid. newExpiry is the resulting expiry —
80
+ // used as a dedup key so confirm-time entries don't double up when archive
81
+ // sync later replays the same renewedEvent. fiatSnapshot captures the
82
+ // MINA→fiat rates at renewal confirm time (missing on archive-replayed
83
+ // renewals, which have no live keeper context).
84
+ renewals?: Array<{ slot: number; amount: string; newExpiry: number; txHash?: string; fiatSnapshot?: FiatRateSnapshot }>;
85
+ // MINA→fiat rates captured at buy confirm time. Immutable — the rate at
86
+ // time of purchase is what tax authorities want. Missing on records created
87
+ // before the first successful CoinGecko response and on archive-replayed
88
+ // purchases (dashboards render fiat as `—`).
89
+ fiatSnapshot?: FiatRateSnapshot;
90
+ // ISO timestamp of the buyer's express waiver of the 14-day refund window,
91
+ // captured at buy time when a FREEZE_AFTER_SLOT was scheduled on the
92
+ // keeper. Absent for normal (non-freeze-window) buys. Kept for audit /
93
+ // dispute purposes — the waiver is the buyer's acknowledgment that the
94
+ // scheduled hardfork can truncate their refund window.
95
+ refundWaiverAcceptedAt?: string;
96
+ // True when the buy was minted through the no-escrow circuit method
97
+ // (buyLicenseNoEscrow). Funds went straight to vendor + platform (98/2)
98
+ // rather than into the contract's escrow tree, so there is nothing to
99
+ // refund. The buyer accepted this at purchase (see refundWaiverAcceptedAt).
100
+ // The UI uses this flag to hide the "Refund" CTA on the licenses page.
101
+ escrowless?: boolean;
102
+ };
103
+
104
+ // Reap pending records this many slots after prove time if no event ever lands.
105
+ // 60 slots ≈ 90 minutes — a generous window for tx inclusion under devnet conditions.
106
+ export const PENDING_REAP_SLOTS = 60;
107
+
108
+ export type LicenseStatus = 'active' | 'refunded' | 'expired' | 'unknown';