@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/index.ts DELETED
@@ -1,51 +0,0 @@
1
- export type {
2
- UnavailableReason,
3
- SigningIndices,
4
- LeaseStatus,
5
- TreeWatermark,
6
- WotsWatermarkState,
7
- LeaseCertificate,
8
- LeaseReservation,
9
- ReserveParams,
10
- LocalWatermark,
11
- ConflictRecord,
12
- SyncResult,
13
- WotsLeaseProvider,
14
- JournalEntry,
15
- DeviceKeyRange,
16
- PersonalLeaseNodeConfig,
17
- } from './types.js';
18
-
19
- export {
20
- WotsWatermarkStore,
21
- flatIndex,
22
- fromFlatIndex,
23
- } from './watermark.js';
24
-
25
- export { LeaseJournal } from './journal.js';
26
-
27
- export { LocalLeaseProvider } from './local.js';
28
-
29
- export { AxiaLeaseProvider } from './axia.js';
30
- export type { AxiaLeaseProviderConfig } from './axia.js';
31
-
32
- export { HybridLeaseProvider } from './hybrid.js';
33
- export type { HybridLeaseProviderConfig } from './hybrid.js';
34
-
35
- export {
36
- PersonalLeaseNodeProvider,
37
- P2PQuorumLeaseProvider,
38
- OnchainWatermarkProvider,
39
- } from './stubs.js';
40
-
41
- export { allocateDeviceRange, deviceSlotForAddressIndex } from './device.js';
42
-
43
- export {
44
- WatermarkMonotonicityError,
45
- WatermarkExhaustedError,
46
- LeaseNotFoundError,
47
- PersonalLeaseNodeNotConfiguredError,
48
- P2PQuorumNotImplementedError,
49
- OnchainWatermarkNotImplementedError,
50
- DeviceRangeViolationError,
51
- } from './errors.js';
package/src/journal.ts DELETED
@@ -1,52 +0,0 @@
1
- /**
2
- * LeaseJournal — append-only audit log for WOTS key-use events.
3
- * Preserves the full history: reserved → committed | burned | reserved-expired.
4
- */
5
-
6
- import type { StorageAdapter, LoggerAdapter } from '@totemsdk/core';
7
- import { NoopLogger } from '@totemsdk/core';
8
- import type { JournalEntry } from './types.js';
9
-
10
- const STORAGE_KEY = 'totem_wots_journal';
11
-
12
- export class LeaseJournal {
13
- private entries: JournalEntry[] = [];
14
- private _initialized = false;
15
-
16
- constructor(
17
- private readonly storage: StorageAdapter,
18
- private readonly logger: LoggerAdapter = new NoopLogger(),
19
- ) {}
20
-
21
- async initialize(): Promise<void> {
22
- if (this._initialized) return;
23
- const stored = await this.storage.get<JournalEntry[]>(STORAGE_KEY);
24
- this.entries = stored ?? [];
25
- this._initialized = true;
26
- }
27
-
28
- async append(entry: JournalEntry): Promise<void> {
29
- this.entries.push(entry);
30
- await this.storage.set(STORAGE_KEY, this.entries);
31
- this.logger.debug(`[LeaseJournal] ${entry.status} treeId=${entry.treeId} idx=${entry.wotsIndex} txId=${entry.txId ?? '-'}`);
32
- }
33
-
34
- getAll(): JournalEntry[] {
35
- return [...this.entries];
36
- }
37
-
38
- getByTree(treeId: string): JournalEntry[] {
39
- return this.entries.filter((e) => e.treeId === treeId);
40
- }
41
-
42
- getByReservation(reservationId: string): JournalEntry | undefined {
43
- return [...this.entries].reverse().find(
44
- (e) => (e as JournalEntry & { reservationId?: string }).reservationId === reservationId,
45
- );
46
- }
47
-
48
- async clear(): Promise<void> {
49
- this.entries = [];
50
- await this.storage.remove(STORAGE_KEY);
51
- }
52
- }
package/src/local.ts DELETED
@@ -1,196 +0,0 @@
1
- /**
2
- * LocalLeaseProvider — Layer 1: local durable ledger.
3
- *
4
- * Single-device, no network coordination.
5
- * All WOTS safety guaranteed by the local WotsWatermarkStore + LeaseJournal.
6
- */
7
-
8
- import type { StorageAdapter, LoggerAdapter } from '@totemsdk/core';
9
- import { NoopLogger } from '@totemsdk/core';
10
- import { LeaseStore, type StoredLease } from '@totemsdk/core';
11
- import type {
12
- WotsLeaseProvider,
13
- ReserveParams,
14
- LeaseReservation,
15
- LeaseCertificate,
16
- LocalWatermark,
17
- SyncResult,
18
- SigningIndices,
19
- } from './types.js';
20
- import { WotsWatermarkStore, flatIndex } from './watermark.js';
21
- import { LeaseJournal } from './journal.js';
22
- import { LeaseNotFoundError, DeviceRangeViolationError } from './errors.js';
23
-
24
- function randomId(): string {
25
- if (typeof crypto !== 'undefined' && crypto.randomUUID) {
26
- return crypto.randomUUID();
27
- }
28
- return Math.random().toString(36).slice(2) + Date.now().toString(36);
29
- }
30
-
31
- export class LocalLeaseProvider implements WotsLeaseProvider {
32
- private readonly watermark: WotsWatermarkStore;
33
- private readonly leaseStore: LeaseStore;
34
- private readonly journal: LeaseJournal;
35
- private _initialized = false;
36
- private readonly deviceId: string;
37
- /** In-memory map: reservationId → treeId (lost on restart; watermark survives). */
38
- private readonly _treeIdByReservation = new Map<string, string>();
39
-
40
- constructor(
41
- storage: StorageAdapter,
42
- private readonly logger: LoggerAdapter = new NoopLogger(),
43
- deviceId = 'local',
44
- ) {
45
- this.watermark = new WotsWatermarkStore(storage, logger);
46
- this.leaseStore = new LeaseStore(storage, logger);
47
- this.journal = new LeaseJournal(storage, logger);
48
- this.deviceId = deviceId;
49
- }
50
-
51
- async initialize(): Promise<void> {
52
- if (this._initialized) return;
53
- await this.watermark.initialize();
54
- await this.leaseStore.initialize();
55
- await this.journal.initialize();
56
- await this.recoverExpiredReservations();
57
- this._initialized = true;
58
- }
59
-
60
- private async recoverExpiredReservations(): Promise<void> {
61
- const now = Date.now();
62
- for (const lease of this.leaseStore.getAll()) {
63
- if (lease.status === 'active' && lease.expiresAt < now) {
64
- const treeId = this._treeIdByReservation.get(lease.leaseId) ?? 'default';
65
- await this.watermark.markUnavailable(treeId, lease.indices, 'reserved-expired');
66
- await this.leaseStore.updateStatus(lease.leaseId, 'expired');
67
- await this.journal.append({
68
- treeId,
69
- branchId: 'default',
70
- wotsIndex: flatIndex(lease.indices),
71
- indices: lease.indices,
72
- status: 'reserved-expired',
73
- timestamp: now,
74
- deviceId: this.deviceId,
75
- });
76
- }
77
- }
78
- }
79
-
80
- async reserveKeyUse(params: ReserveParams): Promise<LeaseReservation> {
81
- if (!this._initialized) await this.initialize();
82
- const treeId = params.treeId;
83
- const ttlMs = params.ttlMs ?? 120_000;
84
-
85
- const indices = this.watermark.getNextIndices(treeId);
86
-
87
- if (params.deviceId) {
88
- const range = this.getDeviceRange(params.deviceId);
89
- if (range && (indices.addressIndex < range.start || indices.addressIndex > range.end)) {
90
- throw new DeviceRangeViolationError(indices.addressIndex, range.start, range.end);
91
- }
92
- }
93
-
94
- const reservationId = randomId();
95
- const expiresAt = Date.now() + ttlMs;
96
-
97
- const lease: StoredLease = {
98
- leaseId: reservationId,
99
- leaseToken: reservationId,
100
- indices,
101
- expiresAt,
102
- status: 'active',
103
- createdAt: Date.now(),
104
- leaseTTL: ttlMs,
105
- };
106
- await this.leaseStore.save(lease);
107
-
108
- // Track treeId in memory so commit/burn can reference the right watermark tree
109
- this._treeIdByReservation.set(reservationId, treeId);
110
-
111
- await this.journal.append({
112
- treeId,
113
- branchId: params.branchId ?? 'default',
114
- wotsIndex: flatIndex(indices),
115
- indices,
116
- status: 'reserved',
117
- payloadHash: params.payloadHash,
118
- timestamp: Date.now(),
119
- deviceId: params.deviceId ?? this.deviceId,
120
- });
121
-
122
- return { reservationId, indices, expiresAt };
123
- }
124
-
125
- async commitKeyUse(reservationId: string, txId: string): Promise<void> {
126
- if (!this._initialized) await this.initialize();
127
- const lease = this.leaseStore.get(reservationId);
128
- if (!lease) throw new LeaseNotFoundError(reservationId);
129
-
130
- const treeId = this._treeIdByReservation.get(reservationId) ?? 'default';
131
- const indices: SigningIndices = lease.indices;
132
- await this.watermark.markUnavailable(treeId, indices, 'committed');
133
- await this.leaseStore.updateStatus(reservationId, 'finalized');
134
- this._treeIdByReservation.delete(reservationId);
135
-
136
- await this.journal.append({
137
- treeId,
138
- branchId: 'default',
139
- wotsIndex: flatIndex(indices),
140
- indices,
141
- status: 'committed',
142
- txId,
143
- timestamp: Date.now(),
144
- deviceId: this.deviceId,
145
- });
146
- }
147
-
148
- async burnReservation(reservationId: string, reason: string): Promise<void> {
149
- if (!this._initialized) await this.initialize();
150
- const lease = this.leaseStore.get(reservationId);
151
- if (!lease) throw new LeaseNotFoundError(reservationId);
152
-
153
- const treeId = this._treeIdByReservation.get(reservationId) ?? 'default';
154
- const indices: SigningIndices = lease.indices;
155
- await this.watermark.markUnavailable(treeId, indices, 'burned');
156
- await this.leaseStore.updateStatus(reservationId, 'cancelled');
157
- this._treeIdByReservation.delete(reservationId);
158
-
159
- this.logger.warn(`[LocalLeaseProvider] Burning reservation ${reservationId}: ${reason}`);
160
- await this.journal.append({
161
- treeId,
162
- branchId: 'default',
163
- wotsIndex: flatIndex(indices),
164
- indices,
165
- status: 'burned',
166
- timestamp: Date.now(),
167
- deviceId: this.deviceId,
168
- });
169
- }
170
-
171
- async getLocalWatermark(treeId: string): Promise<LocalWatermark> {
172
- if (!this._initialized) await this.initialize();
173
- return this.watermark.getLocalWatermark(treeId);
174
- }
175
-
176
- async publishWatermark(_treeId: string): Promise<void> {
177
- // Layer 1: no-op
178
- }
179
-
180
- async syncLeaseJournal(): Promise<SyncResult> {
181
- // Layer 1: no-op
182
- return { synced: true, conflicts: [] };
183
- }
184
-
185
- async verifyLeaseCertificate(cert?: LeaseCertificate): Promise<boolean> {
186
- if (cert === undefined) return true;
187
- return false;
188
- }
189
-
190
- private getDeviceRange(deviceId: string): { start: number; end: number } | null {
191
- const match = deviceId.match(/^device-?(\d+)$/i);
192
- if (!match) return null;
193
- const slot = parseInt(match[1], 10);
194
- return { start: slot * 8, end: slot * 8 + 7 };
195
- }
196
- }
package/src/stubs.ts DELETED
@@ -1,106 +0,0 @@
1
- /**
2
- * Stub implementations for Layers 3–5.
3
- * These throw descriptive errors until the full implementations land.
4
- */
5
-
6
- import type {
7
- WotsLeaseProvider,
8
- ReserveParams,
9
- LeaseReservation,
10
- LeaseCertificate,
11
- LocalWatermark,
12
- SyncResult,
13
- PersonalLeaseNodeConfig,
14
- } from './types.js';
15
- import {
16
- PersonalLeaseNodeNotConfiguredError,
17
- P2PQuorumNotImplementedError,
18
- OnchainWatermarkNotImplementedError,
19
- } from './errors.js';
20
-
21
- /**
22
- * Layer 3 — personal p2p lease node.
23
- *
24
- * Verifies ed25519 certs issued by a configured node public key.
25
- * Reserve/commit throws until the node is reachable — callers should
26
- * wrap with HybridLeaseProvider using a LocalLeaseProvider as the local layer.
27
- */
28
- export class PersonalLeaseNodeProvider implements WotsLeaseProvider {
29
- constructor(private readonly config: PersonalLeaseNodeConfig) {}
30
-
31
- reserveKeyUse(_params: ReserveParams): Promise<LeaseReservation> {
32
- throw new PersonalLeaseNodeNotConfiguredError();
33
- }
34
- commitKeyUse(_reservationId: string, _txId: string): Promise<void> {
35
- throw new PersonalLeaseNodeNotConfiguredError();
36
- }
37
- burnReservation(_reservationId: string, _reason: string): Promise<void> {
38
- throw new PersonalLeaseNodeNotConfiguredError();
39
- }
40
- getLocalWatermark(_treeId: string): Promise<LocalWatermark> {
41
- throw new PersonalLeaseNodeNotConfiguredError();
42
- }
43
- publishWatermark(_treeId: string): Promise<void> {
44
- throw new PersonalLeaseNodeNotConfiguredError();
45
- }
46
- syncLeaseJournal(): Promise<SyncResult> {
47
- throw new PersonalLeaseNodeNotConfiguredError();
48
- }
49
-
50
- async verifyLeaseCertificate(cert?: LeaseCertificate): Promise<boolean> {
51
- if (!cert) return false;
52
- if (cert.issuedBy !== this.config.nodePubkey) return false;
53
- if (cert.expiresAt <= Date.now()) return false;
54
- return true;
55
- }
56
- }
57
-
58
- /** Layer 4 — p2p replicated lease witnesses. */
59
- export class P2PQuorumLeaseProvider implements WotsLeaseProvider {
60
- reserveKeyUse(_params: ReserveParams): Promise<LeaseReservation> {
61
- throw new P2PQuorumNotImplementedError();
62
- }
63
- commitKeyUse(_reservationId: string, _txId: string): Promise<void> {
64
- throw new P2PQuorumNotImplementedError();
65
- }
66
- burnReservation(_reservationId: string, _reason: string): Promise<void> {
67
- throw new P2PQuorumNotImplementedError();
68
- }
69
- getLocalWatermark(_treeId: string): Promise<LocalWatermark> {
70
- throw new P2PQuorumNotImplementedError();
71
- }
72
- publishWatermark(_treeId: string): Promise<void> {
73
- throw new P2PQuorumNotImplementedError();
74
- }
75
- syncLeaseJournal(): Promise<SyncResult> {
76
- throw new P2PQuorumNotImplementedError();
77
- }
78
- verifyLeaseCertificate(_cert?: LeaseCertificate): Promise<boolean> {
79
- throw new P2PQuorumNotImplementedError();
80
- }
81
- }
82
-
83
- /** Layer 5 — on-chain watermark coin. */
84
- export class OnchainWatermarkProvider implements WotsLeaseProvider {
85
- reserveKeyUse(_params: ReserveParams): Promise<LeaseReservation> {
86
- throw new OnchainWatermarkNotImplementedError();
87
- }
88
- commitKeyUse(_reservationId: string, _txId: string): Promise<void> {
89
- throw new OnchainWatermarkNotImplementedError();
90
- }
91
- burnReservation(_reservationId: string, _reason: string): Promise<void> {
92
- throw new OnchainWatermarkNotImplementedError();
93
- }
94
- getLocalWatermark(_treeId: string): Promise<LocalWatermark> {
95
- throw new OnchainWatermarkNotImplementedError();
96
- }
97
- publishWatermark(_treeId: string): Promise<void> {
98
- throw new OnchainWatermarkNotImplementedError();
99
- }
100
- syncLeaseJournal(): Promise<SyncResult> {
101
- throw new OnchainWatermarkNotImplementedError();
102
- }
103
- verifyLeaseCertificate(_cert?: LeaseCertificate): Promise<boolean> {
104
- throw new OnchainWatermarkNotImplementedError();
105
- }
106
- }
package/src/types.ts DELETED
@@ -1,119 +0,0 @@
1
- /**
2
- * @totemsdk/wots-lease — canonical v3 watermark types and WotsLeaseProvider interface
3
- */
4
-
5
- export type UnavailableReason = 'committed' | 'burned' | 'reserved-expired';
6
-
7
- export interface SigningIndices {
8
- addressIndex: number;
9
- l1: number;
10
- l2: number;
11
- }
12
-
13
- export type LeaseStatus = 'pending' | 'active' | 'expired' | 'finalized' | 'cancelled';
14
-
15
- export interface TreeWatermark {
16
- treeId: string;
17
- deviceId?: string;
18
- branchId?: string;
19
- addressCursor: number;
20
- l1Cursor: number;
21
- l2Cursor: number;
22
- unavailable: Record<number, UnavailableReason>;
23
- lastSyncTimestamp?: number;
24
- }
25
-
26
- export interface WotsWatermarkState {
27
- version: 3;
28
- trees: Record<string, TreeWatermark>;
29
- }
30
-
31
- export interface LeaseCertificate {
32
- reservationId: string;
33
- treeId: string;
34
- branchId?: string;
35
- deviceId?: string;
36
- indices: SigningIndices;
37
- purpose?: string;
38
- payloadHash?: string;
39
- issuedBy: string;
40
- issuedAt: number;
41
- expiresAt: number;
42
- signature: string;
43
- }
44
-
45
- export interface LeaseReservation {
46
- reservationId: string;
47
- indices: SigningIndices;
48
- expiresAt: number;
49
- certificate?: LeaseCertificate;
50
- leaseToken?: string;
51
- }
52
-
53
- export interface ReserveParams {
54
- treeId: string;
55
- branchId?: string;
56
- purpose?: string;
57
- deviceId?: string;
58
- ttlMs?: number;
59
- payloadHash?: string;
60
- valueHint?: string;
61
- }
62
-
63
- export interface LocalWatermark {
64
- treeId: string;
65
- addressCursor: number;
66
- l1Cursor: number;
67
- l2Cursor: number;
68
- unavailableCount: number;
69
- capacity: number;
70
- lastSyncTimestamp?: number;
71
- }
72
-
73
- export interface ConflictRecord {
74
- treeId: string;
75
- localIndex: number;
76
- remoteIndex: number;
77
- timestamp: number;
78
- }
79
-
80
- export interface SyncResult {
81
- synced: boolean;
82
- conflicts: ConflictRecord[];
83
- advancedTo?: SigningIndices;
84
- }
85
-
86
- export interface WotsLeaseProvider {
87
- reserveKeyUse(params: ReserveParams): Promise<LeaseReservation>;
88
- commitKeyUse(reservationId: string, txId: string): Promise<void>;
89
- burnReservation(reservationId: string, reason: string): Promise<void>;
90
- getLocalWatermark(treeId: string): Promise<LocalWatermark>;
91
- publishWatermark(treeId: string): Promise<void>;
92
- syncLeaseJournal(): Promise<SyncResult>;
93
- verifyLeaseCertificate(cert?: LeaseCertificate): Promise<boolean>;
94
- }
95
-
96
- export interface JournalEntry {
97
- treeId: string;
98
- branchId: string;
99
- wotsIndex: number;
100
- indices: SigningIndices;
101
- status: 'reserved' | 'committed' | 'burned' | 'reserved-expired';
102
- payloadHash?: string;
103
- txId?: string;
104
- timestamp: number;
105
- deviceId: string;
106
- }
107
-
108
- export interface DeviceKeyRange {
109
- deviceId: string;
110
- startAddressIndex: number;
111
- endAddressIndex: number;
112
- addressCount: number;
113
- }
114
-
115
- export interface PersonalLeaseNodeConfig {
116
- nodeUrl: string;
117
- nodePubkey: string;
118
- authToken?: string;
119
- }