@totemsdk/wots-lease 0.1.2 → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +3 -3
- package/dist/axia.js +22 -17
- package/dist/device.js +6 -2
- package/dist/errors.js +17 -7
- package/dist/hybrid.js +5 -1
- package/dist/index.js +30 -8
- package/dist/journal.d.ts +1 -0
- package/dist/journal.js +52 -4
- package/dist/local.d.ts +4 -2
- package/dist/local.js +57 -26
- package/dist/stubs.d.ts +35 -12
- package/dist/stubs.js +108 -44
- package/dist/types.d.ts +4 -1
- package/dist/types.js +2 -1
- package/dist/watermark.js +15 -9
- package/package.json +36 -15
- package/src/__tests__/watermark.test.ts +0 -200
- package/src/axia.ts +0 -169
- package/src/device.ts +0 -40
- package/src/errors.ts +0 -57
- package/src/hybrid.ts +0 -98
- package/src/index.ts +0 -51
- package/src/journal.ts +0 -52
- package/src/local.ts +0 -196
- package/src/stubs.ts +0 -106
- package/src/types.ts +0 -119
- package/src/watermark.ts +0 -234
package/src/axia.ts
DELETED
|
@@ -1,169 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* AxiaLeaseProvider — wraps the Axia API's /v1/wots-hardened endpoints.
|
|
3
|
-
*
|
|
4
|
-
* Callers do NOT need to call /finalize separately — commitKeyUse() does it.
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import type { StorageAdapter, LoggerAdapter } from '@totemsdk/core';
|
|
8
|
-
import { NoopLogger, LeaseStore, type StoredLease } from '@totemsdk/core';
|
|
9
|
-
import { prepareLease, finalizeLease } from '@totemsdk/core';
|
|
10
|
-
import type {
|
|
11
|
-
WotsLeaseProvider,
|
|
12
|
-
ReserveParams,
|
|
13
|
-
LeaseReservation,
|
|
14
|
-
LeaseCertificate,
|
|
15
|
-
LocalWatermark,
|
|
16
|
-
SyncResult,
|
|
17
|
-
SigningIndices,
|
|
18
|
-
} from './types.js';
|
|
19
|
-
import { WotsWatermarkStore, flatIndex } from './watermark.js';
|
|
20
|
-
import { LeaseJournal } from './journal.js';
|
|
21
|
-
import { LeaseNotFoundError } from './errors.js';
|
|
22
|
-
|
|
23
|
-
export interface AxiaLeaseProviderConfig {
|
|
24
|
-
apiUrl: string;
|
|
25
|
-
apiKey: string;
|
|
26
|
-
rootPublicKey: string;
|
|
27
|
-
storage: StorageAdapter;
|
|
28
|
-
logger?: LoggerAdapter;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export class AxiaLeaseProvider implements WotsLeaseProvider {
|
|
32
|
-
private readonly watermark: WotsWatermarkStore;
|
|
33
|
-
private readonly leaseStore: LeaseStore;
|
|
34
|
-
private readonly journal: LeaseJournal;
|
|
35
|
-
private readonly apiUrl: string;
|
|
36
|
-
private readonly apiKey: string;
|
|
37
|
-
private readonly rootPublicKey: string;
|
|
38
|
-
private readonly logger: LoggerAdapter;
|
|
39
|
-
private _initialized = false;
|
|
40
|
-
|
|
41
|
-
constructor(config: AxiaLeaseProviderConfig) {
|
|
42
|
-
this.apiUrl = config.apiUrl;
|
|
43
|
-
this.apiKey = config.apiKey;
|
|
44
|
-
this.rootPublicKey = config.rootPublicKey;
|
|
45
|
-
this.logger = config.logger ?? new NoopLogger();
|
|
46
|
-
this.watermark = new WotsWatermarkStore(config.storage, this.logger);
|
|
47
|
-
this.leaseStore = new LeaseStore(config.storage, this.logger);
|
|
48
|
-
this.journal = new LeaseJournal(config.storage, this.logger);
|
|
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
|
-
this._initialized = true;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
async reserveKeyUse(params: ReserveParams): Promise<LeaseReservation> {
|
|
60
|
-
if (!this._initialized) await this.initialize();
|
|
61
|
-
|
|
62
|
-
const txId = params.payloadHash ?? `tx-${Date.now()}`;
|
|
63
|
-
const resp = await prepareLease(this.apiUrl, this.apiKey, {
|
|
64
|
-
txId,
|
|
65
|
-
rootPublicKey: this.rootPublicKey,
|
|
66
|
-
to: params.treeId,
|
|
67
|
-
amount: params.valueHint ?? '0',
|
|
68
|
-
ttlMs: params.ttlMs ?? 120_000,
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
const indices: SigningIndices = resp.lease;
|
|
72
|
-
const expiresAt = Date.now() + (params.ttlMs ?? 120_000);
|
|
73
|
-
const reservationId = resp.txId;
|
|
74
|
-
|
|
75
|
-
const lease: StoredLease = {
|
|
76
|
-
leaseId: reservationId,
|
|
77
|
-
leaseToken: resp.leaseToken,
|
|
78
|
-
indices,
|
|
79
|
-
expiresAt,
|
|
80
|
-
status: 'active',
|
|
81
|
-
createdAt: Date.now(),
|
|
82
|
-
leaseTTL: params.ttlMs ?? 120_000,
|
|
83
|
-
};
|
|
84
|
-
await this.leaseStore.save(lease);
|
|
85
|
-
|
|
86
|
-
await this.journal.append({
|
|
87
|
-
treeId: params.treeId,
|
|
88
|
-
branchId: params.branchId ?? 'default',
|
|
89
|
-
wotsIndex: flatIndex(indices),
|
|
90
|
-
indices,
|
|
91
|
-
status: 'reserved',
|
|
92
|
-
payloadHash: params.payloadHash,
|
|
93
|
-
timestamp: Date.now(),
|
|
94
|
-
deviceId: params.deviceId ?? 'axia',
|
|
95
|
-
});
|
|
96
|
-
|
|
97
|
-
return { reservationId, indices, expiresAt, leaseToken: resp.leaseToken };
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
async commitKeyUse(reservationId: string, txId: string): Promise<void> {
|
|
101
|
-
if (!this._initialized) await this.initialize();
|
|
102
|
-
const lease = this.leaseStore.get(reservationId);
|
|
103
|
-
if (!lease) throw new LeaseNotFoundError(reservationId);
|
|
104
|
-
|
|
105
|
-
await finalizeLease(this.apiUrl, this.apiKey, lease.leaseToken, txId);
|
|
106
|
-
|
|
107
|
-
const indices: SigningIndices = lease.indices;
|
|
108
|
-
await this.watermark.markUnavailable(
|
|
109
|
-
lease.indices.addressIndex.toString(),
|
|
110
|
-
indices,
|
|
111
|
-
'committed',
|
|
112
|
-
);
|
|
113
|
-
await this.leaseStore.updateStatus(reservationId, 'finalized');
|
|
114
|
-
|
|
115
|
-
await this.journal.append({
|
|
116
|
-
treeId: reservationId,
|
|
117
|
-
branchId: 'default',
|
|
118
|
-
wotsIndex: flatIndex(indices),
|
|
119
|
-
indices,
|
|
120
|
-
status: 'committed',
|
|
121
|
-
txId,
|
|
122
|
-
timestamp: Date.now(),
|
|
123
|
-
deviceId: 'axia',
|
|
124
|
-
});
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
async burnReservation(reservationId: string, reason: string): Promise<void> {
|
|
128
|
-
if (!this._initialized) await this.initialize();
|
|
129
|
-
const lease = this.leaseStore.get(reservationId);
|
|
130
|
-
if (!lease) throw new LeaseNotFoundError(reservationId);
|
|
131
|
-
|
|
132
|
-
const indices: SigningIndices = lease.indices;
|
|
133
|
-
await this.watermark.markUnavailable(
|
|
134
|
-
lease.indices.addressIndex.toString(),
|
|
135
|
-
indices,
|
|
136
|
-
'burned',
|
|
137
|
-
);
|
|
138
|
-
await this.leaseStore.updateStatus(reservationId, 'cancelled');
|
|
139
|
-
|
|
140
|
-
this.logger.warn(`[AxiaLeaseProvider] Burning reservation ${reservationId}: ${reason}`);
|
|
141
|
-
await this.journal.append({
|
|
142
|
-
treeId: reservationId,
|
|
143
|
-
branchId: 'default',
|
|
144
|
-
wotsIndex: flatIndex(indices),
|
|
145
|
-
indices,
|
|
146
|
-
status: 'burned',
|
|
147
|
-
timestamp: Date.now(),
|
|
148
|
-
deviceId: 'axia',
|
|
149
|
-
});
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
async getLocalWatermark(treeId: string): Promise<LocalWatermark> {
|
|
153
|
-
if (!this._initialized) await this.initialize();
|
|
154
|
-
return this.watermark.getLocalWatermark(treeId);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
async publishWatermark(_treeId: string): Promise<void> {
|
|
158
|
-
// Server maintains its own watermark via the lease API
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
async syncLeaseJournal(): Promise<SyncResult> {
|
|
162
|
-
return { synced: true, conflicts: [] };
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
async verifyLeaseCertificate(cert?: LeaseCertificate): Promise<boolean> {
|
|
166
|
-
if (cert === undefined) return true;
|
|
167
|
-
return false;
|
|
168
|
-
}
|
|
169
|
-
}
|
package/src/device.ts
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Device keyspace partitioning — Layer 2.
|
|
3
|
-
*
|
|
4
|
-
* Deterministic address-index range assignment per device slot.
|
|
5
|
-
* Does NOT accept a raw seed; the caller derives the TreeKey in @totemsdk/core.
|
|
6
|
-
*
|
|
7
|
-
* Layout (8 device slots × 8 addresses each = 64 total):
|
|
8
|
-
* device 0 → addressIndex 0–7
|
|
9
|
-
* device 1 → addressIndex 8–15
|
|
10
|
-
* device 2 → addressIndex 16–23
|
|
11
|
-
* ...
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
import type { DeviceKeyRange } from './types.js';
|
|
15
|
-
|
|
16
|
-
const ADDRESSES_PER_DEVICE = 8;
|
|
17
|
-
const MAX_DEVICE_SLOTS = 8;
|
|
18
|
-
|
|
19
|
-
export function allocateDeviceRange(params: {
|
|
20
|
-
deviceSlot: number;
|
|
21
|
-
deviceId: string;
|
|
22
|
-
}): DeviceKeyRange {
|
|
23
|
-
if (params.deviceSlot < 0 || params.deviceSlot >= MAX_DEVICE_SLOTS) {
|
|
24
|
-
throw new RangeError(
|
|
25
|
-
`Device slot must be 0–${MAX_DEVICE_SLOTS - 1}, got ${params.deviceSlot}`,
|
|
26
|
-
);
|
|
27
|
-
}
|
|
28
|
-
const startAddressIndex = params.deviceSlot * ADDRESSES_PER_DEVICE;
|
|
29
|
-
const endAddressIndex = startAddressIndex + ADDRESSES_PER_DEVICE - 1;
|
|
30
|
-
return {
|
|
31
|
-
deviceId: params.deviceId,
|
|
32
|
-
startAddressIndex,
|
|
33
|
-
endAddressIndex,
|
|
34
|
-
addressCount: ADDRESSES_PER_DEVICE,
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export function deviceSlotForAddressIndex(addressIndex: number): number {
|
|
39
|
-
return Math.floor(addressIndex / ADDRESSES_PER_DEVICE);
|
|
40
|
-
}
|
package/src/errors.ts
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
export class WatermarkMonotonicityError extends Error {
|
|
2
|
-
constructor(message: string) {
|
|
3
|
-
super(message);
|
|
4
|
-
this.name = 'WatermarkMonotonicityError';
|
|
5
|
-
}
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
export class WatermarkExhaustedError extends Error {
|
|
9
|
-
constructor(public readonly treeId: string) {
|
|
10
|
-
super(`WOTS keyspace exhausted for tree: ${treeId}`);
|
|
11
|
-
this.name = 'WatermarkExhaustedError';
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export class LeaseNotFoundError extends Error {
|
|
16
|
-
constructor(public readonly reservationId: string) {
|
|
17
|
-
super(`Lease reservation not found: ${reservationId}`);
|
|
18
|
-
this.name = 'LeaseNotFoundError';
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export class PersonalLeaseNodeNotConfiguredError extends Error {
|
|
23
|
-
constructor() {
|
|
24
|
-
super(
|
|
25
|
-
'PersonalLeaseNodeProvider requires a running lookup node. ' +
|
|
26
|
-
'Deploy @totemsdk/lookup-node and configure { nodeUrl, nodePubkey }.',
|
|
27
|
-
);
|
|
28
|
-
this.name = 'PersonalLeaseNodeNotConfiguredError';
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export class P2PQuorumNotImplementedError extends Error {
|
|
33
|
-
constructor() {
|
|
34
|
-
super('P2PQuorumLeaseProvider is not yet implemented.');
|
|
35
|
-
this.name = 'P2PQuorumNotImplementedError';
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export class OnchainWatermarkNotImplementedError extends Error {
|
|
40
|
-
constructor() {
|
|
41
|
-
super('OnchainWatermarkProvider is not yet implemented.');
|
|
42
|
-
this.name = 'OnchainWatermarkNotImplementedError';
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export class DeviceRangeViolationError extends Error {
|
|
47
|
-
constructor(
|
|
48
|
-
public readonly addressIndex: number,
|
|
49
|
-
public readonly allowedStart: number,
|
|
50
|
-
public readonly allowedEnd: number,
|
|
51
|
-
) {
|
|
52
|
-
super(
|
|
53
|
-
`Address index ${addressIndex} is outside device range [${allowedStart}, ${allowedEnd}]`,
|
|
54
|
-
);
|
|
55
|
-
this.name = 'DeviceRangeViolationError';
|
|
56
|
-
}
|
|
57
|
-
}
|
package/src/hybrid.ts
DELETED
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* HybridLeaseProvider — recommended production default.
|
|
3
|
-
*
|
|
4
|
-
* Always uses local first, then gates on node cert and/or quorum attestation
|
|
5
|
-
* for transactions above a configurable value threshold.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import type {
|
|
9
|
-
WotsLeaseProvider,
|
|
10
|
-
ReserveParams,
|
|
11
|
-
LeaseReservation,
|
|
12
|
-
LeaseCertificate,
|
|
13
|
-
LocalWatermark,
|
|
14
|
-
SyncResult,
|
|
15
|
-
} from './types.js';
|
|
16
|
-
import type { LocalLeaseProvider } from './local.js';
|
|
17
|
-
import type { PersonalLeaseNodeProvider } from './stubs.js';
|
|
18
|
-
import type { P2PQuorumLeaseProvider } from './stubs.js';
|
|
19
|
-
import type { OnchainWatermarkProvider } from './stubs.js';
|
|
20
|
-
|
|
21
|
-
export interface HybridLeaseProviderConfig {
|
|
22
|
-
local: LocalLeaseProvider;
|
|
23
|
-
node?: PersonalLeaseNodeProvider;
|
|
24
|
-
quorum?: P2PQuorumLeaseProvider;
|
|
25
|
-
onchain?: OnchainWatermarkProvider;
|
|
26
|
-
threshold?: number;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export class HybridLeaseProvider implements WotsLeaseProvider {
|
|
30
|
-
private readonly local: LocalLeaseProvider;
|
|
31
|
-
private readonly node?: PersonalLeaseNodeProvider;
|
|
32
|
-
private readonly quorum?: P2PQuorumLeaseProvider;
|
|
33
|
-
private readonly onchain?: OnchainWatermarkProvider;
|
|
34
|
-
private readonly threshold: number;
|
|
35
|
-
|
|
36
|
-
constructor(config: HybridLeaseProviderConfig) {
|
|
37
|
-
this.local = config.local;
|
|
38
|
-
this.node = config.node;
|
|
39
|
-
this.quorum = config.quorum;
|
|
40
|
-
this.onchain = config.onchain;
|
|
41
|
-
this.threshold = config.threshold ?? Infinity;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
private isHighValue(params: ReserveParams): boolean {
|
|
45
|
-
if (!params.valueHint) return false;
|
|
46
|
-
const val = parseFloat(params.valueHint);
|
|
47
|
-
return !isNaN(val) && val >= this.threshold;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
async reserveKeyUse(params: ReserveParams): Promise<LeaseReservation> {
|
|
51
|
-
const reservation = await this.local.reserveKeyUse(params);
|
|
52
|
-
|
|
53
|
-
if (this.isHighValue(params)) {
|
|
54
|
-
if (this.node) {
|
|
55
|
-
try {
|
|
56
|
-
const nodeReservation = await this.node.reserveKeyUse(params);
|
|
57
|
-
return { ...reservation, certificate: nodeReservation.certificate };
|
|
58
|
-
} catch {
|
|
59
|
-
// Node unavailable — continue with local only
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
return reservation;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
commitKeyUse(reservationId: string, txId: string): Promise<void> {
|
|
68
|
-
return this.local.commitKeyUse(reservationId, txId);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
burnReservation(reservationId: string, reason: string): Promise<void> {
|
|
72
|
-
return this.local.burnReservation(reservationId, reason);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
getLocalWatermark(treeId: string): Promise<LocalWatermark> {
|
|
76
|
-
return this.local.getLocalWatermark(treeId);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
publishWatermark(treeId: string): Promise<void> {
|
|
80
|
-
if (this.node) {
|
|
81
|
-
return this.node.publishWatermark(treeId).catch(() => this.local.publishWatermark(treeId));
|
|
82
|
-
}
|
|
83
|
-
return this.local.publishWatermark(treeId);
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
syncLeaseJournal(): Promise<SyncResult> {
|
|
87
|
-
if (this.node) {
|
|
88
|
-
return this.node.syncLeaseJournal().catch(() => this.local.syncLeaseJournal());
|
|
89
|
-
}
|
|
90
|
-
return this.local.syncLeaseJournal();
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
async verifyLeaseCertificate(cert?: LeaseCertificate): Promise<boolean> {
|
|
94
|
-
if (!cert) return this.local.verifyLeaseCertificate(cert);
|
|
95
|
-
if (this.node) return this.node.verifyLeaseCertificate(cert);
|
|
96
|
-
return false;
|
|
97
|
-
}
|
|
98
|
-
}
|
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
|
-
}
|