@totemsdk/wots-lease 0.1.1 → 0.1.3

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/src/watermark.ts DELETED
@@ -1,234 +0,0 @@
1
- /**
2
- * WotsWatermarkStore — canonical v3 implementation
3
- *
4
- * - Reads v1 (flat usedIndices) and v2 (per-address usedIndices) automatically on load.
5
- * - Writes only v3.
6
- * - Enforces monotonicity: unavailable map can only grow, cursors can only advance.
7
- * - Storage key unchanged ('totem_wots_watermark') to avoid storage churn.
8
- */
9
-
10
- import type { StorageAdapter, LoggerAdapter } from '@totemsdk/core';
11
- import { NoopLogger } from '@totemsdk/core';
12
- import type {
13
- WotsWatermarkState,
14
- TreeWatermark,
15
- SigningIndices,
16
- UnavailableReason,
17
- LocalWatermark,
18
- } from './types.js';
19
- import { WatermarkMonotonicityError, WatermarkExhaustedError } from './errors.js';
20
-
21
- const STORAGE_KEY = 'totem_wots_watermark';
22
- const MAX_L = 64;
23
- const CAPACITY_PER_TREE = MAX_L * MAX_L * MAX_L;
24
- const DEFAULT_TREE = 'default';
25
-
26
- export function flatIndex(idx: SigningIndices): number {
27
- return idx.addressIndex * MAX_L * MAX_L + idx.l1 * MAX_L + idx.l2;
28
- }
29
-
30
- export function fromFlatIndex(flat: number): SigningIndices {
31
- const addressIndex = Math.floor(flat / (MAX_L * MAX_L));
32
- const rem = flat % (MAX_L * MAX_L);
33
- const l1 = Math.floor(rem / MAX_L);
34
- const l2 = rem % MAX_L;
35
- return { addressIndex, l1, l2 };
36
- }
37
-
38
- function emptyTree(treeId: string): TreeWatermark {
39
- return { treeId, addressCursor: 0, l1Cursor: 0, l2Cursor: 0, unavailable: {} };
40
- }
41
-
42
- function nextIndices(cur: SigningIndices): SigningIndices | null {
43
- let { addressIndex, l1, l2 } = cur;
44
- l2++;
45
- if (l2 >= MAX_L) { l2 = 0; l1++; }
46
- if (l1 >= MAX_L) { l1 = 0; addressIndex++; }
47
- if (addressIndex >= MAX_L) return null;
48
- return { addressIndex, l1, l2 };
49
- }
50
-
51
- type V1State = { next_addressIndex?: number; next_l1?: number; next_l2?: number; usedIndices?: Array<[number, number, number]> };
52
- type V2State = { version: 2; addresses: Record<number, { next_l1: number; next_l2: number; usedIndices: [number, number][] }> };
53
- type V3State = WotsWatermarkState;
54
- type RawState = V1State | V2State | V3State | null;
55
-
56
- function migrateToV3(raw: RawState): WotsWatermarkState {
57
- if (!raw) {
58
- return { version: 3, trees: {} };
59
- }
60
-
61
- if ('version' in raw && (raw as { version: number }).version === 3) {
62
- return raw as V3State;
63
- }
64
-
65
- if ('version' in raw && (raw as { version: number }).version === 2) {
66
- const v2 = raw as V2State;
67
- const tree = emptyTree(DEFAULT_TREE);
68
- let maxFlat = -1;
69
- for (const [addrIdxStr, addrData] of Object.entries(v2.addresses)) {
70
- const addressIndex = Number(addrIdxStr);
71
- for (const [l1, l2] of addrData.usedIndices) {
72
- const f = flatIndex({ addressIndex, l1, l2 });
73
- tree.unavailable[f] = 'committed';
74
- if (f > maxFlat) maxFlat = f;
75
- }
76
- const curFlat = flatIndex({ addressIndex, l1: addrData.next_l1, l2: addrData.next_l2 });
77
- if (curFlat > maxFlat) maxFlat = curFlat;
78
- }
79
- if (maxFlat >= 0) {
80
- const cur = fromFlatIndex(maxFlat);
81
- tree.addressCursor = cur.addressIndex;
82
- tree.l1Cursor = cur.l1;
83
- tree.l2Cursor = cur.l2;
84
- }
85
- return { version: 3, trees: { [DEFAULT_TREE]: tree } };
86
- }
87
-
88
- const v1 = raw as V1State;
89
- const tree = emptyTree(DEFAULT_TREE);
90
- for (const [ai, l1, l2] of v1.usedIndices ?? []) {
91
- const f = flatIndex({ addressIndex: ai, l1, l2 });
92
- tree.unavailable[f] = 'committed';
93
- }
94
- tree.addressCursor = v1.next_addressIndex ?? 0;
95
- tree.l1Cursor = v1.next_l1 ?? 0;
96
- tree.l2Cursor = v1.next_l2 ?? 0;
97
- return { version: 3, trees: { [DEFAULT_TREE]: tree } };
98
- }
99
-
100
- export class WotsWatermarkStore {
101
- private state: WotsWatermarkState | null = null;
102
- private _initialized = false;
103
- private readonly logger: LoggerAdapter;
104
-
105
- constructor(
106
- private readonly storage: StorageAdapter,
107
- logger: LoggerAdapter = new NoopLogger(),
108
- ) {
109
- this.logger = logger;
110
- }
111
-
112
- async initialize(): Promise<void> {
113
- if (this._initialized) return;
114
- const raw = await this.storage.get<RawState>(STORAGE_KEY);
115
- this.state = migrateToV3(raw);
116
- if (!('version' in (raw ?? {})) || (raw as { version?: number }).version !== 3) {
117
- await this.persist();
118
- this.logger.info('[WotsWatermarkStore] Migrated to v3');
119
- }
120
- this._initialized = true;
121
- }
122
-
123
- private ensureInit(): WotsWatermarkState {
124
- if (!this.state) throw new Error('WotsWatermarkStore not initialized — call initialize() first');
125
- return this.state;
126
- }
127
-
128
- private async persist(): Promise<void> {
129
- await this.storage.set(STORAGE_KEY, this.state);
130
- }
131
-
132
- private getOrCreateTree(treeId: string): TreeWatermark {
133
- const s = this.ensureInit();
134
- if (!s.trees[treeId]) {
135
- s.trees[treeId] = emptyTree(treeId);
136
- }
137
- return s.trees[treeId];
138
- }
139
-
140
- getNextIndices(treeId: string): SigningIndices {
141
- const tree = this.getOrCreateTree(treeId);
142
- let cur: SigningIndices = {
143
- addressIndex: tree.addressCursor,
144
- l1: tree.l1Cursor,
145
- l2: tree.l2Cursor,
146
- };
147
- let attempts = 0;
148
- while (attempts < CAPACITY_PER_TREE) {
149
- if (!tree.unavailable[flatIndex(cur)]) return cur;
150
- const nxt = nextIndices(cur);
151
- if (!nxt) break;
152
- cur = nxt;
153
- attempts++;
154
- }
155
- throw new WatermarkExhaustedError(treeId);
156
- }
157
-
158
- async markUnavailable(
159
- treeId: string,
160
- indices: SigningIndices,
161
- reason: UnavailableReason,
162
- ): Promise<void> {
163
- const tree = this.getOrCreateTree(treeId);
164
- const f = flatIndex(indices);
165
- tree.unavailable[f] = reason;
166
- const nxt = nextIndices(indices);
167
- if (nxt) {
168
- const nxtFlat = flatIndex(nxt);
169
- const curFlat = flatIndex({ addressIndex: tree.addressCursor, l1: tree.l1Cursor, l2: tree.l2Cursor });
170
- if (nxtFlat > curFlat) {
171
- tree.addressCursor = nxt.addressIndex;
172
- tree.l1Cursor = nxt.l1;
173
- tree.l2Cursor = nxt.l2;
174
- }
175
- }
176
- await this.persist();
177
- }
178
-
179
- isUnavailable(treeId: string, indices: SigningIndices): boolean {
180
- const s = this.ensureInit();
181
- const tree = s.trees[treeId];
182
- if (!tree) return false;
183
- return flatIndex(indices) in tree.unavailable;
184
- }
185
-
186
- async save(treeId: string, patch: Partial<TreeWatermark>): Promise<void> {
187
- const s = this.ensureInit();
188
- const existing = s.trees[treeId] ?? emptyTree(treeId);
189
- const merged: TreeWatermark = { ...existing, ...patch, treeId };
190
-
191
- const existingFlat = flatIndex({ addressIndex: existing.addressCursor, l1: existing.l1Cursor, l2: existing.l2Cursor });
192
- const newFlat = flatIndex({ addressIndex: merged.addressCursor, l1: merged.l1Cursor, l2: merged.l2Cursor });
193
- if (newFlat < existingFlat) {
194
- throw new WatermarkMonotonicityError(
195
- `Cannot decrease watermark cursor for ${treeId}: ${existingFlat} → ${newFlat}`,
196
- );
197
- }
198
-
199
- const existingUnavailCount = Object.keys(existing.unavailable).length;
200
- const newUnavailCount = Object.keys(merged.unavailable).length;
201
- if (newUnavailCount < existingUnavailCount) {
202
- throw new WatermarkMonotonicityError(
203
- `Cannot shrink unavailable map for ${treeId}: ${existingUnavailCount} → ${newUnavailCount}`,
204
- );
205
- }
206
-
207
- s.trees[treeId] = merged;
208
- await this.persist();
209
- }
210
-
211
- getLocalWatermark(treeId: string): LocalWatermark {
212
- const s = this.ensureInit();
213
- const tree = s.trees[treeId] ?? emptyTree(treeId);
214
- return {
215
- treeId,
216
- addressCursor: tree.addressCursor,
217
- l1Cursor: tree.l1Cursor,
218
- l2Cursor: tree.l2Cursor,
219
- unavailableCount: Object.keys(tree.unavailable).length,
220
- capacity: CAPACITY_PER_TREE,
221
- lastSyncTimestamp: tree.lastSyncTimestamp,
222
- };
223
- }
224
-
225
- getRawState(): WotsWatermarkState {
226
- return this.ensureInit();
227
- }
228
-
229
- async clear(): Promise<void> {
230
- this.state = { version: 3, trees: {} };
231
- this._initialized = false;
232
- await this.storage.remove(STORAGE_KEY);
233
- }
234
- }