@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Totem SDK Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -92,6 +92,6 @@ entries.forEach(e => console.log(e.flatIndex, e.allocatedAt, e.committedAt));
92
92
 
93
93
  ## See also
94
94
 
95
- - [`@totemsdk/core`](../core) — WOTS primitives this package protects
96
- - [`@totemsdk/lookup-node`](../lookup-node) — `LeaseCoordinator` for multi-client setups
97
- - [`@totemsdk/omnia`](../omnia) — integrates wots-lease to protect channel signing slots
95
+ - [`@totemsdk/core`](https://www.npmjs.com/package/@totemsdk/core) — WOTS primitives this package protects
96
+ - [`@totemsdk/lookup-node`](https://www.npmjs.com/package/@totemsdk/lookup-node) — `LeaseCoordinator` for multi-client setups
97
+ - [`@totemsdk/omnia`](https://www.npmjs.com/package/@totemsdk/omnia) — integrates wots-lease to protect channel signing slots
package/dist/axia.js CHANGED
@@ -1,23 +1,26 @@
1
+ "use strict";
1
2
  /**
2
3
  * AxiaLeaseProvider — wraps the Axia API's /v1/wots-hardened endpoints.
3
4
  *
4
5
  * Callers do NOT need to call /finalize separately — commitKeyUse() does it.
5
6
  */
6
- import { NoopLogger, LeaseStore } from '@totemsdk/core';
7
- import { prepareLease, finalizeLease } from '@totemsdk/core';
8
- import { WotsWatermarkStore, flatIndex } from './watermark.js';
9
- import { LeaseJournal } from './journal.js';
10
- import { LeaseNotFoundError } from './errors.js';
11
- export class AxiaLeaseProvider {
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.AxiaLeaseProvider = void 0;
9
+ const core_1 = require("@totemsdk/core");
10
+ const core_2 = require("@totemsdk/core");
11
+ const watermark_js_1 = require("./watermark.js");
12
+ const journal_js_1 = require("./journal.js");
13
+ const errors_js_1 = require("./errors.js");
14
+ class AxiaLeaseProvider {
12
15
  constructor(config) {
13
16
  this._initialized = false;
14
17
  this.apiUrl = config.apiUrl;
15
18
  this.apiKey = config.apiKey;
16
19
  this.rootPublicKey = config.rootPublicKey;
17
- this.logger = config.logger ?? new NoopLogger();
18
- this.watermark = new WotsWatermarkStore(config.storage, this.logger);
19
- this.leaseStore = new LeaseStore(config.storage, this.logger);
20
- this.journal = new LeaseJournal(config.storage, this.logger);
20
+ this.logger = config.logger ?? new core_1.NoopLogger();
21
+ this.watermark = new watermark_js_1.WotsWatermarkStore(config.storage, this.logger);
22
+ this.leaseStore = new core_1.LeaseStore(config.storage, this.logger);
23
+ this.journal = new journal_js_1.LeaseJournal(config.storage, this.logger);
21
24
  }
22
25
  async initialize() {
23
26
  if (this._initialized)
@@ -31,7 +34,7 @@ export class AxiaLeaseProvider {
31
34
  if (!this._initialized)
32
35
  await this.initialize();
33
36
  const txId = params.payloadHash ?? `tx-${Date.now()}`;
34
- const resp = await prepareLease(this.apiUrl, this.apiKey, {
37
+ const resp = await (0, core_2.prepareLease)(this.apiUrl, this.apiKey, {
35
38
  txId,
36
39
  rootPublicKey: this.rootPublicKey,
37
40
  to: params.treeId,
@@ -44,6 +47,7 @@ export class AxiaLeaseProvider {
44
47
  const lease = {
45
48
  leaseId: reservationId,
46
49
  leaseToken: resp.leaseToken,
50
+ treeId: params.treeId,
47
51
  indices,
48
52
  expiresAt,
49
53
  status: 'active',
@@ -54,7 +58,7 @@ export class AxiaLeaseProvider {
54
58
  await this.journal.append({
55
59
  treeId: params.treeId,
56
60
  branchId: params.branchId ?? 'default',
57
- wotsIndex: flatIndex(indices),
61
+ wotsIndex: (0, watermark_js_1.flatIndex)(indices),
58
62
  indices,
59
63
  status: 'reserved',
60
64
  payloadHash: params.payloadHash,
@@ -68,15 +72,15 @@ export class AxiaLeaseProvider {
68
72
  await this.initialize();
69
73
  const lease = this.leaseStore.get(reservationId);
70
74
  if (!lease)
71
- throw new LeaseNotFoundError(reservationId);
72
- await finalizeLease(this.apiUrl, this.apiKey, lease.leaseToken, txId);
75
+ throw new errors_js_1.LeaseNotFoundError(reservationId);
76
+ await (0, core_2.finalizeLease)(this.apiUrl, this.apiKey, lease.leaseToken, txId);
73
77
  const indices = lease.indices;
74
78
  await this.watermark.markUnavailable(lease.indices.addressIndex.toString(), indices, 'committed');
75
79
  await this.leaseStore.updateStatus(reservationId, 'finalized');
76
80
  await this.journal.append({
77
81
  treeId: reservationId,
78
82
  branchId: 'default',
79
- wotsIndex: flatIndex(indices),
83
+ wotsIndex: (0, watermark_js_1.flatIndex)(indices),
80
84
  indices,
81
85
  status: 'committed',
82
86
  txId,
@@ -89,7 +93,7 @@ export class AxiaLeaseProvider {
89
93
  await this.initialize();
90
94
  const lease = this.leaseStore.get(reservationId);
91
95
  if (!lease)
92
- throw new LeaseNotFoundError(reservationId);
96
+ throw new errors_js_1.LeaseNotFoundError(reservationId);
93
97
  const indices = lease.indices;
94
98
  await this.watermark.markUnavailable(lease.indices.addressIndex.toString(), indices, 'burned');
95
99
  await this.leaseStore.updateStatus(reservationId, 'cancelled');
@@ -97,7 +101,7 @@ export class AxiaLeaseProvider {
97
101
  await this.journal.append({
98
102
  treeId: reservationId,
99
103
  branchId: 'default',
100
- wotsIndex: flatIndex(indices),
104
+ wotsIndex: (0, watermark_js_1.flatIndex)(indices),
101
105
  indices,
102
106
  status: 'burned',
103
107
  timestamp: Date.now(),
@@ -121,3 +125,4 @@ export class AxiaLeaseProvider {
121
125
  return false;
122
126
  }
123
127
  }
128
+ exports.AxiaLeaseProvider = AxiaLeaseProvider;
package/dist/device.js CHANGED
@@ -1,3 +1,4 @@
1
+ "use strict";
1
2
  /**
2
3
  * Device keyspace partitioning — Layer 2.
3
4
  *
@@ -10,9 +11,12 @@
10
11
  * device 2 → addressIndex 16–23
11
12
  * ...
12
13
  */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.allocateDeviceRange = allocateDeviceRange;
16
+ exports.deviceSlotForAddressIndex = deviceSlotForAddressIndex;
13
17
  const ADDRESSES_PER_DEVICE = 8;
14
18
  const MAX_DEVICE_SLOTS = 8;
15
- export function allocateDeviceRange(params) {
19
+ function allocateDeviceRange(params) {
16
20
  if (params.deviceSlot < 0 || params.deviceSlot >= MAX_DEVICE_SLOTS) {
17
21
  throw new RangeError(`Device slot must be 0–${MAX_DEVICE_SLOTS - 1}, got ${params.deviceSlot}`);
18
22
  }
@@ -25,6 +29,6 @@ export function allocateDeviceRange(params) {
25
29
  addressCount: ADDRESSES_PER_DEVICE,
26
30
  };
27
31
  }
28
- export function deviceSlotForAddressIndex(addressIndex) {
32
+ function deviceSlotForAddressIndex(addressIndex) {
29
33
  return Math.floor(addressIndex / ADDRESSES_PER_DEVICE);
30
34
  }
package/dist/errors.js CHANGED
@@ -1,43 +1,52 @@
1
- export class WatermarkMonotonicityError extends Error {
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DeviceRangeViolationError = exports.OnchainWatermarkNotImplementedError = exports.P2PQuorumNotImplementedError = exports.PersonalLeaseNodeNotConfiguredError = exports.LeaseNotFoundError = exports.WatermarkExhaustedError = exports.WatermarkMonotonicityError = void 0;
4
+ class WatermarkMonotonicityError extends Error {
2
5
  constructor(message) {
3
6
  super(message);
4
7
  this.name = 'WatermarkMonotonicityError';
5
8
  }
6
9
  }
7
- export class WatermarkExhaustedError extends Error {
10
+ exports.WatermarkMonotonicityError = WatermarkMonotonicityError;
11
+ class WatermarkExhaustedError extends Error {
8
12
  constructor(treeId) {
9
13
  super(`WOTS keyspace exhausted for tree: ${treeId}`);
10
14
  this.treeId = treeId;
11
15
  this.name = 'WatermarkExhaustedError';
12
16
  }
13
17
  }
14
- export class LeaseNotFoundError extends Error {
18
+ exports.WatermarkExhaustedError = WatermarkExhaustedError;
19
+ class LeaseNotFoundError extends Error {
15
20
  constructor(reservationId) {
16
21
  super(`Lease reservation not found: ${reservationId}`);
17
22
  this.reservationId = reservationId;
18
23
  this.name = 'LeaseNotFoundError';
19
24
  }
20
25
  }
21
- export class PersonalLeaseNodeNotConfiguredError extends Error {
26
+ exports.LeaseNotFoundError = LeaseNotFoundError;
27
+ class PersonalLeaseNodeNotConfiguredError extends Error {
22
28
  constructor() {
23
29
  super('PersonalLeaseNodeProvider requires a running lookup node. ' +
24
30
  'Deploy @totemsdk/lookup-node and configure { nodeUrl, nodePubkey }.');
25
31
  this.name = 'PersonalLeaseNodeNotConfiguredError';
26
32
  }
27
33
  }
28
- export class P2PQuorumNotImplementedError extends Error {
34
+ exports.PersonalLeaseNodeNotConfiguredError = PersonalLeaseNodeNotConfiguredError;
35
+ class P2PQuorumNotImplementedError extends Error {
29
36
  constructor() {
30
37
  super('P2PQuorumLeaseProvider is not yet implemented.');
31
38
  this.name = 'P2PQuorumNotImplementedError';
32
39
  }
33
40
  }
34
- export class OnchainWatermarkNotImplementedError extends Error {
41
+ exports.P2PQuorumNotImplementedError = P2PQuorumNotImplementedError;
42
+ class OnchainWatermarkNotImplementedError extends Error {
35
43
  constructor() {
36
44
  super('OnchainWatermarkProvider is not yet implemented.');
37
45
  this.name = 'OnchainWatermarkNotImplementedError';
38
46
  }
39
47
  }
40
- export class DeviceRangeViolationError extends Error {
48
+ exports.OnchainWatermarkNotImplementedError = OnchainWatermarkNotImplementedError;
49
+ class DeviceRangeViolationError extends Error {
41
50
  constructor(addressIndex, allowedStart, allowedEnd) {
42
51
  super(`Address index ${addressIndex} is outside device range [${allowedStart}, ${allowedEnd}]`);
43
52
  this.addressIndex = addressIndex;
@@ -46,3 +55,4 @@ export class DeviceRangeViolationError extends Error {
46
55
  this.name = 'DeviceRangeViolationError';
47
56
  }
48
57
  }
58
+ exports.DeviceRangeViolationError = DeviceRangeViolationError;
package/dist/hybrid.js CHANGED
@@ -1,10 +1,13 @@
1
+ "use strict";
1
2
  /**
2
3
  * HybridLeaseProvider — recommended production default.
3
4
  *
4
5
  * Always uses local first, then gates on node cert and/or quorum attestation
5
6
  * for transactions above a configurable value threshold.
6
7
  */
7
- export class HybridLeaseProvider {
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.HybridLeaseProvider = void 0;
10
+ class HybridLeaseProvider {
8
11
  constructor(config) {
9
12
  this.local = config.local;
10
13
  this.node = config.node;
@@ -62,3 +65,4 @@ export class HybridLeaseProvider {
62
65
  return false;
63
66
  }
64
67
  }
68
+ exports.HybridLeaseProvider = HybridLeaseProvider;
package/dist/index.js CHANGED
@@ -1,8 +1,30 @@
1
- export { WotsWatermarkStore, flatIndex, fromFlatIndex, } from './watermark.js';
2
- export { LeaseJournal } from './journal.js';
3
- export { LocalLeaseProvider } from './local.js';
4
- export { AxiaLeaseProvider } from './axia.js';
5
- export { HybridLeaseProvider } from './hybrid.js';
6
- export { PersonalLeaseNodeProvider, P2PQuorumLeaseProvider, OnchainWatermarkProvider, } from './stubs.js';
7
- export { allocateDeviceRange, deviceSlotForAddressIndex } from './device.js';
8
- export { WatermarkMonotonicityError, WatermarkExhaustedError, LeaseNotFoundError, PersonalLeaseNodeNotConfiguredError, P2PQuorumNotImplementedError, OnchainWatermarkNotImplementedError, DeviceRangeViolationError, } from './errors.js';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DeviceRangeViolationError = exports.OnchainWatermarkNotImplementedError = exports.P2PQuorumNotImplementedError = exports.PersonalLeaseNodeNotConfiguredError = exports.LeaseNotFoundError = exports.WatermarkExhaustedError = exports.WatermarkMonotonicityError = exports.deviceSlotForAddressIndex = exports.allocateDeviceRange = exports.OnchainWatermarkProvider = exports.P2PQuorumLeaseProvider = exports.PersonalLeaseNodeProvider = exports.HybridLeaseProvider = exports.AxiaLeaseProvider = exports.LocalLeaseProvider = exports.LeaseJournal = exports.fromFlatIndex = exports.flatIndex = exports.WotsWatermarkStore = void 0;
4
+ var watermark_js_1 = require("./watermark.js");
5
+ Object.defineProperty(exports, "WotsWatermarkStore", { enumerable: true, get: function () { return watermark_js_1.WotsWatermarkStore; } });
6
+ Object.defineProperty(exports, "flatIndex", { enumerable: true, get: function () { return watermark_js_1.flatIndex; } });
7
+ Object.defineProperty(exports, "fromFlatIndex", { enumerable: true, get: function () { return watermark_js_1.fromFlatIndex; } });
8
+ var journal_js_1 = require("./journal.js");
9
+ Object.defineProperty(exports, "LeaseJournal", { enumerable: true, get: function () { return journal_js_1.LeaseJournal; } });
10
+ var local_js_1 = require("./local.js");
11
+ Object.defineProperty(exports, "LocalLeaseProvider", { enumerable: true, get: function () { return local_js_1.LocalLeaseProvider; } });
12
+ var axia_js_1 = require("./axia.js");
13
+ Object.defineProperty(exports, "AxiaLeaseProvider", { enumerable: true, get: function () { return axia_js_1.AxiaLeaseProvider; } });
14
+ var hybrid_js_1 = require("./hybrid.js");
15
+ Object.defineProperty(exports, "HybridLeaseProvider", { enumerable: true, get: function () { return hybrid_js_1.HybridLeaseProvider; } });
16
+ var stubs_js_1 = require("./stubs.js");
17
+ Object.defineProperty(exports, "PersonalLeaseNodeProvider", { enumerable: true, get: function () { return stubs_js_1.PersonalLeaseNodeProvider; } });
18
+ Object.defineProperty(exports, "P2PQuorumLeaseProvider", { enumerable: true, get: function () { return stubs_js_1.P2PQuorumLeaseProvider; } });
19
+ Object.defineProperty(exports, "OnchainWatermarkProvider", { enumerable: true, get: function () { return stubs_js_1.OnchainWatermarkProvider; } });
20
+ var device_js_1 = require("./device.js");
21
+ Object.defineProperty(exports, "allocateDeviceRange", { enumerable: true, get: function () { return device_js_1.allocateDeviceRange; } });
22
+ Object.defineProperty(exports, "deviceSlotForAddressIndex", { enumerable: true, get: function () { return device_js_1.deviceSlotForAddressIndex; } });
23
+ var errors_js_1 = require("./errors.js");
24
+ Object.defineProperty(exports, "WatermarkMonotonicityError", { enumerable: true, get: function () { return errors_js_1.WatermarkMonotonicityError; } });
25
+ Object.defineProperty(exports, "WatermarkExhaustedError", { enumerable: true, get: function () { return errors_js_1.WatermarkExhaustedError; } });
26
+ Object.defineProperty(exports, "LeaseNotFoundError", { enumerable: true, get: function () { return errors_js_1.LeaseNotFoundError; } });
27
+ Object.defineProperty(exports, "PersonalLeaseNodeNotConfiguredError", { enumerable: true, get: function () { return errors_js_1.PersonalLeaseNodeNotConfiguredError; } });
28
+ Object.defineProperty(exports, "P2PQuorumNotImplementedError", { enumerable: true, get: function () { return errors_js_1.P2PQuorumNotImplementedError; } });
29
+ Object.defineProperty(exports, "OnchainWatermarkNotImplementedError", { enumerable: true, get: function () { return errors_js_1.OnchainWatermarkNotImplementedError; } });
30
+ Object.defineProperty(exports, "DeviceRangeViolationError", { enumerable: true, get: function () { return errors_js_1.DeviceRangeViolationError; } });
package/dist/journal.d.ts CHANGED
@@ -12,6 +12,7 @@ export declare class LeaseJournal {
12
12
  constructor(storage: StorageAdapter, logger?: LoggerAdapter);
13
13
  initialize(): Promise<void>;
14
14
  append(entry: JournalEntry): Promise<void>;
15
+ private _verifyChain;
15
16
  getAll(): JournalEntry[];
16
17
  getByTree(treeId: string): JournalEntry[];
17
18
  getByReservation(reservationId: string): JournalEntry | undefined;
package/dist/journal.js CHANGED
@@ -1,11 +1,30 @@
1
+ "use strict";
1
2
  /**
2
3
  * LeaseJournal — append-only audit log for WOTS key-use events.
3
4
  * Preserves the full history: reserved → committed | burned | reserved-expired.
4
5
  */
5
- import { NoopLogger } from '@totemsdk/core';
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.LeaseJournal = void 0;
8
+ const crypto_1 = require("crypto");
9
+ const core_1 = require("@totemsdk/core");
6
10
  const STORAGE_KEY = 'totem_wots_journal';
7
- export class LeaseJournal {
8
- constructor(storage, logger = new NoopLogger()) {
11
+ function hashEntry(entry) {
12
+ const encoder = new TextEncoder();
13
+ const data = {
14
+ t: entry.treeId,
15
+ b: entry.branchId,
16
+ i: entry.wotsIndex,
17
+ s: entry.status,
18
+ r: entry.reservationId,
19
+ p: entry.previousHash,
20
+ ts: entry.timestamp,
21
+ d: entry.deviceId,
22
+ };
23
+ const bytes = encoder.encode(JSON.stringify(data));
24
+ return (0, crypto_1.createHash)('sha256').update(bytes).digest('hex');
25
+ }
26
+ class LeaseJournal {
27
+ constructor(storage, logger = new core_1.NoopLogger()) {
9
28
  this.storage = storage;
10
29
  this.logger = logger;
11
30
  this.entries = [];
@@ -16,12 +35,40 @@ export class LeaseJournal {
16
35
  return;
17
36
  const stored = await this.storage.get(STORAGE_KEY);
18
37
  this.entries = stored ?? [];
38
+ if (this.entries.length > 0) {
39
+ const ok = this._verifyChain();
40
+ if (!ok) {
41
+ this.logger.error('[LeaseJournal] hash chain integrity check FAILED — journal may be tampered');
42
+ throw new Error('Journal hash chain integrity check failed');
43
+ }
44
+ }
19
45
  this._initialized = true;
20
46
  }
21
47
  async append(entry) {
48
+ const prev = this.entries[this.entries.length - 1];
49
+ entry.previousHash = prev?.hash;
50
+ entry.hash = hashEntry(entry);
22
51
  this.entries.push(entry);
23
52
  await this.storage.set(STORAGE_KEY, this.entries);
24
- this.logger.debug(`[LeaseJournal] ${entry.status} treeId=${entry.treeId} idx=${entry.wotsIndex} txId=${entry.txId ?? '-'}`);
53
+ this.logger.debug(`[LeaseJournal] ${entry.status} treeId=${entry.treeId} idx=${entry.wotsIndex} txId=${entry.txId ?? '-'} hash=${entry.hash.slice(0, 8)}`);
54
+ }
55
+ _verifyChain() {
56
+ for (let i = 0; i < this.entries.length; i++) {
57
+ const e = this.entries[i];
58
+ const expectedHash = hashEntry(e);
59
+ if (e.hash !== expectedHash) {
60
+ this.logger.error(`[LeaseJournal] hash mismatch at entry ${i}: expected ${expectedHash}, stored ${e.hash}`);
61
+ return false;
62
+ }
63
+ if (i > 0) {
64
+ const prevHash = this.entries[i - 1].hash;
65
+ if (e.previousHash !== prevHash) {
66
+ this.logger.error(`[LeaseJournal] previousHash mismatch at entry ${i}: expected ${prevHash}, stored ${e.previousHash}`);
67
+ return false;
68
+ }
69
+ }
70
+ }
71
+ return true;
25
72
  }
26
73
  getAll() {
27
74
  return [...this.entries];
@@ -37,3 +84,4 @@ export class LeaseJournal {
37
84
  await this.storage.remove(STORAGE_KEY);
38
85
  }
39
86
  }
87
+ exports.LeaseJournal = LeaseJournal;
package/dist/local.d.ts CHANGED
@@ -13,10 +13,12 @@ export declare class LocalLeaseProvider implements WotsLeaseProvider {
13
13
  private readonly journal;
14
14
  private _initialized;
15
15
  private readonly deviceId;
16
- /** In-memory map: reservationId → treeId (lost on restart; watermark survives). */
17
- private readonly _treeIdByReservation;
18
16
  constructor(storage: StorageAdapter, logger?: LoggerAdapter, deviceId?: string);
19
17
  initialize(): Promise<void>;
18
+ /** Burn all active (non-expired) leases that have no matching treeId.
19
+ * On restart, leases with missing treeId (from before the treeId field was added)
20
+ * must be burned to prevent index reuse. */
21
+ private burnUnresolvedReservations;
20
22
  private recoverExpiredReservations;
21
23
  reserveKeyUse(params: ReserveParams): Promise<LeaseReservation>;
22
24
  commitKeyUse(reservationId: string, txId: string): Promise<void>;
package/dist/local.js CHANGED
@@ -1,29 +1,30 @@
1
+ "use strict";
1
2
  /**
2
3
  * LocalLeaseProvider — Layer 1: local durable ledger.
3
4
  *
4
5
  * Single-device, no network coordination.
5
6
  * All WOTS safety guaranteed by the local WotsWatermarkStore + LeaseJournal.
6
7
  */
7
- import { NoopLogger } from '@totemsdk/core';
8
- import { LeaseStore } from '@totemsdk/core';
9
- import { WotsWatermarkStore, flatIndex } from './watermark.js';
10
- import { LeaseJournal } from './journal.js';
11
- import { LeaseNotFoundError, DeviceRangeViolationError } from './errors.js';
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.LocalLeaseProvider = void 0;
10
+ const core_1 = require("@totemsdk/core");
11
+ const core_2 = require("@totemsdk/core");
12
+ const watermark_js_1 = require("./watermark.js");
13
+ const journal_js_1 = require("./journal.js");
14
+ const errors_js_1 = require("./errors.js");
12
15
  function randomId() {
13
16
  if (typeof crypto !== 'undefined' && crypto.randomUUID) {
14
17
  return crypto.randomUUID();
15
18
  }
16
19
  return Math.random().toString(36).slice(2) + Date.now().toString(36);
17
20
  }
18
- export class LocalLeaseProvider {
19
- constructor(storage, logger = new NoopLogger(), deviceId = 'local') {
21
+ class LocalLeaseProvider {
22
+ constructor(storage, logger = new core_1.NoopLogger(), deviceId = 'local') {
20
23
  this.logger = logger;
21
24
  this._initialized = false;
22
- /** In-memory map: reservationId → treeId (lost on restart; watermark survives). */
23
- this._treeIdByReservation = new Map();
24
- this.watermark = new WotsWatermarkStore(storage, logger);
25
- this.leaseStore = new LeaseStore(storage, logger);
26
- this.journal = new LeaseJournal(storage, logger);
25
+ this.watermark = new watermark_js_1.WotsWatermarkStore(storage, logger);
26
+ this.leaseStore = new core_2.LeaseStore(storage, logger);
27
+ this.journal = new journal_js_1.LeaseJournal(storage, logger);
27
28
  this.deviceId = deviceId;
28
29
  }
29
30
  async initialize() {
@@ -33,21 +34,46 @@ export class LocalLeaseProvider {
33
34
  await this.leaseStore.initialize();
34
35
  await this.journal.initialize();
35
36
  await this.recoverExpiredReservations();
37
+ await this.burnUnresolvedReservations();
36
38
  this._initialized = true;
37
39
  }
40
+ /** Burn all active (non-expired) leases that have no matching treeId.
41
+ * On restart, leases with missing treeId (from before the treeId field was added)
42
+ * must be burned to prevent index reuse. */
43
+ async burnUnresolvedReservations() {
44
+ const now = Date.now();
45
+ for (const lease of this.leaseStore.getAll()) {
46
+ if (lease.status === 'active' && lease.expiresAt >= now && !lease.treeId) {
47
+ this.logger.warn(`[LocalLeaseProvider] Burning unresolved lease ${lease.leaseId} (no treeId)`);
48
+ await this.watermark.markUnavailable('default', lease.indices, 'burned');
49
+ await this.leaseStore.updateStatus(lease.leaseId, 'cancelled');
50
+ await this.journal.append({
51
+ treeId: 'default',
52
+ branchId: 'default',
53
+ wotsIndex: (0, watermark_js_1.flatIndex)(lease.indices),
54
+ indices: lease.indices,
55
+ status: 'burned',
56
+ reservationId: lease.leaseId,
57
+ timestamp: now,
58
+ deviceId: this.deviceId,
59
+ });
60
+ }
61
+ }
62
+ }
38
63
  async recoverExpiredReservations() {
39
64
  const now = Date.now();
40
65
  for (const lease of this.leaseStore.getAll()) {
41
66
  if (lease.status === 'active' && lease.expiresAt < now) {
42
- const treeId = this._treeIdByReservation.get(lease.leaseId) ?? 'default';
67
+ const treeId = lease.treeId ?? 'default';
43
68
  await this.watermark.markUnavailable(treeId, lease.indices, 'reserved-expired');
44
69
  await this.leaseStore.updateStatus(lease.leaseId, 'expired');
45
70
  await this.journal.append({
46
71
  treeId,
47
72
  branchId: 'default',
48
- wotsIndex: flatIndex(lease.indices),
73
+ wotsIndex: (0, watermark_js_1.flatIndex)(lease.indices),
49
74
  indices: lease.indices,
50
75
  status: 'reserved-expired',
76
+ reservationId: lease.leaseId,
51
77
  timestamp: now,
52
78
  deviceId: this.deviceId,
53
79
  });
@@ -59,11 +85,13 @@ export class LocalLeaseProvider {
59
85
  await this.initialize();
60
86
  const treeId = params.treeId;
61
87
  const ttlMs = params.ttlMs ?? 120000;
88
+ // Atomically get the next available index AND mark it reserved in the watermark
62
89
  const indices = this.watermark.getNextIndices(treeId);
90
+ await this.watermark.markUnavailable(treeId, indices, 'reserved');
63
91
  if (params.deviceId) {
64
92
  const range = this.getDeviceRange(params.deviceId);
65
93
  if (range && (indices.addressIndex < range.start || indices.addressIndex > range.end)) {
66
- throw new DeviceRangeViolationError(indices.addressIndex, range.start, range.end);
94
+ throw new errors_js_1.DeviceRangeViolationError(indices.addressIndex, range.start, range.end);
67
95
  }
68
96
  }
69
97
  const reservationId = randomId();
@@ -71,6 +99,7 @@ export class LocalLeaseProvider {
71
99
  const lease = {
72
100
  leaseId: reservationId,
73
101
  leaseToken: reservationId,
102
+ treeId,
74
103
  indices,
75
104
  expiresAt,
76
105
  status: 'active',
@@ -78,14 +107,13 @@ export class LocalLeaseProvider {
78
107
  leaseTTL: ttlMs,
79
108
  };
80
109
  await this.leaseStore.save(lease);
81
- // Track treeId in memory so commit/burn can reference the right watermark tree
82
- this._treeIdByReservation.set(reservationId, treeId);
83
110
  await this.journal.append({
84
111
  treeId,
85
112
  branchId: params.branchId ?? 'default',
86
- wotsIndex: flatIndex(indices),
113
+ wotsIndex: (0, watermark_js_1.flatIndex)(indices),
87
114
  indices,
88
115
  status: 'reserved',
116
+ reservationId,
89
117
  payloadHash: params.payloadHash,
90
118
  timestamp: Date.now(),
91
119
  deviceId: params.deviceId ?? this.deviceId,
@@ -97,18 +125,20 @@ export class LocalLeaseProvider {
97
125
  await this.initialize();
98
126
  const lease = this.leaseStore.get(reservationId);
99
127
  if (!lease)
100
- throw new LeaseNotFoundError(reservationId);
101
- const treeId = this._treeIdByReservation.get(reservationId) ?? 'default';
128
+ throw new errors_js_1.LeaseNotFoundError(reservationId);
129
+ if (lease.status === 'finalized')
130
+ return;
131
+ const treeId = lease.treeId ?? 'default';
102
132
  const indices = lease.indices;
103
133
  await this.watermark.markUnavailable(treeId, indices, 'committed');
104
134
  await this.leaseStore.updateStatus(reservationId, 'finalized');
105
- this._treeIdByReservation.delete(reservationId);
106
135
  await this.journal.append({
107
136
  treeId,
108
137
  branchId: 'default',
109
- wotsIndex: flatIndex(indices),
138
+ wotsIndex: (0, watermark_js_1.flatIndex)(indices),
110
139
  indices,
111
140
  status: 'committed',
141
+ reservationId,
112
142
  txId,
113
143
  timestamp: Date.now(),
114
144
  deviceId: this.deviceId,
@@ -119,19 +149,19 @@ export class LocalLeaseProvider {
119
149
  await this.initialize();
120
150
  const lease = this.leaseStore.get(reservationId);
121
151
  if (!lease)
122
- throw new LeaseNotFoundError(reservationId);
123
- const treeId = this._treeIdByReservation.get(reservationId) ?? 'default';
152
+ throw new errors_js_1.LeaseNotFoundError(reservationId);
153
+ const treeId = lease.treeId ?? 'default';
124
154
  const indices = lease.indices;
125
155
  await this.watermark.markUnavailable(treeId, indices, 'burned');
126
156
  await this.leaseStore.updateStatus(reservationId, 'cancelled');
127
- this._treeIdByReservation.delete(reservationId);
128
157
  this.logger.warn(`[LocalLeaseProvider] Burning reservation ${reservationId}: ${reason}`);
129
158
  await this.journal.append({
130
159
  treeId,
131
160
  branchId: 'default',
132
- wotsIndex: flatIndex(indices),
161
+ wotsIndex: (0, watermark_js_1.flatIndex)(indices),
133
162
  indices,
134
163
  status: 'burned',
164
+ reservationId,
135
165
  timestamp: Date.now(),
136
166
  deviceId: this.deviceId,
137
167
  });
@@ -161,3 +191,4 @@ export class LocalLeaseProvider {
161
191
  return { start: slot * 8, end: slot * 8 + 7 };
162
192
  }
163
193
  }
194
+ exports.LocalLeaseProvider = LocalLeaseProvider;
package/dist/stubs.d.ts CHANGED
@@ -1,23 +1,46 @@
1
1
  /**
2
- * Stub implementations for Layers 3–5.
3
- * These throw descriptive errors until the full implementations land.
2
+ * Implementations for Layers 3–5 of the WotsLeaseProvider hierarchy.
3
+ *
4
+ * Layer 3 (PersonalLeaseNodeProvider) — HTTP client for a personal @totemsdk/lookup-node
5
+ * that has lease coordination enabled ({ lease: { enabled: true } }).
6
+ * The node exposes REST endpoints under /v1/lease/*.
7
+ *
8
+ * Layers 4–5 (P2PQuorumLeaseProvider, OnchainWatermarkProvider) — require
9
+ * distributed infrastructure not yet available; they throw descriptive errors.
4
10
  */
5
11
  import type { WotsLeaseProvider, ReserveParams, LeaseReservation, LeaseCertificate, LocalWatermark, SyncResult, PersonalLeaseNodeConfig } from './types.js';
6
12
  /**
7
- * Layer 3 — personal p2p lease node.
13
+ * Layer 3 — personal lookup-node lease coordinator.
14
+ *
15
+ * Calls the HTTP REST API exposed by a running @totemsdk/lookup-node that has
16
+ * lease coordination enabled. All write operations are forwarded to the node's
17
+ * LeaseCoordinator so the node acts as the source-of-truth watermark journal
18
+ * for high-value transactions.
8
19
  *
9
- * Verifies ed25519 certs issued by a configured node public key.
10
- * Reserve/commit throws until the node is reachable — callers should
11
- * wrap with HybridLeaseProvider using a LocalLeaseProvider as the local layer.
20
+ * Wrap with HybridLeaseProvider so local reservations always succeed even when
21
+ * the personal node is temporarily unreachable:
22
+ *
23
+ * ```ts
24
+ * const provider = new HybridLeaseProvider({
25
+ * local: new LocalLeaseProvider(storage),
26
+ * node: new PersonalLeaseNodeProvider({ nodeUrl, nodePubkey }),
27
+ * threshold: 10, // escalate to node for txns >= 10 MIN
28
+ * });
29
+ * ```
12
30
  */
13
31
  export declare class PersonalLeaseNodeProvider implements WotsLeaseProvider {
14
- private readonly config;
32
+ private readonly baseUrl;
33
+ private readonly nodePubkey;
34
+ private readonly authToken?;
15
35
  constructor(config: PersonalLeaseNodeConfig);
16
- reserveKeyUse(_params: ReserveParams): Promise<LeaseReservation>;
17
- commitKeyUse(_reservationId: string, _txId: string): Promise<void>;
18
- burnReservation(_reservationId: string, _reason: string): Promise<void>;
19
- getLocalWatermark(_treeId: string): Promise<LocalWatermark>;
20
- publishWatermark(_treeId: string): Promise<void>;
36
+ private headers;
37
+ private post;
38
+ private get;
39
+ reserveKeyUse(params: ReserveParams): Promise<LeaseReservation>;
40
+ commitKeyUse(reservationId: string, txId: string): Promise<void>;
41
+ burnReservation(reservationId: string, reason: string): Promise<void>;
42
+ getLocalWatermark(treeId: string): Promise<LocalWatermark>;
43
+ publishWatermark(treeId: string): Promise<void>;
21
44
  syncLeaseJournal(): Promise<SyncResult>;
22
45
  verifyLeaseCertificate(cert?: LeaseCertificate): Promise<boolean>;
23
46
  }