@dignetwork/dig-sdk 0.0.1-alpha.98 → 0.1.0

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 (162) hide show
  1. package/LICENSE +21 -7
  2. package/README.md +267 -0
  3. package/dist/adapters.cjs +315 -0
  4. package/dist/adapters.cjs.map +1 -0
  5. package/dist/adapters.d.cts +20 -0
  6. package/dist/adapters.d.ts +20 -0
  7. package/dist/adapters.js +306 -0
  8. package/dist/adapters.js.map +1 -0
  9. package/dist/dev-shim-Bgw8X2E9.d.cts +118 -0
  10. package/dist/dev-shim-Bgw8X2E9.d.ts +118 -0
  11. package/dist/dig-client-entry-BIzuZ7Rs.d.cts +263 -0
  12. package/dist/dig-client-entry-BIzuZ7Rs.d.ts +263 -0
  13. package/dist/dig-client.cjs +330 -0
  14. package/dist/dig-client.cjs.map +1 -0
  15. package/dist/dig-client.d.cts +1 -0
  16. package/dist/dig-client.d.ts +1 -0
  17. package/dist/dig-client.js +319 -0
  18. package/dist/dig-client.js.map +1 -0
  19. package/dist/index.cjs +754 -0
  20. package/dist/index.cjs.map +1 -0
  21. package/dist/index.d.cts +192 -0
  22. package/dist/index.d.ts +192 -5
  23. package/dist/index.js +731 -19
  24. package/dist/index.js.map +1 -0
  25. package/dist/next.cjs +326 -0
  26. package/dist/next.cjs.map +1 -0
  27. package/dist/next.d.cts +23 -0
  28. package/dist/next.d.ts +23 -0
  29. package/dist/next.js +319 -0
  30. package/dist/next.js.map +1 -0
  31. package/dist/spend.cjs +14 -0
  32. package/dist/spend.cjs.map +1 -0
  33. package/dist/spend.d.cts +1 -0
  34. package/dist/spend.d.ts +1 -0
  35. package/dist/spend.js +3 -0
  36. package/dist/spend.js.map +1 -0
  37. package/dist/vite.cjs +338 -0
  38. package/dist/vite.cjs.map +1 -0
  39. package/dist/vite.d.cts +35 -0
  40. package/dist/vite.d.ts +35 -0
  41. package/dist/vite.js +332 -0
  42. package/dist/vite.js.map +1 -0
  43. package/package.json +87 -59
  44. package/vendor/PROVENANCE.md +102 -0
  45. package/vendor/dig_client.d.ts +150 -0
  46. package/vendor/dig_client.mjs +805 -0
  47. package/vendor/dig_client_bg.wasm +0 -0
  48. package/dist/DataIntegrityTree/DataIntegrityTree.d.ts +0 -163
  49. package/dist/DataIntegrityTree/DataIntegrityTree.d.ts.map +0 -1
  50. package/dist/DataIntegrityTree/DataIntegrityTree.js +0 -707
  51. package/dist/DataIntegrityTree/DataLayerError.d.ts +0 -6
  52. package/dist/DataIntegrityTree/DataLayerError.d.ts.map +0 -1
  53. package/dist/DataIntegrityTree/DataLayerError.js +0 -17
  54. package/dist/DataIntegrityTree/index.d.ts +0 -2
  55. package/dist/DataIntegrityTree/index.d.ts.map +0 -1
  56. package/dist/DataIntegrityTree/index.js +0 -17
  57. package/dist/DigNetwork/ContentServer.d.ts +0 -33
  58. package/dist/DigNetwork/ContentServer.d.ts.map +0 -1
  59. package/dist/DigNetwork/ContentServer.js +0 -308
  60. package/dist/DigNetwork/DigChallenge.d.ts +0 -82
  61. package/dist/DigNetwork/DigChallenge.d.ts.map +0 -1
  62. package/dist/DigNetwork/DigChallenge.js +0 -144
  63. package/dist/DigNetwork/DigNetwork.d.ts +0 -14
  64. package/dist/DigNetwork/DigNetwork.d.ts.map +0 -1
  65. package/dist/DigNetwork/DigNetwork.js +0 -169
  66. package/dist/DigNetwork/DigPeer.d.ts +0 -24
  67. package/dist/DigNetwork/DigPeer.d.ts.map +0 -1
  68. package/dist/DigNetwork/DigPeer.js +0 -118
  69. package/dist/DigNetwork/IncentiveServer.d.ts +0 -13
  70. package/dist/DigNetwork/IncentiveServer.d.ts.map +0 -1
  71. package/dist/DigNetwork/IncentiveServer.js +0 -76
  72. package/dist/DigNetwork/PropagationServer.d.ts +0 -75
  73. package/dist/DigNetwork/PropagationServer.d.ts.map +0 -1
  74. package/dist/DigNetwork/PropagationServer.js +0 -536
  75. package/dist/DigNetwork/index.d.ts +0 -4
  76. package/dist/DigNetwork/index.d.ts.map +0 -1
  77. package/dist/DigNetwork/index.js +0 -19
  78. package/dist/blockchain/DataStore.d.ts +0 -67
  79. package/dist/blockchain/DataStore.d.ts.map +0 -1
  80. package/dist/blockchain/DataStore.js +0 -413
  81. package/dist/blockchain/DataStoreSerializer.d.ts +0 -52
  82. package/dist/blockchain/DataStoreSerializer.d.ts.map +0 -1
  83. package/dist/blockchain/DataStoreSerializer.js +0 -109
  84. package/dist/blockchain/FullNodePeer.d.ts +0 -31
  85. package/dist/blockchain/FullNodePeer.d.ts.map +0 -1
  86. package/dist/blockchain/FullNodePeer.js +0 -295
  87. package/dist/blockchain/ServerCoin.d.ts +0 -29
  88. package/dist/blockchain/ServerCoin.d.ts.map +0 -1
  89. package/dist/blockchain/ServerCoin.js +0 -321
  90. package/dist/blockchain/Wallet.d.ts +0 -28
  91. package/dist/blockchain/Wallet.d.ts.map +0 -1
  92. package/dist/blockchain/Wallet.js +0 -253
  93. package/dist/blockchain/coins.d.ts +0 -6
  94. package/dist/blockchain/coins.d.ts.map +0 -1
  95. package/dist/blockchain/coins.js +0 -102
  96. package/dist/blockchain/index.d.ts +0 -8
  97. package/dist/blockchain/index.d.ts.map +0 -1
  98. package/dist/blockchain/index.js +0 -36
  99. package/dist/index.d.ts.map +0 -1
  100. package/dist/prompts.d.ts +0 -21
  101. package/dist/prompts.d.ts.map +0 -1
  102. package/dist/prompts.js +0 -149
  103. package/dist/types.d.ts +0 -64
  104. package/dist/types.d.ts.map +0 -1
  105. package/dist/types.js +0 -2
  106. package/dist/utils/ContentScanner.d.ts +0 -63
  107. package/dist/utils/ContentScanner.d.ts.map +0 -1
  108. package/dist/utils/ContentScanner.js +0 -175
  109. package/dist/utils/Environment.d.ts +0 -18
  110. package/dist/utils/Environment.d.ts.map +0 -1
  111. package/dist/utils/Environment.js +0 -85
  112. package/dist/utils/FileCache.d.ts +0 -11
  113. package/dist/utils/FileCache.d.ts.map +0 -1
  114. package/dist/utils/FileCache.js +0 -58
  115. package/dist/utils/FileTransfer.d.ts +0 -47
  116. package/dist/utils/FileTransfer.d.ts.map +0 -1
  117. package/dist/utils/FileTransfer.js +0 -209
  118. package/dist/utils/NconfManager.d.ts +0 -11
  119. package/dist/utils/NconfManager.d.ts.map +0 -1
  120. package/dist/utils/NconfManager.js +0 -56
  121. package/dist/utils/StoreArchiveManager.d.ts +0 -45
  122. package/dist/utils/StoreArchiveManager.d.ts.map +0 -1
  123. package/dist/utils/StoreArchiveManager.js +0 -153
  124. package/dist/utils/asyncPool.d.ts +0 -9
  125. package/dist/utils/asyncPool.d.ts.map +0 -1
  126. package/dist/utils/asyncPool.js +0 -23
  127. package/dist/utils/config.d.ts +0 -68
  128. package/dist/utils/config.d.ts.map +0 -1
  129. package/dist/utils/config.js +0 -223
  130. package/dist/utils/connectionUtils.d.ts +0 -10
  131. package/dist/utils/connectionUtils.d.ts.map +0 -1
  132. package/dist/utils/connectionUtils.js +0 -18
  133. package/dist/utils/credentialsUtils.d.ts +0 -8
  134. package/dist/utils/credentialsUtils.d.ts.map +0 -1
  135. package/dist/utils/credentialsUtils.js +0 -122
  136. package/dist/utils/directoryUtils.d.ts +0 -9
  137. package/dist/utils/directoryUtils.d.ts.map +0 -1
  138. package/dist/utils/directoryUtils.js +0 -110
  139. package/dist/utils/encryption.d.ts +0 -8
  140. package/dist/utils/encryption.d.ts.map +0 -1
  141. package/dist/utils/encryption.js +0 -55
  142. package/dist/utils/hashUtils.d.ts +0 -8
  143. package/dist/utils/hashUtils.d.ts.map +0 -1
  144. package/dist/utils/hashUtils.js +0 -44
  145. package/dist/utils/index.d.ts +0 -14
  146. package/dist/utils/index.d.ts.map +0 -1
  147. package/dist/utils/index.js +0 -29
  148. package/dist/utils/merkle.d.ts +0 -2
  149. package/dist/utils/merkle.d.ts.map +0 -1
  150. package/dist/utils/merkle.js +0 -28
  151. package/dist/utils/network.d.ts +0 -2
  152. package/dist/utils/network.d.ts.map +0 -1
  153. package/dist/utils/network.js +0 -54
  154. package/dist/utils/spinnerUtils.d.ts +0 -2
  155. package/dist/utils/spinnerUtils.d.ts.map +0 -1
  156. package/dist/utils/spinnerUtils.js +0 -47
  157. package/dist/utils/ssl.d.ts +0 -5
  158. package/dist/utils/ssl.d.ts.map +0 -1
  159. package/dist/utils/ssl.js +0 -50
  160. package/dist/utils/validationUtils.d.ts +0 -9
  161. package/dist/utils/validationUtils.d.ts.map +0 -1
  162. package/dist/utils/validationUtils.js +0 -55
@@ -1,413 +0,0 @@
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("@dignetwork/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 colorette_1 = require("colorette");
16
- const hashUtils_1 = require("../utils/hashUtils");
17
- const DataIntegrityTree_1 = require("../DataIntegrityTree");
18
- const prompts_1 = require("../prompts");
19
- const FileCache_1 = require("../utils/FileCache");
20
- const DataStoreSerializer_1 = require("./DataStoreSerializer");
21
- const node_cache_1 = __importDefault(require("node-cache"));
22
- const config_2 = require("../utils/config");
23
- // Initialize the cache with a TTL of 180 seconds (3 minutes)
24
- const rootHistoryCache = new node_cache_1.default({ stdTTL: 180 });
25
- const stat = (0, util_1.promisify)(fs_1.default.stat);
26
- const readdir = (0, util_1.promisify)(fs_1.default.readdir);
27
- class DataStore {
28
- constructor(storeId, options) {
29
- this.storeId = storeId;
30
- let _options;
31
- if (options) {
32
- _options = options;
33
- }
34
- else {
35
- _options = {
36
- storageMode: "local",
37
- storeDir: config_1.STORE_PATH,
38
- };
39
- }
40
- this.tree = new DataIntegrityTree_1.DataIntegrityTree(storeId, _options);
41
- }
42
- get StoreId() {
43
- return this.storeId;
44
- }
45
- get Tree() {
46
- return this.tree;
47
- }
48
- toBuffer() {
49
- return Buffer.from(this.storeId, "hex");
50
- }
51
- toString() {
52
- return this.storeId;
53
- }
54
- serialize() {
55
- return JSON.stringify({
56
- storeId: this.storeId,
57
- });
58
- }
59
- static async getActiveStore() {
60
- const storeId = await (0, config_1.getActiveStoreId)();
61
- if (storeId) {
62
- return DataStore.from(storeId.toString("hex"));
63
- }
64
- }
65
- static deserialize(serialized) {
66
- const parsed = JSON.parse(serialized);
67
- return new DataStore(parsed.storeId);
68
- }
69
- static from(storeId, rootHash) {
70
- const existingTreeOptions = {
71
- storageMode: "local",
72
- storeDir: config_1.STORE_PATH,
73
- disableInitialize: true,
74
- };
75
- if (rootHash) {
76
- existingTreeOptions.rootHash = rootHash;
77
- }
78
- if (storeId instanceof Buffer) {
79
- return new DataStore(storeId.toString("hex"), existingTreeOptions);
80
- }
81
- return new DataStore(storeId, existingTreeOptions);
82
- }
83
- static async create(inputs = {}) {
84
- const finalInputs = await (0, prompts_1.askForStoreDetails)(inputs);
85
- try {
86
- const peer = await FullNodePeer_1.FullNodePeer.connect();
87
- const height = await peer.getPeak();
88
- if (!height) {
89
- throw new Error("Failed to get peak height");
90
- }
91
- const hash = await peer.getHeaderHash(height);
92
- const newStoreCoin = await this.mint(finalInputs.label, finalInputs.description, BigInt(0), finalInputs.authorizedWriter);
93
- console.log("Store submitted to mempool");
94
- console.log(`Store ID: ${newStoreCoin.launcherId.toString("hex")}`);
95
- try {
96
- console.log(`Coin ID: ${(0, datalayer_driver_1.getCoinId)(newStoreCoin.coin).toString("hex")}`);
97
- await FullNodePeer_1.FullNodePeer.waitForConfirmation(newStoreCoin.coin.parentCoinInfo);
98
- }
99
- catch (error) {
100
- console.error(error.message);
101
- }
102
- const dataStore = new DataStore(newStoreCoin.launcherId.toString("hex"));
103
- await dataStore.setCreationHeight(height, hash);
104
- return dataStore;
105
- }
106
- catch (error) {
107
- console.error("Failed to mint Data Layer Store:", error);
108
- throw error;
109
- }
110
- }
111
- static async mint(label, description, sizeInBytes, authorizedWriterPublicSyntheticKey, adminPublicSyntheticKey) {
112
- try {
113
- const peer = await FullNodePeer_1.FullNodePeer.connect();
114
- const wallet = await Wallet_1.Wallet.load("default");
115
- const publicSyntheticKey = await wallet.getPublicSyntheticKey();
116
- const ownerSyntheicPuzzleHash = (0, datalayer_driver_1.syntheticKeyToPuzzleHash)(publicSyntheticKey);
117
- const storeCreationCoins = await (0, coins_1.selectUnspentCoins)(peer, BigInt(1), BigInt(0));
118
- const delegationLayers = [];
119
- if (adminPublicSyntheticKey) {
120
- delegationLayers.push((0, datalayer_driver_1.adminDelegatedPuzzleFromKey)(Buffer.from(adminPublicSyntheticKey, "hex")));
121
- }
122
- if (authorizedWriterPublicSyntheticKey) {
123
- delegationLayers.push((0, datalayer_driver_1.writerDelegatedPuzzleFromKey)(Buffer.from(authorizedWriterPublicSyntheticKey, "hex")));
124
- }
125
- delegationLayers.push((0, datalayer_driver_1.oracleDelegatedPuzzle)(ownerSyntheicPuzzleHash, BigInt(100000)));
126
- const rootHash = Buffer.from("0000000000000000000000000000000000000000000000000000000000000000", "hex");
127
- const mintStoreParams = [
128
- publicSyntheticKey,
129
- storeCreationCoins,
130
- rootHash,
131
- label || undefined,
132
- description || undefined,
133
- sizeInBytes || BigInt(0),
134
- ownerSyntheicPuzzleHash,
135
- delegationLayers,
136
- ];
137
- const { coinSpends: preflightCoinSpends } = await (0, datalayer_driver_1.mintStore)(
138
- // @ts-ignore
139
- ...mintStoreParams,
140
- // @ts-ignore
141
- BigInt(0));
142
- const fee = await (0, coins_1.calculateFeeForCoinSpends)(peer, preflightCoinSpends);
143
- const storeCreationResponse = await datalayer_driver_1.mintStore.apply(null, [
144
- // @ts-ignore
145
- ...mintStoreParams,
146
- // @ts-ignore
147
- fee,
148
- ]);
149
- const sig = (0, datalayer_driver_1.signCoinSpends)(storeCreationResponse.coinSpends, [await wallet.getPrivateSyntheticKey()], false);
150
- const err = await peer.broadcastSpend(storeCreationResponse.coinSpends, [sig]);
151
- if (err) {
152
- throw new Error(err);
153
- }
154
- await new Promise((resolve) => setTimeout(resolve, 5000));
155
- return storeCreationResponse.newStore;
156
- }
157
- catch (error) {
158
- console.error("Unable to mint store");
159
- throw error;
160
- }
161
- }
162
- /**
163
- * Instance method to calculate the disk space used by the store/storeId folder.
164
- * @returns {Promise<number>} - The total disk space used by the store in bytes.
165
- */
166
- async getDiskSpace() {
167
- const storePath = path_1.default.join(config_1.STORE_PATH, this.storeId);
168
- return await DataStore.calculateFolderSize(storePath);
169
- }
170
- /**
171
- * Static method to calculate the total disk space used by all stores in the store folder.
172
- * @returns {Promise<number>} - The total disk space used by the store folder in bytes.
173
- */
174
- static async getTotalDiskSpace() {
175
- return await DataStore.calculateFolderSize(config_1.STORE_PATH);
176
- }
177
- /**
178
- * Helper method to calculate the size of a folder and its subfolders recursively.
179
- * @param folderPath - The path of the folder to calculate the size of.
180
- * @returns {Promise<number>} - The total size of the folder in bytes.
181
- */
182
- static async calculateFolderSize(folderPath) {
183
- let totalSize = BigInt(0);
184
- const files = await readdir(folderPath);
185
- for (const file of files) {
186
- const filePath = path_1.default.join(folderPath, file);
187
- const fileStat = await stat(filePath);
188
- if (fileStat.isDirectory()) {
189
- totalSize += await this.calculateFolderSize(filePath); // Recursive call for subdirectories
190
- }
191
- else {
192
- totalSize += BigInt(fileStat.size); // Add file size to total
193
- }
194
- }
195
- return totalSize;
196
- }
197
- static getAllStores() {
198
- const storeFolders = fs_1.default.readdirSync(config_1.STORE_PATH);
199
- const storIds = storeFolders.filter((folder) => /^[a-f0-9]{64}$/.test(folder) &&
200
- fs_1.default.lstatSync(path_1.default.join(config_1.STORE_PATH, folder)).isDirectory());
201
- return storIds.map((storeId) => DataStore.from(storeId));
202
- }
203
- async fetchCoinInfo() {
204
- try {
205
- // Initialize the cache for the current storeId's coin info
206
- const storeCoinCache = new FileCache_1.FileCache(`stores`);
207
- // Try to get cached store info
208
- const cachedInfo = storeCoinCache.get(this.storeId);
209
- if (cachedInfo) {
210
- try {
211
- const { latestStore: serializedStore, latestHeight: previousHeight, latestHash: previousHash, } = cachedInfo;
212
- // Deserialize the stored data using DataStoreSerializer
213
- const { latestStore: previousInfo } = DataStoreSerializer_1.DataStoreSerializer.deserialize({
214
- latestStore: serializedStore,
215
- latestHeight: previousHeight.toString(),
216
- latestHash: previousHash,
217
- });
218
- // Sync with peer if necessary
219
- const peer = await FullNodePeer_1.FullNodePeer.connect();
220
- const { latestStore, latestHeight } = await peer.syncStore(previousInfo, previousHeight, Buffer.from(previousHash, "hex"), false);
221
- const latestHash = await peer.getHeaderHash(latestHeight);
222
- // Serialize the store data for caching
223
- const serializedLatestStore = new DataStoreSerializer_1.DataStoreSerializer(latestStore, latestHeight, latestHash).serialize();
224
- // Cache updated store info
225
- storeCoinCache.set(this.storeId, {
226
- latestStore: serializedLatestStore,
227
- latestHeight,
228
- latestHash: latestHash.toString("hex"),
229
- });
230
- return { latestStore, latestHeight, latestHash };
231
- }
232
- catch {
233
- // Return cached info if sync fails
234
- const { latestStore, latestHeight, latestHash } = DataStoreSerializer_1.DataStoreSerializer.deserialize({
235
- latestStore: cachedInfo.latestStore,
236
- latestHeight: cachedInfo.latestHeight.toString(),
237
- latestHash: cachedInfo.latestHash,
238
- });
239
- return {
240
- latestStore,
241
- latestHeight,
242
- latestHash: latestHash,
243
- };
244
- }
245
- }
246
- // Use getCreationHeight to retrieve height and hash information
247
- const { createdAtHeight, createdAtHash } = await this.getCreationHeight();
248
- // Sync store from peer
249
- const peer = await FullNodePeer_1.FullNodePeer.connect();
250
- const { latestStore, latestHeight } = await peer.syncStoreFromLauncherId(Buffer.from(this.storeId, "hex"), createdAtHeight, createdAtHash, false);
251
- const latestHash = await peer.getHeaderHash(latestHeight);
252
- // Serialize the latest store info for caching
253
- const serializedLatestStore = new DataStoreSerializer_1.DataStoreSerializer(latestStore, latestHeight, latestHash).serialize();
254
- // Cache the latest store info
255
- storeCoinCache.set(this.storeId, {
256
- latestStore: serializedLatestStore,
257
- latestHeight,
258
- latestHash: latestHash.toString("hex"),
259
- });
260
- return { latestStore, latestHeight, latestHash };
261
- }
262
- catch (error) {
263
- console.trace("Failed to fetch coin info", error);
264
- throw error;
265
- }
266
- }
267
- async cacheStoreCreationHeight() {
268
- const peer = await FullNodePeer_1.FullNodePeer.connect();
269
- const createdAtHeight = await peer.getStoreCreationHeight(Buffer.from(this.storeId, "hex"), null, Buffer.from(config_2.MAIN_NET_GENISES_CHALLENGE, "hex"));
270
- // Get just before created at height so we can find the coin
271
- const justBeforeCreatedAtHeight = Number(createdAtHeight) - 1;
272
- const createdAtHash = await peer.getHeaderHash(justBeforeCreatedAtHeight);
273
- await this.setCreationHeight(justBeforeCreatedAtHeight, createdAtHash);
274
- return { createdAtHeight: justBeforeCreatedAtHeight, createdAtHash };
275
- }
276
- async getCreationHeight() {
277
- // Initialize the FileCache for the height file
278
- const fileCache = new FileCache_1.FileCache(`stores/${this.storeId}`);
279
- // Try to retrieve the cached height information
280
- const cachedHeightInfo = fileCache.get("height");
281
- if (!cachedHeightInfo) {
282
- // If no cache, regenerate the cache
283
- return this.cacheStoreCreationHeight();
284
- }
285
- // Parse the cached height and hash values
286
- const { height, hash } = cachedHeightInfo;
287
- const defaultHeight = config_1.MIN_HEIGHT;
288
- const defaultHash = Buffer.from(config_1.MIN_HEIGHT_HEADER_HASH, "hex");
289
- return {
290
- createdAtHeight: height || defaultHeight,
291
- createdAtHash: hash ? Buffer.from(hash, "hex") : defaultHash,
292
- };
293
- }
294
- async setCreationHeight(height, hash) {
295
- const fileCache = new FileCache_1.FileCache(`stores/${this.storeId}`);
296
- // Cache the height and hash information
297
- fileCache.set("height", {
298
- height,
299
- hash: hash.toString("hex"),
300
- });
301
- }
302
- async getRootHistory(bustCache) {
303
- if (bustCache) {
304
- rootHistoryCache.del(this.storeId);
305
- }
306
- // Check if the root history is cached for this storeId
307
- const cachedHistory = rootHistoryCache.get(this.storeId);
308
- if (cachedHistory) {
309
- return cachedHistory;
310
- }
311
- // Fetch root history from peer if not cached
312
- const peer = await FullNodePeer_1.FullNodePeer.connect();
313
- const { createdAtHeight, createdAtHash } = await this.getCreationHeight();
314
- const { rootHashes, rootHashesTimestamps } = await peer.syncStoreFromLauncherId(Buffer.from(this.storeId, "hex"), createdAtHeight, createdAtHash, true);
315
- if (!rootHashes) {
316
- return [];
317
- }
318
- // Build the root history list
319
- const rootHistory = rootHashes.map((rootHash, index) => ({
320
- root_hash: rootHash.toString("hex"),
321
- timestamp: Number(rootHashesTimestamps?.[index].toString()),
322
- synced: fs_1.default.existsSync(path_1.default.join(config_1.STORE_PATH, this.storeId, `${rootHash.toString("hex")}.dat`)),
323
- }));
324
- // Store the root history in the cache
325
- rootHistoryCache.set(this.storeId, rootHistory);
326
- return rootHistory;
327
- }
328
- // Generates a fresh manifest file based on the current root history
329
- // and what is currently on disk
330
- async generateManifestFile(folderPath) {
331
- if (!folderPath) {
332
- folderPath = path_1.default.join(config_1.STORE_PATH, this.storeId, "data");
333
- }
334
- const rootHistory = await this.getRootHistory();
335
- // Need this for the dataintegrity tree to work properly
336
- fs_1.default.writeFileSync(path_1.default.join(folderPath, "manifest.dat"), rootHistory
337
- .filter((root) => root.synced)
338
- .map((root) => root.root_hash)
339
- .join("\n"));
340
- }
341
- async getMetaData() {
342
- const { latestStore } = await this.fetchCoinInfo();
343
- return latestStore.metadata;
344
- }
345
- async isSynced() {
346
- const dataStore = await DataStore.from(this.storeId);
347
- const rootHistory = await dataStore.getRootHistory();
348
- return !rootHistory.some((root) => !root.synced);
349
- }
350
- async hasMetaWritePermissions(publicSyntheticKey) {
351
- const wallet = await Wallet_1.Wallet.load("default");
352
- const { latestStore } = await this.fetchCoinInfo();
353
- let ownerPuzzleHash = publicSyntheticKey
354
- ? (0, datalayer_driver_1.syntheticKeyToPuzzleHash)(publicSyntheticKey)
355
- : await wallet.getOwnerPuzzleHash();
356
- const isStoreOwner = latestStore.ownerPuzzleHash.equals(ownerPuzzleHash);
357
- const hasWriteAccess = latestStore.delegatedPuzzles.some((puzzle) => puzzle.adminInnerPuzzleHash?.equals(ownerPuzzleHash) ||
358
- puzzle.writerInnerPuzzleHash?.equals(ownerPuzzleHash));
359
- return isStoreOwner || hasWriteAccess;
360
- }
361
- async updateMetadata(metadata) {
362
- const peer = await FullNodePeer_1.FullNodePeer.connect();
363
- const wallet = await Wallet_1.Wallet.load("default");
364
- const publicSyntheticKey = await wallet.getPublicSyntheticKey();
365
- const { latestStore } = await this.fetchCoinInfo();
366
- const updateStoreResponse = (0, datalayer_driver_1.updateStoreMetadata)(latestStore, metadata.rootHash, metadata.label, metadata.description, metadata.bytes, publicSyntheticKey, null, null);
367
- const fee = await (0, coins_1.calculateFeeForCoinSpends)(peer, null);
368
- const unspentCoins = await (0, coins_1.selectUnspentCoins)(peer, BigInt(0), fee);
369
- const feeCoinSpends = await (0, datalayer_driver_1.addFee)(publicSyntheticKey, unspentCoins, updateStoreResponse.coinSpends.map((coinSpend) => (0, datalayer_driver_1.getCoinId)(coinSpend.coin)), fee);
370
- const combinedCoinSpends = [
371
- ...updateStoreResponse.coinSpends,
372
- ...feeCoinSpends,
373
- ];
374
- const sig = (0, datalayer_driver_1.signCoinSpends)(combinedCoinSpends, [await wallet.getPrivateSyntheticKey()], false);
375
- const err = await peer.broadcastSpend(combinedCoinSpends, [sig]);
376
- if (err) {
377
- throw new Error(err);
378
- }
379
- return updateStoreResponse.newStore;
380
- }
381
- /**
382
- * Retrieve the file set for a given root hash and validate file integrity.
383
- *
384
- * @param {string} rootHash - The root hash to fetch the file set.
385
- * @returns {Promise<{ fileName: string, file: string }[]>} - An array of unique file objects.
386
- */
387
- async getFileSetForRootHash(rootHash) {
388
- const datFilePath = path_1.default.join(config_1.STORE_PATH, this.storeId, `${rootHash}.dat`);
389
- const datFileContent = JSON.parse(fs_1.default.readFileSync(datFilePath, "utf-8"));
390
- // Use a Set to ensure uniqueness
391
- const filesInvolved = new Set();
392
- // Iterate over each file and perform an integrity check
393
- for (const [fileKey, fileData] of Object.entries(datFileContent.files)) {
394
- const filePath = (0, hashUtils_1.getFilePathFromSha256)(datFileContent.files[fileKey].sha256, "data");
395
- // Perform the integrity check
396
- const integrityCheck = await DataIntegrityTree_1.DataIntegrityTree.validateKeyIntegrityWithForeignTree(fileKey, datFileContent.files[fileKey].sha256, datFileContent, rootHash, path_1.default.join(config_1.STORE_PATH, this.storeId, "data"));
397
- if (integrityCheck) {
398
- // Add the file to the Set
399
- filesInvolved.add({
400
- name: Buffer.from(fileKey, "hex").toString("utf-8"),
401
- path: filePath,
402
- });
403
- }
404
- else {
405
- console.error((0, colorette_1.red)(`File ${fileKey} failed the integrity check.`));
406
- throw new Error(`Integrity check failed for file: ${fileKey}. Aborting.`);
407
- }
408
- }
409
- // Convert Set to Array and return
410
- return Array.from(filesInvolved);
411
- }
412
- }
413
- exports.DataStore = DataStore;
@@ -1,52 +0,0 @@
1
- import { DataStore } from "@dignetwork/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
@@ -1 +0,0 @@
1
- {"version":3,"file":"DataStoreSerializer.d.ts","sourceRoot":"","sources":["../../src/blockchain/DataStoreSerializer.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EAKV,MAAM,8BAA8B,CAAC;AACtC,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"}
@@ -1,109 +0,0 @@
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;
@@ -1,31 +0,0 @@
1
- import { Peer } from "@dignetwork/datalayer-driver";
2
- export declare class FullNodePeer {
3
- private static cachedPeer;
4
- private static memoizedFetchNewPeerIPs;
5
- private peer;
6
- private static deprioritizedIps;
7
- private constructor();
8
- /**
9
- * Connect to the best peer, optionally using custom certificate and key file paths.
10
- * @param {string} [certFilePath] - Optional custom certificate file path.
11
- * @param {string} [keyFilePath] - Optional custom key file path.
12
- * @returns {Promise<Peer>} The connected peer.
13
- */
14
- static connect(certFilePath?: string, keyFilePath?: string): Promise<Peer>;
15
- private static isPortReachable;
16
- private static isValidIpAddress;
17
- /**
18
- * Retrieves the TRUSTED_FULLNODE IP from the environment
19
- * and verifies if it is a valid IP address.
20
- *
21
- * @returns {string | null} The valid IP address or null if invalid
22
- */
23
- private static getTrustedFullNode;
24
- private static fetchNewPeerIPs;
25
- private static getPeerIPs;
26
- private static createPeerProxy;
27
- private static getBestPeer;
28
- getPeer(): Peer;
29
- static waitForConfirmation(parentCoinInfo: Buffer): Promise<boolean>;
30
- }
31
- //# sourceMappingURL=FullNodePeer.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"FullNodePeer.d.ts","sourceRoot":"","sources":["../../src/blockchain/FullNodePeer.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,IAAI,EAAE,MAAM,8BAA8B,CAAC;AAqBpD,qBAAa,YAAY;IACvB,OAAO,CAAC,MAAM,CAAC,UAAU,CAAkD;IAC3E,OAAO,CAAC,MAAM,CAAC,uBAAuB,CAA0B;IAChE,OAAO,CAAC,IAAI,CAAO;IACnB,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAA0B;IAQzD,OAAO;IAIP;;;;;OAKG;WACiB,OAAO,CACzB,YAAY,CAAC,EAAE,MAAM,EACrB,WAAW,CAAC,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC;IAKhB,OAAO,CAAC,MAAM,CAAC,eAAe;IAiB9B,OAAO,CAAC,MAAM,CAAC,gBAAgB;IAM/B;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,kBAAkB;mBASZ,eAAe;mBA6Df,UAAU;IA2B/B,OAAO,CAAC,MAAM,CAAC,eAAe;mBAyDT,WAAW;IA+HzB,OAAO,IAAI,IAAI;WAIF,mBAAmB,CACrC,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,OAAO,CAAC;CAwBpB"}