@dignetwork/dig-sdk 0.0.1-alpha.2

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 (104) hide show
  1. package/LICENSE +7 -0
  2. package/dist/DataIntegrityTree/DataIntegrityTree.d.ts +160 -0
  3. package/dist/DataIntegrityTree/DataIntegrityTree.d.ts.map +1 -0
  4. package/dist/DataIntegrityTree/DataIntegrityTree.js +648 -0
  5. package/dist/DataIntegrityTree/DataLayerError.d.ts +6 -0
  6. package/dist/DataIntegrityTree/DataLayerError.d.ts.map +1 -0
  7. package/dist/DataIntegrityTree/DataLayerError.js +17 -0
  8. package/dist/DataIntegrityTree/index.d.ts +2 -0
  9. package/dist/DataIntegrityTree/index.d.ts.map +1 -0
  10. package/dist/DataIntegrityTree/index.js +17 -0
  11. package/dist/DigNetwork/ContentServer.d.ts +28 -0
  12. package/dist/DigNetwork/ContentServer.d.ts.map +1 -0
  13. package/dist/DigNetwork/ContentServer.js +243 -0
  14. package/dist/DigNetwork/DigChallenge.d.ts +82 -0
  15. package/dist/DigNetwork/DigChallenge.d.ts.map +1 -0
  16. package/dist/DigNetwork/DigChallenge.js +144 -0
  17. package/dist/DigNetwork/DigNetwork.d.ts +19 -0
  18. package/dist/DigNetwork/DigNetwork.d.ts.map +1 -0
  19. package/dist/DigNetwork/DigNetwork.js +222 -0
  20. package/dist/DigNetwork/DigPeer.d.ts +19 -0
  21. package/dist/DigNetwork/DigPeer.d.ts.map +1 -0
  22. package/dist/DigNetwork/DigPeer.js +164 -0
  23. package/dist/DigNetwork/IncentiveServer.d.ts +13 -0
  24. package/dist/DigNetwork/IncentiveServer.d.ts.map +1 -0
  25. package/dist/DigNetwork/IncentiveServer.js +76 -0
  26. package/dist/DigNetwork/PropagationServer.d.ts +41 -0
  27. package/dist/DigNetwork/PropagationServer.d.ts.map +1 -0
  28. package/dist/DigNetwork/PropagationServer.js +415 -0
  29. package/dist/DigNetwork/index.d.ts +4 -0
  30. package/dist/DigNetwork/index.d.ts.map +1 -0
  31. package/dist/DigNetwork/index.js +19 -0
  32. package/dist/blockchain/DataStore.d.ts +54 -0
  33. package/dist/blockchain/DataStore.d.ts.map +1 -0
  34. package/dist/blockchain/DataStore.js +410 -0
  35. package/dist/blockchain/DataStoreSerializer.d.ts +52 -0
  36. package/dist/blockchain/DataStoreSerializer.d.ts.map +1 -0
  37. package/dist/blockchain/DataStoreSerializer.js +109 -0
  38. package/dist/blockchain/FullNodePeer.d.ts +17 -0
  39. package/dist/blockchain/FullNodePeer.d.ts.map +1 -0
  40. package/dist/blockchain/FullNodePeer.js +215 -0
  41. package/dist/blockchain/ServerCoin.d.ts +21 -0
  42. package/dist/blockchain/ServerCoin.d.ts.map +1 -0
  43. package/dist/blockchain/ServerCoin.js +261 -0
  44. package/dist/blockchain/Wallet.d.ts +28 -0
  45. package/dist/blockchain/Wallet.d.ts.map +1 -0
  46. package/dist/blockchain/Wallet.js +220 -0
  47. package/dist/blockchain/coins.d.ts +6 -0
  48. package/dist/blockchain/coins.d.ts.map +1 -0
  49. package/dist/blockchain/coins.js +101 -0
  50. package/dist/blockchain/index.d.ts +8 -0
  51. package/dist/blockchain/index.d.ts.map +1 -0
  52. package/dist/blockchain/index.js +36 -0
  53. package/dist/index.d.ts +5 -0
  54. package/dist/index.d.ts.map +1 -0
  55. package/dist/index.js +20 -0
  56. package/dist/prompts.d.ts +21 -0
  57. package/dist/prompts.d.ts.map +1 -0
  58. package/dist/prompts.js +149 -0
  59. package/dist/types.d.ts +62 -0
  60. package/dist/types.d.ts.map +1 -0
  61. package/dist/types.js +2 -0
  62. package/dist/utils/FileCache.d.ts +11 -0
  63. package/dist/utils/FileCache.d.ts.map +1 -0
  64. package/dist/utils/FileCache.js +58 -0
  65. package/dist/utils/NconfManager.d.ts +11 -0
  66. package/dist/utils/NconfManager.d.ts.map +1 -0
  67. package/dist/utils/NconfManager.js +55 -0
  68. package/dist/utils/config.d.ts +67 -0
  69. package/dist/utils/config.d.ts.map +1 -0
  70. package/dist/utils/config.js +223 -0
  71. package/dist/utils/connectionUtils.d.ts +10 -0
  72. package/dist/utils/connectionUtils.d.ts.map +1 -0
  73. package/dist/utils/connectionUtils.js +18 -0
  74. package/dist/utils/credentialsUtils.d.ts +8 -0
  75. package/dist/utils/credentialsUtils.d.ts.map +1 -0
  76. package/dist/utils/credentialsUtils.js +122 -0
  77. package/dist/utils/deltaUtils.d.ts +2 -0
  78. package/dist/utils/deltaUtils.d.ts.map +1 -0
  79. package/dist/utils/deltaUtils.js +83 -0
  80. package/dist/utils/directoryUtils.d.ts +15 -0
  81. package/dist/utils/directoryUtils.d.ts.map +1 -0
  82. package/dist/utils/directoryUtils.js +91 -0
  83. package/dist/utils/encryption.d.ts +8 -0
  84. package/dist/utils/encryption.d.ts.map +1 -0
  85. package/dist/utils/encryption.js +55 -0
  86. package/dist/utils/hashUtils.d.ts +8 -0
  87. package/dist/utils/hashUtils.d.ts.map +1 -0
  88. package/dist/utils/hashUtils.js +44 -0
  89. package/dist/utils/index.d.ts +14 -0
  90. package/dist/utils/index.d.ts.map +1 -0
  91. package/dist/utils/index.js +29 -0
  92. package/dist/utils/network.d.ts +2 -0
  93. package/dist/utils/network.d.ts.map +1 -0
  94. package/dist/utils/network.js +38 -0
  95. package/dist/utils/spinnerUtils.d.ts +2 -0
  96. package/dist/utils/spinnerUtils.d.ts.map +1 -0
  97. package/dist/utils/spinnerUtils.js +47 -0
  98. package/dist/utils/ssl.d.ts +5 -0
  99. package/dist/utils/ssl.d.ts.map +1 -0
  100. package/dist/utils/ssl.js +50 -0
  101. package/dist/utils/validationUtils.d.ts +9 -0
  102. package/dist/utils/validationUtils.d.ts.map +1 -0
  103. package/dist/utils/validationUtils.js +55 -0
  104. package/package.json +64 -0
@@ -0,0 +1,410 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DataStore = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const datalayer_driver_1 = require("datalayer-driver");
10
+ const util_1 = require("util");
11
+ const FullNodePeer_1 = require("./FullNodePeer");
12
+ const Wallet_1 = require("./Wallet");
13
+ const config_1 = require("../utils/config");
14
+ const coins_1 = require("./coins");
15
+ const utils_1 = require("../utils");
16
+ const DataIntegrityTree_1 = require("../DataIntegrityTree");
17
+ const prompts_1 = require("../prompts");
18
+ const FileCache_1 = require("../utils/FileCache");
19
+ const DataStoreSerializer_1 = require("./DataStoreSerializer");
20
+ const stat = (0, util_1.promisify)(fs_1.default.stat);
21
+ const readdir = (0, util_1.promisify)(fs_1.default.readdir);
22
+ class DataStore {
23
+ constructor(storeId, options) {
24
+ this.storeId = storeId;
25
+ let _options;
26
+ if (options) {
27
+ _options = options;
28
+ }
29
+ else {
30
+ _options = {
31
+ storageMode: "local",
32
+ storeDir: config_1.STORE_PATH,
33
+ };
34
+ }
35
+ this.tree = new DataIntegrityTree_1.DataIntegrityTree(storeId, _options);
36
+ }
37
+ get StoreId() {
38
+ return this.storeId;
39
+ }
40
+ get Tree() {
41
+ return this.tree;
42
+ }
43
+ toBuffer() {
44
+ return Buffer.from(this.storeId, "hex");
45
+ }
46
+ toString() {
47
+ return this.storeId;
48
+ }
49
+ serialize() {
50
+ return JSON.stringify({
51
+ storeId: this.storeId,
52
+ });
53
+ }
54
+ static async getActiveStore() {
55
+ const storeId = await (0, config_1.getActiveStoreId)();
56
+ if (storeId) {
57
+ return DataStore.from(storeId.toString("hex"));
58
+ }
59
+ }
60
+ static deserialize(serialized) {
61
+ const parsed = JSON.parse(serialized);
62
+ return new DataStore(parsed.storeId);
63
+ }
64
+ static from(storeId) {
65
+ const existingTreeOptions = {
66
+ storageMode: "local",
67
+ storeDir: config_1.STORE_PATH,
68
+ disableInitialize: true,
69
+ };
70
+ if (storeId instanceof Buffer) {
71
+ return new DataStore(storeId.toString("hex"), existingTreeOptions);
72
+ }
73
+ return new DataStore(storeId, existingTreeOptions);
74
+ }
75
+ static async create(inputs = {}) {
76
+ const finalInputs = await (0, prompts_1.askForStoreDetails)(inputs);
77
+ try {
78
+ const peer = await FullNodePeer_1.FullNodePeer.connect();
79
+ const height = await peer.getPeak();
80
+ if (!height) {
81
+ throw new Error("Failed to get peak height");
82
+ }
83
+ const hash = await peer.getHeaderHash(height);
84
+ const newStoreCoin = await this.mint(finalInputs.label, finalInputs.description, BigInt(0), finalInputs.authorizedWriter);
85
+ console.log("Store submitted to mempool");
86
+ console.log(`Store ID: ${newStoreCoin.launcherId.toString("hex")}`);
87
+ try {
88
+ console.log(`Coin ID: ${(0, datalayer_driver_1.getCoinId)(newStoreCoin.coin).toString("hex")}`);
89
+ await FullNodePeer_1.FullNodePeer.waitForConfirmation(newStoreCoin.coin.parentCoinInfo);
90
+ }
91
+ catch (error) {
92
+ console.error(error.message);
93
+ }
94
+ const dataStore = new DataStore(newStoreCoin.launcherId.toString("hex"));
95
+ await dataStore.setCreationHeight(height, hash);
96
+ return dataStore;
97
+ }
98
+ catch (error) {
99
+ console.error("Failed to mint Data Layer Store:", error);
100
+ throw error;
101
+ }
102
+ }
103
+ static async mint(label, description, sizeInBytes, authorizedWriterPublicSyntheticKey, adminPublicSyntheticKey) {
104
+ try {
105
+ const peer = await FullNodePeer_1.FullNodePeer.connect();
106
+ const wallet = await Wallet_1.Wallet.load("default");
107
+ const publicSyntheticKey = await wallet.getPublicSyntheticKey();
108
+ const ownerSyntheicPuzzleHash = (0, datalayer_driver_1.syntheticKeyToPuzzleHash)(publicSyntheticKey);
109
+ const storeCreationCoins = await (0, coins_1.selectUnspentCoins)(peer, BigInt(1), BigInt(0));
110
+ const delegationLayers = [];
111
+ if (adminPublicSyntheticKey) {
112
+ delegationLayers.push((0, datalayer_driver_1.adminDelegatedPuzzleFromKey)(Buffer.from(adminPublicSyntheticKey, "hex")));
113
+ }
114
+ if (authorizedWriterPublicSyntheticKey) {
115
+ delegationLayers.push((0, datalayer_driver_1.writerDelegatedPuzzleFromKey)(Buffer.from(authorizedWriterPublicSyntheticKey, "hex")));
116
+ }
117
+ delegationLayers.push((0, datalayer_driver_1.oracleDelegatedPuzzle)(ownerSyntheicPuzzleHash, BigInt(100000)));
118
+ const rootHash = Buffer.from("0000000000000000000000000000000000000000000000000000000000000000", "hex");
119
+ const mintStoreParams = [
120
+ publicSyntheticKey,
121
+ storeCreationCoins,
122
+ rootHash,
123
+ label || undefined,
124
+ description || undefined,
125
+ sizeInBytes || BigInt(0),
126
+ ownerSyntheicPuzzleHash,
127
+ delegationLayers,
128
+ ];
129
+ const { coinSpends: preflightCoinSpends } = await (0, datalayer_driver_1.mintStore)(
130
+ // @ts-ignore
131
+ ...mintStoreParams,
132
+ // @ts-ignore
133
+ BigInt(0));
134
+ const fee = await (0, coins_1.calculateFeeForCoinSpends)(peer, preflightCoinSpends);
135
+ const storeCreationResponse = await datalayer_driver_1.mintStore.apply(null, [
136
+ // @ts-ignore
137
+ ...mintStoreParams,
138
+ // @ts-ignore
139
+ fee,
140
+ ]);
141
+ const sig = (0, datalayer_driver_1.signCoinSpends)(storeCreationResponse.coinSpends, [await wallet.getPrivateSyntheticKey()], false);
142
+ const err = await peer.broadcastSpend(storeCreationResponse.coinSpends, [sig]);
143
+ if (err) {
144
+ throw new Error(err);
145
+ }
146
+ await new Promise((resolve) => setTimeout(resolve, 5000));
147
+ return storeCreationResponse.newStore;
148
+ }
149
+ catch (error) {
150
+ console.error("Unable to mint store");
151
+ throw error;
152
+ }
153
+ }
154
+ /**
155
+ * Instance method to calculate the disk space used by the store/storeId folder.
156
+ * @returns {Promise<number>} - The total disk space used by the store in bytes.
157
+ */
158
+ async getDiskSpace() {
159
+ const storePath = path_1.default.join(config_1.STORE_PATH, this.storeId);
160
+ return await DataStore.calculateFolderSize(storePath);
161
+ }
162
+ /**
163
+ * Static method to calculate the total disk space used by all stores in the store folder.
164
+ * @returns {Promise<number>} - The total disk space used by the store folder in bytes.
165
+ */
166
+ static async getTotalDiskSpace() {
167
+ return await DataStore.calculateFolderSize(config_1.STORE_PATH);
168
+ }
169
+ /**
170
+ * Helper method to calculate the size of a folder and its subfolders recursively.
171
+ * @param folderPath - The path of the folder to calculate the size of.
172
+ * @returns {Promise<number>} - The total size of the folder in bytes.
173
+ */
174
+ static async calculateFolderSize(folderPath) {
175
+ let totalSize = BigInt(0);
176
+ const files = await readdir(folderPath);
177
+ for (const file of files) {
178
+ const filePath = path_1.default.join(folderPath, file);
179
+ const fileStat = await stat(filePath);
180
+ if (fileStat.isDirectory()) {
181
+ totalSize += await this.calculateFolderSize(filePath); // Recursive call for subdirectories
182
+ }
183
+ else {
184
+ totalSize += BigInt(fileStat.size); // Add file size to total
185
+ }
186
+ }
187
+ return totalSize;
188
+ }
189
+ static getAllStores() {
190
+ const storeFolders = fs_1.default.readdirSync(config_1.STORE_PATH);
191
+ const storIds = storeFolders.filter((folder) => /^[a-f0-9]{64}$/.test(folder) &&
192
+ fs_1.default.lstatSync(path_1.default.join(config_1.STORE_PATH, folder)).isDirectory());
193
+ return storIds.map((storeId) => DataStore.from(storeId));
194
+ }
195
+ async fetchCoinInfo() {
196
+ try {
197
+ // Initialize the cache for the current storeId's coin info
198
+ const storeCoinCache = new FileCache_1.FileCache(`stores`);
199
+ // Try to get cached store info
200
+ const cachedInfo = storeCoinCache.get(this.storeId);
201
+ if (cachedInfo) {
202
+ try {
203
+ const { latestStore: serializedStore, latestHeight: previousHeight, latestHash: previousHash, } = cachedInfo;
204
+ // Deserialize the stored data using DataStoreSerializer
205
+ const { latestStore: previousInfo } = DataStoreSerializer_1.DataStoreSerializer.deserialize({
206
+ latestStore: serializedStore,
207
+ latestHeight: previousHeight.toString(),
208
+ latestHash: previousHash,
209
+ });
210
+ // Sync with peer if necessary
211
+ const peer = await FullNodePeer_1.FullNodePeer.connect();
212
+ const { latestStore, latestHeight } = await peer.syncStore(previousInfo, previousHeight, Buffer.from(previousHash, "hex"), false);
213
+ const latestHash = await peer.getHeaderHash(latestHeight);
214
+ // Serialize the store data for caching
215
+ const serializedLatestStore = new DataStoreSerializer_1.DataStoreSerializer(latestStore, latestHeight, latestHash).serialize();
216
+ // Cache updated store info
217
+ storeCoinCache.set(this.storeId, {
218
+ latestStore: serializedLatestStore,
219
+ latestHeight,
220
+ latestHash: latestHash.toString("hex"),
221
+ });
222
+ return { latestStore, latestHeight, latestHash };
223
+ }
224
+ catch {
225
+ // Return cached info if sync fails
226
+ const { latestStore, latestHeight, latestHash } = DataStoreSerializer_1.DataStoreSerializer.deserialize({
227
+ latestStore: cachedInfo.latestStore,
228
+ latestHeight: cachedInfo.latestHeight.toString(),
229
+ latestHash: cachedInfo.latestHash,
230
+ });
231
+ return {
232
+ latestStore,
233
+ latestHeight,
234
+ latestHash: latestHash,
235
+ };
236
+ }
237
+ }
238
+ // Use getCreationHeight to retrieve height and hash information
239
+ const { createdAtHeight, createdAtHash } = await this.getCreationHeight();
240
+ // Sync store from peer
241
+ const peer = await FullNodePeer_1.FullNodePeer.connect();
242
+ const { latestStore, latestHeight } = await peer.syncStoreFromLauncherId(Buffer.from(this.storeId, "hex"), createdAtHeight, createdAtHash, false);
243
+ const latestHash = await peer.getHeaderHash(latestHeight);
244
+ // Serialize the latest store info for caching
245
+ const serializedLatestStore = new DataStoreSerializer_1.DataStoreSerializer(latestStore, latestHeight, latestHash).serialize();
246
+ // Cache the latest store info
247
+ storeCoinCache.set(this.storeId, {
248
+ latestStore: serializedLatestStore,
249
+ latestHeight,
250
+ latestHash: latestHash.toString("hex"),
251
+ });
252
+ return { latestStore, latestHeight, latestHash };
253
+ }
254
+ catch (error) {
255
+ console.trace("Failed to fetch coin info", error);
256
+ throw error;
257
+ }
258
+ }
259
+ async getCreationHeight() {
260
+ const defaultHeight = config_1.MIN_HEIGHT;
261
+ const defaultHash = Buffer.from(config_1.MIN_HEIGHT_HEADER_HASH, "hex");
262
+ // Initialize the FileCache for the height file
263
+ const fileCache = new FileCache_1.FileCache(`stores/${this.storeId}`);
264
+ // Try to retrieve the cached height information
265
+ const cachedHeightInfo = fileCache.get("height");
266
+ if (!cachedHeightInfo) {
267
+ // If no cache, return the default values
268
+ return { createdAtHeight: defaultHeight, createdAtHash: defaultHash };
269
+ }
270
+ // Parse the cached height and hash values
271
+ const { height, hash } = cachedHeightInfo;
272
+ return {
273
+ createdAtHeight: height || defaultHeight,
274
+ createdAtHash: Buffer.from(hash || config_1.MIN_HEIGHT_HEADER_HASH, "hex"),
275
+ };
276
+ }
277
+ async setCreationHeight(height, hash) {
278
+ const fileCache = new FileCache_1.FileCache(`stores/${this.storeId}`);
279
+ // Cache the height and hash information
280
+ fileCache.set("height", {
281
+ height,
282
+ hash: hash.toString("hex"),
283
+ });
284
+ }
285
+ async getRootHistory() {
286
+ const peer = await FullNodePeer_1.FullNodePeer.connect();
287
+ const { createdAtHeight, createdAtHash } = await this.getCreationHeight();
288
+ const { rootHashes, rootHashesTimestamps } = await peer.syncStoreFromLauncherId(Buffer.from(this.storeId, "hex"), createdAtHeight, createdAtHash, true);
289
+ if (!rootHashes) {
290
+ return [];
291
+ }
292
+ return rootHashes.map((rootHash, index) => ({
293
+ root_hash: rootHash.toString("hex"),
294
+ timestamp: Number(rootHashesTimestamps?.[index].toString()),
295
+ }));
296
+ }
297
+ async getLocalRootHistory() {
298
+ const manifestFilePath = (0, config_1.getManifestFilePath)(this.storeId);
299
+ if (!fs_1.default.existsSync(manifestFilePath)) {
300
+ console.error("Manifest file not found", manifestFilePath);
301
+ return undefined;
302
+ }
303
+ const manifestHashes = fs_1.default
304
+ .readFileSync(manifestFilePath, "utf-8")
305
+ .split("\n")
306
+ .filter(Boolean);
307
+ return manifestHashes.map((rootHash) => ({
308
+ root_hash: rootHash,
309
+ timestamp: 0, // Timestamps are not yet included in the manifest
310
+ }));
311
+ }
312
+ async validate() {
313
+ const rootHistory = await this.getRootHistory();
314
+ const manifestFilePath = (0, config_1.getManifestFilePath)(this.storeId);
315
+ if (!fs_1.default.existsSync(manifestFilePath)) {
316
+ console.error("Manifest file not found", manifestFilePath);
317
+ return false;
318
+ }
319
+ const manifestHashes = fs_1.default
320
+ .readFileSync(manifestFilePath, "utf-8")
321
+ .split("\n")
322
+ .filter(Boolean);
323
+ if (manifestHashes.length > rootHistory.length) {
324
+ console.error("The store is corrupted: Manifest file has more hashes than the root history.");
325
+ return false;
326
+ }
327
+ if (rootHistory.length > manifestHashes.length) {
328
+ console.error("The store is not synced: Root history has more hashes than the manifest file.");
329
+ return false;
330
+ }
331
+ for (let i = 0; i < manifestHashes.length; i++) {
332
+ if (manifestHashes[i] !== rootHistory[i]?.root_hash) {
333
+ console.error(`Root hash mismatch at position ${i}: expected ${manifestHashes[i]} but found ${rootHistory[i]?.root_hash}`);
334
+ return false;
335
+ }
336
+ }
337
+ let filesIntegrityIntact = true;
338
+ for (const rootHash of manifestHashes) {
339
+ const datFilePath = path_1.default.join(config_1.STORE_PATH, this.storeId, `${rootHash}.dat`);
340
+ if (!fs_1.default.existsSync(datFilePath)) {
341
+ console.error(`Data file for root hash ${rootHash} not found`);
342
+ return false;
343
+ }
344
+ const datFileContent = JSON.parse(fs_1.default.readFileSync(datFilePath, "utf-8"));
345
+ if (datFileContent.root !== rootHash) {
346
+ console.error(`Root hash in data file does not match: ${datFileContent.root} !== ${rootHash}`);
347
+ return false;
348
+ }
349
+ for (const [fileKey, fileData] of Object.entries(datFileContent.files)) {
350
+ const integrityCheck = (0, utils_1.validateFileSha256)(fileData.sha256, path_1.default.join(config_1.STORE_PATH, this.storeId, "data"));
351
+ if (!integrityCheck) {
352
+ filesIntegrityIntact = false;
353
+ }
354
+ }
355
+ }
356
+ if (!filesIntegrityIntact) {
357
+ console.error("Store Corrupted: Data failed SHA256 validation.");
358
+ return false;
359
+ }
360
+ return true;
361
+ }
362
+ async getMetaData() {
363
+ const { latestStore } = await this.fetchCoinInfo();
364
+ return latestStore.metadata;
365
+ }
366
+ async isSynced() {
367
+ const rootHistory = await this.getRootHistory();
368
+ const manifestFilePath = (0, config_1.getManifestFilePath)(this.storeId);
369
+ if (!fs_1.default.existsSync(manifestFilePath)) {
370
+ return false;
371
+ }
372
+ const manifestHashes = fs_1.default
373
+ .readFileSync(manifestFilePath, "utf-8")
374
+ .split("\n")
375
+ .filter(Boolean);
376
+ return rootHistory.length === manifestHashes.length;
377
+ }
378
+ async hasMetaWritePermissions(publicSyntheticKey) {
379
+ const wallet = await Wallet_1.Wallet.load("default");
380
+ const { latestStore } = await this.fetchCoinInfo();
381
+ let ownerPuzzleHash = publicSyntheticKey
382
+ ? (0, datalayer_driver_1.syntheticKeyToPuzzleHash)(publicSyntheticKey)
383
+ : await wallet.getOwnerPuzzleHash();
384
+ const isStoreOwner = latestStore.ownerPuzzleHash.equals(ownerPuzzleHash);
385
+ const hasWriteAccess = latestStore.delegatedPuzzles.some((puzzle) => puzzle.adminInnerPuzzleHash?.equals(ownerPuzzleHash) ||
386
+ puzzle.writerInnerPuzzleHash?.equals(ownerPuzzleHash));
387
+ return isStoreOwner || hasWriteAccess;
388
+ }
389
+ async updateMetadata(metadata) {
390
+ const peer = await FullNodePeer_1.FullNodePeer.connect();
391
+ const wallet = await Wallet_1.Wallet.load("default");
392
+ const publicSyntheticKey = await wallet.getPublicSyntheticKey();
393
+ const { latestStore } = await this.fetchCoinInfo();
394
+ const updateStoreResponse = (0, datalayer_driver_1.updateStoreMetadata)(latestStore, metadata.rootHash, metadata.label, metadata.description, metadata.bytes, publicSyntheticKey, null, null);
395
+ const fee = await (0, coins_1.calculateFeeForCoinSpends)(peer, null);
396
+ const unspentCoins = await (0, coins_1.selectUnspentCoins)(peer, BigInt(0), fee);
397
+ const feeCoinSpends = await (0, datalayer_driver_1.addFee)(publicSyntheticKey, unspentCoins, updateStoreResponse.coinSpends.map((coinSpend) => (0, datalayer_driver_1.getCoinId)(coinSpend.coin)), fee);
398
+ const combinedCoinSpends = [
399
+ ...updateStoreResponse.coinSpends,
400
+ ...feeCoinSpends,
401
+ ];
402
+ const sig = (0, datalayer_driver_1.signCoinSpends)(combinedCoinSpends, [await wallet.getPrivateSyntheticKey()], false);
403
+ const err = await peer.broadcastSpend(combinedCoinSpends, [sig]);
404
+ if (err) {
405
+ throw new Error(err);
406
+ }
407
+ return updateStoreResponse.newStore;
408
+ }
409
+ }
410
+ exports.DataStore = DataStore;
@@ -0,0 +1,52 @@
1
+ import { DataStore } from "datalayer-driver";
2
+ import { Buffer } from "buffer";
3
+ export declare class DataStoreSerializer {
4
+ private storeInfo;
5
+ private latestHeight;
6
+ private latestHash;
7
+ constructor(storeInfo: DataStore, latestHeight: number, latestHash: Buffer);
8
+ serialize(): {
9
+ coin: {
10
+ parentCoinInfo: string;
11
+ puzzleHash: string;
12
+ amount: string;
13
+ };
14
+ launcherId: string;
15
+ proof: {
16
+ lineageProof: {
17
+ parentParentCoinInfo: string;
18
+ parentInnerPuzzleHash: string;
19
+ parentAmount: string;
20
+ } | undefined;
21
+ eveProof: {
22
+ parentParentCoinInfo: string;
23
+ parentAmount: string;
24
+ } | undefined;
25
+ };
26
+ metadata: {
27
+ rootHash: string;
28
+ label: string | undefined;
29
+ description: string | undefined;
30
+ bytes: string | undefined;
31
+ };
32
+ ownerPuzzleHash: string;
33
+ delegatedPuzzles: {
34
+ adminInnerPuzzleHash: string | undefined;
35
+ writerInnerPuzzleHash: string | undefined;
36
+ oraclePaymentPuzzleHash: string | undefined;
37
+ oracleFee: string | undefined;
38
+ }[];
39
+ latestHeight: string;
40
+ latestHash: string;
41
+ };
42
+ static deserialize(data: {
43
+ latestStore: any;
44
+ latestHeight: string;
45
+ latestHash: string;
46
+ }): {
47
+ latestStore: DataStore;
48
+ latestHeight: number;
49
+ latestHash: Buffer;
50
+ };
51
+ }
52
+ //# sourceMappingURL=DataStoreSerializer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DataStoreSerializer.d.ts","sourceRoot":"","sources":["../../src/blockchain/DataStoreSerializer.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EAKV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,SAAS,CAAY;IAC7B,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,UAAU,CAAS;gBAEf,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM;IAOnE,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WAgDF,WAAW,CACvB,IAAI,EAAE;QACJ,WAAW,EAAE,GAAG,CAAC;QACjB,YAAY,EAAE,MAAM,CAAC;QACrB,UAAU,EAAE,MAAM,CAAC;KACpB,GACA;QACD,WAAW,EAAE,SAAS,CAAC;QACvB,YAAY,EAAE,MAAM,CAAC;QACrB,UAAU,EAAE,MAAM,CAAC;KACpB;CAuEF"}
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DataStoreSerializer = void 0;
4
+ const buffer_1 = require("buffer");
5
+ class DataStoreSerializer {
6
+ constructor(storeInfo, latestHeight, latestHash) {
7
+ this.storeInfo = storeInfo;
8
+ this.latestHeight = latestHeight;
9
+ this.latestHash = latestHash;
10
+ }
11
+ // Serialize the DataStore object and additional fields
12
+ serialize() {
13
+ return {
14
+ coin: {
15
+ parentCoinInfo: this.storeInfo.coin.parentCoinInfo.toString("hex"),
16
+ puzzleHash: this.storeInfo.coin.puzzleHash.toString("hex"),
17
+ amount: this.storeInfo.coin.amount.toString(),
18
+ },
19
+ launcherId: this.storeInfo.launcherId.toString("hex"),
20
+ proof: {
21
+ lineageProof: this.storeInfo.proof.lineageProof
22
+ ? {
23
+ parentParentCoinInfo: this.storeInfo.proof.lineageProof.parentParentCoinInfo.toString("hex"),
24
+ parentInnerPuzzleHash: this.storeInfo.proof.lineageProof.parentInnerPuzzleHash.toString("hex"),
25
+ parentAmount: this.storeInfo.proof.lineageProof.parentAmount.toString(),
26
+ }
27
+ : undefined,
28
+ eveProof: this.storeInfo.proof.eveProof
29
+ ? {
30
+ parentParentCoinInfo: this.storeInfo.proof.eveProof.parentParentCoinInfo.toString("hex"),
31
+ parentAmount: this.storeInfo.proof.eveProof.parentAmount.toString(),
32
+ }
33
+ : undefined,
34
+ },
35
+ metadata: {
36
+ rootHash: this.storeInfo.metadata.rootHash.toString("hex"),
37
+ label: this.storeInfo.metadata.label,
38
+ description: this.storeInfo.metadata.description,
39
+ bytes: this.storeInfo.metadata.bytes?.toString(),
40
+ },
41
+ ownerPuzzleHash: this.storeInfo.ownerPuzzleHash.toString("hex"),
42
+ delegatedPuzzles: this.storeInfo.delegatedPuzzles.map((puzzle) => ({
43
+ adminInnerPuzzleHash: puzzle.adminInnerPuzzleHash?.toString("hex"),
44
+ writerInnerPuzzleHash: puzzle.writerInnerPuzzleHash?.toString("hex"),
45
+ oraclePaymentPuzzleHash: puzzle.oraclePaymentPuzzleHash?.toString("hex"),
46
+ oracleFee: puzzle.oracleFee?.toString(),
47
+ })),
48
+ latestHeight: this.latestHeight.toString(),
49
+ latestHash: this.latestHash.toString("base64"), // Use base64 for Buffer
50
+ };
51
+ }
52
+ // Deserialize the data back into DataStore and associated fields
53
+ static deserialize(data) {
54
+ const coin = {
55
+ parentCoinInfo: buffer_1.Buffer.from(data.latestStore.coin.parentCoinInfo, "hex"),
56
+ puzzleHash: buffer_1.Buffer.from(data.latestStore.coin.puzzleHash, "hex"),
57
+ amount: BigInt(data.latestStore.coin.amount),
58
+ };
59
+ const proof = {
60
+ lineageProof: data.latestStore.proof.lineageProof
61
+ ? {
62
+ parentParentCoinInfo: buffer_1.Buffer.from(data.latestStore.proof.lineageProof.parentParentCoinInfo, "hex"),
63
+ parentInnerPuzzleHash: buffer_1.Buffer.from(data.latestStore.proof.lineageProof.parentInnerPuzzleHash, "hex"),
64
+ parentAmount: BigInt(data.latestStore.proof.lineageProof.parentAmount),
65
+ }
66
+ : undefined,
67
+ eveProof: data.latestStore.proof.eveProof
68
+ ? {
69
+ parentParentCoinInfo: buffer_1.Buffer.from(data.latestStore.proof.eveProof.parentParentCoinInfo, "hex"),
70
+ parentAmount: BigInt(data.latestStore.proof.eveProof.parentAmount),
71
+ }
72
+ : undefined,
73
+ };
74
+ const metadata = {
75
+ rootHash: buffer_1.Buffer.from(data.latestStore.metadata.rootHash, "hex"),
76
+ label: data.latestStore.metadata.label,
77
+ description: data.latestStore.metadata.description,
78
+ bytes: data.latestStore.metadata.bytes
79
+ ? BigInt(data.latestStore.metadata.bytes)
80
+ : undefined,
81
+ };
82
+ const delegatedPuzzles = data.latestStore.delegatedPuzzles.map((puzzle) => ({
83
+ adminInnerPuzzleHash: puzzle.adminInnerPuzzleHash
84
+ ? buffer_1.Buffer.from(puzzle.adminInnerPuzzleHash, "hex")
85
+ : undefined,
86
+ writerInnerPuzzleHash: puzzle.writerInnerPuzzleHash
87
+ ? buffer_1.Buffer.from(puzzle.writerInnerPuzzleHash, "hex")
88
+ : undefined,
89
+ oraclePaymentPuzzleHash: puzzle.oraclePaymentPuzzleHash
90
+ ? buffer_1.Buffer.from(puzzle.oraclePaymentPuzzleHash, "hex")
91
+ : undefined,
92
+ oracleFee: puzzle.oracleFee ? BigInt(puzzle.oracleFee) : undefined,
93
+ }));
94
+ const dataStoreInfo = {
95
+ coin,
96
+ launcherId: buffer_1.Buffer.from(data.latestStore.launcherId, "hex"),
97
+ proof,
98
+ metadata,
99
+ ownerPuzzleHash: buffer_1.Buffer.from(data.latestStore.ownerPuzzleHash, "hex"),
100
+ delegatedPuzzles,
101
+ };
102
+ return {
103
+ latestStore: dataStoreInfo,
104
+ latestHeight: parseInt(data.latestHeight, 10),
105
+ latestHash: buffer_1.Buffer.from(data.latestHash, "base64"), // Deserialize from base64
106
+ };
107
+ }
108
+ }
109
+ exports.DataStoreSerializer = DataStoreSerializer;
@@ -0,0 +1,17 @@
1
+ import { Peer } from "datalayer-driver";
2
+ export declare class FullNodePeer {
3
+ private static cachedPeer;
4
+ private static memoizedFetchNewPeerIPs;
5
+ private peer;
6
+ private constructor();
7
+ static connect(): Promise<Peer>;
8
+ private static isPortReachable;
9
+ private static isValidIpAddress;
10
+ private static fetchNewPeerIPs;
11
+ private static getPeerIPs;
12
+ private static createPeerProxy;
13
+ private static getBestPeer;
14
+ getPeer(): Peer;
15
+ static waitForConfirmation(parentCoinInfo: Buffer): Promise<boolean>;
16
+ }
17
+ //# sourceMappingURL=FullNodePeer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FullNodePeer.d.ts","sourceRoot":"","sources":["../../src/blockchain/FullNodePeer.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAmBxC,qBAAa,YAAY;IACvB,OAAO,CAAC,MAAM,CAAC,UAAU,CAAkD;IAC3E,OAAO,CAAC,MAAM,CAAC,uBAAuB,CAA0B;IAChE,OAAO,CAAC,IAAI,CAAO;IAQnB,OAAO;WAIa,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAK5C,OAAO,CAAC,MAAM,CAAC,eAAe;IAiB9B,OAAO,CAAC,MAAM,CAAC,gBAAgB;mBAOV,eAAe;mBAkDf,UAAU;IAyB/B,OAAO,CAAC,MAAM,CAAC,eAAe;mBA4BT,WAAW;IAgGzB,OAAO,IAAI,IAAI;WAIF,mBAAmB,CACrC,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,OAAO,CAAC;CAwBpB"}