@dignetwork/dig-sdk 0.0.1-alpha.6 → 0.0.1-alpha.62

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 (56) hide show
  1. package/dist/DataIntegrityTree/DataIntegrityTree.d.ts +5 -2
  2. package/dist/DataIntegrityTree/DataIntegrityTree.d.ts.map +1 -1
  3. package/dist/DataIntegrityTree/DataIntegrityTree.js +88 -31
  4. package/dist/DigNetwork/ContentServer.d.ts +6 -1
  5. package/dist/DigNetwork/ContentServer.d.ts.map +1 -1
  6. package/dist/DigNetwork/ContentServer.js +40 -16
  7. package/dist/DigNetwork/DigNetwork.d.ts +3 -8
  8. package/dist/DigNetwork/DigNetwork.d.ts.map +1 -1
  9. package/dist/DigNetwork/DigNetwork.js +117 -171
  10. package/dist/DigNetwork/DigPeer.d.ts +9 -3
  11. package/dist/DigNetwork/DigPeer.d.ts.map +1 -1
  12. package/dist/DigNetwork/DigPeer.js +72 -114
  13. package/dist/DigNetwork/PropagationServer.d.ts +80 -34
  14. package/dist/DigNetwork/PropagationServer.d.ts.map +1 -1
  15. package/dist/DigNetwork/PropagationServer.js +387 -374
  16. package/dist/blockchain/DataStore.d.ts +12 -5
  17. package/dist/blockchain/DataStore.d.ts.map +1 -1
  18. package/dist/blockchain/DataStore.js +60 -90
  19. package/dist/blockchain/DataStoreSerializer.d.ts +1 -1
  20. package/dist/blockchain/DataStoreSerializer.d.ts.map +1 -1
  21. package/dist/blockchain/FullNodePeer.d.ts +9 -1
  22. package/dist/blockchain/FullNodePeer.d.ts.map +1 -1
  23. package/dist/blockchain/FullNodePeer.js +38 -10
  24. package/dist/blockchain/ServerCoin.d.ts +11 -3
  25. package/dist/blockchain/ServerCoin.d.ts.map +1 -1
  26. package/dist/blockchain/ServerCoin.js +45 -17
  27. package/dist/blockchain/Wallet.d.ts +2 -2
  28. package/dist/blockchain/Wallet.d.ts.map +1 -1
  29. package/dist/blockchain/Wallet.js +2 -2
  30. package/dist/blockchain/coins.d.ts +1 -1
  31. package/dist/blockchain/coins.d.ts.map +1 -1
  32. package/dist/blockchain/coins.js +1 -1
  33. package/dist/types.d.ts +1 -0
  34. package/dist/types.d.ts.map +1 -1
  35. package/dist/utils/ContentScanner.d.ts +63 -0
  36. package/dist/utils/ContentScanner.d.ts.map +1 -0
  37. package/dist/utils/ContentScanner.js +175 -0
  38. package/dist/utils/FileTransfer.d.ts +47 -0
  39. package/dist/utils/FileTransfer.d.ts.map +1 -0
  40. package/dist/utils/FileTransfer.js +209 -0
  41. package/dist/utils/StoreArchiveManager.d.ts +45 -0
  42. package/dist/utils/StoreArchiveManager.d.ts.map +1 -0
  43. package/dist/utils/StoreArchiveManager.js +153 -0
  44. package/dist/utils/config.d.ts +0 -1
  45. package/dist/utils/config.d.ts.map +1 -1
  46. package/dist/utils/config.js +5 -12
  47. package/dist/utils/directoryUtils.d.ts +0 -6
  48. package/dist/utils/directoryUtils.d.ts.map +1 -1
  49. package/dist/utils/directoryUtils.js +30 -11
  50. package/dist/utils/index.d.ts +0 -1
  51. package/dist/utils/index.d.ts.map +1 -1
  52. package/dist/utils/index.js +0 -1
  53. package/package.json +12 -3
  54. package/dist/utils/deltaUtils.d.ts +0 -2
  55. package/dist/utils/deltaUtils.d.ts.map +0 -1
  56. package/dist/utils/deltaUtils.js +0 -83
@@ -78,6 +78,9 @@ declare class DataIntegrityTree {
78
78
  * @returns The serialized Merkle tree.
79
79
  */
80
80
  serialize(rootHash?: string | null): object;
81
+ static getRootOfForeignTree(treeData: {
82
+ leaves: string[];
83
+ }): string;
81
84
  /**
82
85
  * Deserialize a JSON object to a Merkle tree.
83
86
  * @param rootHash - The root hash of the tree.
@@ -106,7 +109,7 @@ declare class DataIntegrityTree {
106
109
  * @param rootHash - The root hash of the tree. Defaults to the latest root hash.
107
110
  * @returns The readable stream for the file.
108
111
  */
109
- getValueStream(hexKey: string, rootHash?: string | null): Readable;
112
+ getValueStream(hexKey: string, rootHash?: string | null, byteOffset?: number | null, length?: number | null): Readable;
110
113
  /**
111
114
  * Delete all leaves from the Merkle tree.
112
115
  */
@@ -154,7 +157,7 @@ declare class DataIntegrityTree {
154
157
  * @param expectedRootHash - The expected root hash of the Merkle tree.
155
158
  * @returns A boolean indicating if the SHA-256 is present in the foreign tree and the root hash matches.
156
159
  */
157
- static validateKeyIntegrityWithForeignTree(key: string, sha256: string, serializedTree: object, expectedRootHash: string): boolean;
160
+ static validateKeyIntegrityWithForeignTree(hexkey: string, sha256: string, serializedTree: object, expectedRootHash: string, dataDir: string): Promise<boolean>;
158
161
  }
159
162
  export { DataIntegrityTree };
160
163
  //# sourceMappingURL=DataIntegrityTree.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"DataIntegrityTree.d.ts","sourceRoot":"","sources":["../../src/DataIntegrityTree/DataIntegrityTree.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAuClC,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAClC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAGlB,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED;;GAEG;AACH,cAAM,iBAAiB;IACrB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,OAAO,CAAS;IACjB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC5D,OAAO,CAAC,IAAI,CAAa;gBAEb,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,wBAA6B;WAiDrD,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE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,GAAE,MAAM,GAAG,IAAW,EAC9B,UAAU,GAAE,MAAM,GAAG,IAAW,EAChC,MAAM,GAAE,MAAM,GAAG,IAAW,GAC3B,QAAQ;IA4DX;;OAEG;IACH,eAAe,IAAI,IAAI;IAKvB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAUhE;;;;;;OAMG;IACH,QAAQ,CACN,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,QAAQ,GAAE,MAAM,GAAG,IAAW,GAC7B,MAAM;IAsCT;;;;;OAKG;IACH,WAAW,CAAC,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO;IA4B5D;;;;;OAKG;IACH,WAAW,CACT,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,GAChB;QAAE,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAAC,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE;IA+B/D;;;;;OAKG;IACG,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAyD5E;;;;;;;;;OASG;WACU,mCAAmC,CAC9C,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,EACtB,gBAAgB,EAAE,MAAM,EACxB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,OAAO,CAAC;CAwFpB;AAED,OAAO,EAAE,iBAAiB,EAAE,CAAC"}
@@ -111,7 +111,10 @@ class DataIntegrityTree {
111
111
  }
112
112
  }
113
113
  static from(storeId, options) {
114
- return new DataIntegrityTree(storeId, { ...options, disableInitialize: true });
114
+ return new DataIntegrityTree(storeId, {
115
+ ...options,
116
+ disableInitialize: true,
117
+ });
115
118
  }
116
119
  /**
117
120
  * Load the manifest file.
@@ -220,14 +223,19 @@ class DataIntegrityTree {
220
223
  hash: combinedHash,
221
224
  sha256: sha256,
222
225
  });
226
+ await new Promise((resolve) => setTimeout(resolve, 100));
223
227
  this._rebuildTree();
228
+ await new Promise((resolve) => setTimeout(resolve, 100));
224
229
  resolve();
225
230
  }
226
231
  catch (err) {
227
232
  reject(err);
228
233
  }
234
+ tempWriteStream.end();
235
+ finalWriteStream.end();
229
236
  });
230
237
  tempWriteStream.on("error", (err) => {
238
+ tempWriteStream.end();
231
239
  reject(err);
232
240
  });
233
241
  readStream.on("error", (err) => {
@@ -305,6 +313,11 @@ class DataIntegrityTree {
305
313
  files: Object.fromEntries(this.files),
306
314
  };
307
315
  }
316
+ static getRootOfForeignTree(treeData) {
317
+ const leaves = treeData.leaves.map((leaf) => Buffer.from(leaf, "hex"));
318
+ const tree = new merkletreejs_1.MerkleTree(leaves, crypto_js_1.SHA256, { sortPairs: true });
319
+ return tree.getRoot().toString("hex");
320
+ }
308
321
  /**
309
322
  * Deserialize a JSON object to a Merkle tree.
310
323
  * @param rootHash - The root hash of the tree.
@@ -337,7 +350,9 @@ class DataIntegrityTree {
337
350
  ? fs.readFileSync(manifestPath, "utf-8").trim().split("\n")
338
351
  : [];
339
352
  // Check if the last entry is the same as the rootHash to avoid duplicates
340
- const latestRootHash = manifestContent.length > 0 ? manifestContent[manifestContent.length - 1] : null;
353
+ const latestRootHash = manifestContent.length > 0
354
+ ? manifestContent[manifestContent.length - 1]
355
+ : null;
341
356
  if (latestRootHash !== rootHash) {
342
357
  // Append the new rootHash if it is not the same as the last one
343
358
  fs.appendFileSync(manifestPath, `${rootHash}\n`);
@@ -413,7 +428,7 @@ class DataIntegrityTree {
413
428
  * @param rootHash - The root hash of the tree. Defaults to the latest root hash.
414
429
  * @returns The readable stream for the file.
415
430
  */
416
- getValueStream(hexKey, rootHash = null) {
431
+ getValueStream(hexKey, rootHash = null, byteOffset = null, length = null) {
417
432
  if (!isHexString(hexKey)) {
418
433
  throw new Error("key must be a valid hex string");
419
434
  }
@@ -436,8 +451,22 @@ class DataIntegrityTree {
436
451
  if (!fs.existsSync(filePath)) {
437
452
  throw new Error(`File at path ${filePath} does not exist`);
438
453
  }
439
- // Create a read stream and pipe it through a decompression stream using the same algorithm (gzip)
440
- const readStream = fs.createReadStream(filePath);
454
+ const fileSize = fs.statSync(filePath).size;
455
+ // Validate offset and length
456
+ if (byteOffset !== null && length !== null) {
457
+ if (byteOffset + length > fileSize) {
458
+ throw new Error(`Offset (${byteOffset}) and length (${length}) exceed the file size (${fileSize}).`);
459
+ }
460
+ }
461
+ // Create the read stream with optional byte range
462
+ const options = {};
463
+ if (byteOffset !== null) {
464
+ options.start = byteOffset;
465
+ }
466
+ if (length !== null && byteOffset !== null) {
467
+ options.end = byteOffset + length - 1; // `end` is inclusive, hence `byteOffset + length - 1`
468
+ }
469
+ const readStream = fs.createReadStream(filePath, options);
441
470
  const decompressStream = zlib.createGunzip();
442
471
  // Return the combined stream as a generic Readable stream
443
472
  return readStream.pipe(decompressStream);
@@ -579,14 +608,13 @@ class DataIntegrityTree {
579
608
  decompressStream.on("end", () => {
580
609
  const uncompressedSha256 = hash.digest("hex");
581
610
  const isValid = uncompressedSha256 === sha256;
582
- console.log(`SHA-256 of uncompressed file: ${uncompressedSha256}`);
583
611
  if (!isValid) {
584
612
  return resolve(false);
585
613
  }
586
614
  const tree = this.deserializeTree(rootHash);
587
615
  const combinedHash = crypto
588
616
  .createHash("sha256")
589
- .update(`${toHex(sha256)}/${sha256}`)
617
+ .update(sha256)
590
618
  .digest("hex");
591
619
  const leaf = Buffer.from(combinedHash, "hex");
592
620
  const isInTree = tree.getLeafIndex(leaf) !== -1;
@@ -610,8 +638,8 @@ class DataIntegrityTree {
610
638
  * @param expectedRootHash - The expected root hash of the Merkle tree.
611
639
  * @returns A boolean indicating if the SHA-256 is present in the foreign tree and the root hash matches.
612
640
  */
613
- static validateKeyIntegrityWithForeignTree(key, sha256, serializedTree, expectedRootHash) {
614
- if (!isHexString(key)) {
641
+ static async validateKeyIntegrityWithForeignTree(hexkey, sha256, serializedTree, expectedRootHash, dataDir) {
642
+ if (!isHexString(hexkey)) {
615
643
  throw new Error("key must be a valid hex string");
616
644
  }
617
645
  if (!isHexString(sha256)) {
@@ -620,29 +648,58 @@ class DataIntegrityTree {
620
648
  if (!isHexString(expectedRootHash)) {
621
649
  throw new Error("expectedRootHash must be a valid hex string");
622
650
  }
623
- // Deserialize the foreign tree
624
- const leaves = serializedTree.leaves.map((leaf) => Buffer.from(leaf, "hex"));
625
- const tree = new merkletreejs_1.MerkleTree(leaves, crypto_js_1.SHA256, { sortPairs: true });
626
- // Verify that the deserialized tree's root matches the expected root hash
627
- const treeRootHash = tree.getRoot().toString("hex");
628
- if (treeRootHash !== expectedRootHash) {
629
- console.warn(`Expected root hash ${expectedRootHash}, but got ${treeRootHash}`);
630
- return false;
651
+ // File path based on sha256
652
+ const filePath = path.join(dataDir, sha256.match(/.{1,2}/g).join("/"));
653
+ // Check if the file exists
654
+ if (!fs.existsSync(filePath)) {
655
+ throw new Error(`File at path ${filePath} does not exist`);
631
656
  }
632
- // Rebuild the files map from the serialized tree
633
- // @ts-ignore
634
- tree.files = new Map(Object.entries(serializedTree.files).map(([key, value]) => [
635
- key,
636
- { hash: value.hash, sha256: value.sha256 },
637
- ]));
638
- // Check if the SHA-256 exists in the foreign tree's files
639
- const combinedHash = crypto
640
- .createHash("sha256")
641
- .update(`${toHex(key)}/${sha256}`)
642
- .digest("hex");
643
- const leaf = Buffer.from(combinedHash, "hex");
644
- const isInTree = tree.getLeafIndex(leaf) !== -1;
645
- return isInTree;
657
+ const compressedReadStream = fs.createReadStream(filePath);
658
+ const decompressStream = zlib.createGunzip();
659
+ const hash = crypto.createHash("sha256");
660
+ // Process file decompression and hash comparison
661
+ return new Promise((resolve, reject) => {
662
+ compressedReadStream.pipe(decompressStream);
663
+ decompressStream.on("data", (chunk) => {
664
+ hash.update(chunk);
665
+ });
666
+ decompressStream.on("end", () => {
667
+ const uncompressedSha256 = hash.digest("hex");
668
+ if (uncompressedSha256 !== sha256) {
669
+ console.warn(`File hash mismatch. Expected: ${sha256}, got: ${uncompressedSha256}`);
670
+ return resolve(false);
671
+ }
672
+ // Deserialize the foreign tree
673
+ const leaves = serializedTree.leaves.map((leaf) => Buffer.from(leaf, "hex"));
674
+ const tree = new merkletreejs_1.MerkleTree(leaves, crypto_js_1.SHA256, { sortPairs: true });
675
+ // Verify that the deserialized tree's root matches the expected root hash
676
+ const treeRootHash = tree.getRoot().toString("hex");
677
+ if (treeRootHash !== expectedRootHash) {
678
+ console.warn(`Expected root hash ${expectedRootHash}, but got ${treeRootHash}`);
679
+ return resolve(false);
680
+ }
681
+ // Rebuild the files map from the serialized tree
682
+ // @ts-ignore
683
+ tree.files = new Map(Object.entries(serializedTree.files).map(([key, value]) => [
684
+ key,
685
+ { hash: value.hash, sha256: value.sha256 },
686
+ ]));
687
+ // Check if the SHA-256 exists in the foreign tree's files
688
+ const combinedHash = crypto
689
+ .createHash("sha256")
690
+ .update(`${hexkey}/${sha256}`)
691
+ .digest("hex");
692
+ const leaf = Buffer.from(combinedHash, "hex");
693
+ const isInTree = tree.getLeafIndex(leaf) !== -1;
694
+ resolve(isInTree);
695
+ });
696
+ decompressStream.on("error", (err) => {
697
+ reject(err);
698
+ });
699
+ compressedReadStream.on("error", (err) => {
700
+ reject(err);
701
+ });
702
+ });
646
703
  }
647
704
  }
648
705
  exports.DataIntegrityTree = DataIntegrityTree;
@@ -3,6 +3,8 @@ import { Readable } from "stream";
3
3
  export declare class ContentServer {
4
4
  private ipAddress;
5
5
  private storeId;
6
+ private static certPath;
7
+ private static keyPath;
6
8
  private static readonly port;
7
9
  constructor(ipAddress: string, storeId: string);
8
10
  getKey(key: string, rootHash: string, challengeHex?: string): Promise<string>;
@@ -15,10 +17,13 @@ export declare class ContentServer {
15
17
  success: boolean;
16
18
  headers?: http.IncomingHttpHeaders;
17
19
  }>;
18
- headStore(): Promise<{
20
+ headStore(options?: {
21
+ hasRootHash: string;
22
+ }): Promise<{
19
23
  success: boolean;
20
24
  headers?: http.IncomingHttpHeaders;
21
25
  }>;
26
+ hasRootHash(rootHash: string): Promise<boolean>;
22
27
  streamKey(key: string): Promise<Readable>;
23
28
  private head;
24
29
  private fetchJson;
@@ -1 +1 @@
1
- {"version":3,"file":"ContentServer.d.ts","sourceRoot":"","sources":["../../src/DigNetwork/ContentServer.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAGlC,qBAAa,aAAa;IACxB,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAM;gBAEtB,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;IAMjC,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAa7E,iBAAiB,IAAI,OAAO,CAAC,MAAM,CAAC;IAepC,YAAY,IAAI,OAAO,CAAC,GAAG,CAAC;IAM5B,cAAc,IAAI,OAAO,CAAC,GAAG,CAAC;IAM9B,cAAc,IAAI,OAAO,CAAC,GAAG,CAAC;IAM9B,YAAY,IAAI,OAAO,CAAC,GAAG,CAAC;IAM5B,OAAO,CAClB,GAAG,EAAE,MAAM,GACV,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,IAAI,CAAC,mBAAmB,CAAA;KAAE,CAAC;IAMvD,SAAS,IAAI,OAAO,CAAC;QAChC,OAAO,EAAE,OAAO,CAAC;QACjB,OAAO,CAAC,EAAE,IAAI,CAAC,mBAAmB,CAAC;KACpC,CAAC;IAMK,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;YA0ClC,IAAI;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;IAUrD,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;YA0ClC,IAAI;YA0EJ,SAAS;YAMT,gBAAgB;YAiChB,KAAK;CA0DpB"}
@@ -4,17 +4,24 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ContentServer = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
7
8
  const http_1 = __importDefault(require("http"));
8
9
  const url_1 = require("url");
10
+ const ssl_1 = require("../utils/ssl");
9
11
  class ContentServer {
10
12
  constructor(ipAddress, storeId) {
11
13
  this.ipAddress = ipAddress;
12
14
  this.storeId = storeId;
15
+ if (!ContentServer.certPath || !ContentServer.keyPath) {
16
+ const { certPath, keyPath } = (0, ssl_1.getOrCreateSSLCerts)();
17
+ ContentServer.certPath = certPath;
18
+ ContentServer.keyPath = keyPath;
19
+ }
13
20
  }
14
21
  // Method to get the content of a specified key from the peer, with optional challenge query
15
22
  async getKey(key, rootHash, challengeHex) {
16
23
  // Construct the base URL
17
- let url = `http://${this.ipAddress}/chia.${this.storeId}.${rootHash}/${key}`;
24
+ let url = `https://${this.ipAddress}:${ContentServer.port}/chia.${this.storeId}.${rootHash}/${key}`;
18
25
  // If a challenge is provided, append it as a query parameter
19
26
  if (challengeHex) {
20
27
  url += `?challenge=${challengeHex}`;
@@ -35,38 +42,49 @@ class ContentServer {
35
42
  }
36
43
  // Method to get the .well-known information
37
44
  async getWellKnown() {
38
- const url = `http://${this.ipAddress}/.well-known`;
45
+ const url = `https://${this.ipAddress}:${ContentServer.port}/.well-known`;
39
46
  return this.fetchJson(url);
40
47
  }
41
48
  // Method to get the list of known stores
42
49
  async getKnownStores() {
43
- const url = `http://${this.ipAddress}/.well-known/stores`;
50
+ const url = `https://${this.ipAddress}:${ContentServer.port}/.well-known/stores`;
44
51
  return this.fetchJson(url);
45
52
  }
46
53
  // Method to get the index of all stores
47
54
  async getStoresIndex() {
48
- const url = `http://${this.ipAddress}/`;
55
+ const url = `https://${this.ipAddress}:${ContentServer.port}/`;
49
56
  return this.fetchJson(url);
50
57
  }
51
58
  // Method to get the index of keys in a store
52
59
  async getKeysIndex() {
53
- const url = `http://${this.ipAddress}/${this.storeId}`;
60
+ const url = `https://${this.ipAddress}:${ContentServer.port}/${this.storeId}`;
54
61
  return this.fetchJson(url);
55
62
  }
56
63
  // Method to check if a specific key exists (HEAD request)
57
64
  async headKey(key) {
58
- const url = `http://${this.ipAddress}/${this.storeId}/${key}`;
59
- return this.head(url); // Return the object from head method
65
+ const url = `https://${this.ipAddress}:${ContentServer.port}/${this.storeId}/${key}`;
66
+ return this.head(url);
60
67
  }
61
68
  // Method to check if a specific store exists (HEAD request)
62
- async headStore() {
63
- const url = `http://${this.ipAddress}/${this.storeId}`;
64
- console.log({ url });
65
- return this.head(url); // Return the object from head method
69
+ async headStore(options) {
70
+ let url = `https://${this.ipAddress}:${ContentServer.port}/${this.storeId}`;
71
+ if (options?.hasRootHash) {
72
+ url += `?hasRootHash=${options.hasRootHash}`;
73
+ }
74
+ return this.head(url);
75
+ }
76
+ async hasRootHash(rootHash) {
77
+ const { success, headers } = await this.headStore({
78
+ hasRootHash: rootHash,
79
+ });
80
+ if (success) {
81
+ return headers?.["x-has-root-hash"] === "true";
82
+ }
83
+ return false;
66
84
  }
67
85
  streamKey(key) {
68
86
  return new Promise((resolve, reject) => {
69
- const url = `http://${this.ipAddress}/${this.storeId}/${key}`;
87
+ const url = `https://${this.ipAddress}:${ContentServer.port}/${this.storeId}/${key}`;
70
88
  const urlObj = new url_1.URL(url);
71
89
  const requestOptions = {
72
90
  hostname: urlObj.hostname,
@@ -93,7 +111,7 @@ class ContentServer {
93
111
  }
94
112
  });
95
113
  request.on("error", (error) => {
96
- console.error(`Request error for ${url}:`, error);
114
+ console.error(`GET Request error for ${url}:`, error);
97
115
  reject(error);
98
116
  });
99
117
  request.end();
@@ -111,6 +129,9 @@ class ContentServer {
111
129
  (urlObj.protocol === "http:" ? 80 : ContentServer.port),
112
130
  path: urlObj.pathname + urlObj.search,
113
131
  method: "HEAD",
132
+ key: fs_1.default.readFileSync(ContentServer.keyPath),
133
+ cert: fs_1.default.readFileSync(ContentServer.certPath),
134
+ rejectUnauthorized: false,
114
135
  };
115
136
  const request = http_1.default.request(requestOptions, (response) => {
116
137
  const { statusCode, headers } = response;
@@ -149,7 +170,7 @@ class ContentServer {
149
170
  }
150
171
  });
151
172
  request.on("error", (error) => {
152
- console.error(`Request error for ${url}:`, error);
173
+ console.error(`HEAD ${url}:`, error.message);
153
174
  reject({ success: false });
154
175
  });
155
176
  request.end();
@@ -201,6 +222,9 @@ class ContentServer {
201
222
  port: urlObj.port || ContentServer.port,
202
223
  path: urlObj.pathname + urlObj.search, // Include query params
203
224
  method: "GET",
225
+ key: fs_1.default.readFileSync(ContentServer.keyPath),
226
+ cert: fs_1.default.readFileSync(ContentServer.certPath),
227
+ rejectUnauthorized: false,
204
228
  };
205
229
  const request = http_1.default.request(requestOptions, (response) => {
206
230
  let data = "";
@@ -232,7 +256,7 @@ class ContentServer {
232
256
  }
233
257
  });
234
258
  request.on("error", (error) => {
235
- console.error(`Request error for ${url}:`, error);
259
+ console.error(`GET ${url}:`, error.message);
236
260
  reject(error);
237
261
  });
238
262
  request.end();
@@ -240,4 +264,4 @@ class ContentServer {
240
264
  }
241
265
  }
242
266
  exports.ContentServer = ContentServer;
243
- ContentServer.port = 80;
267
+ ContentServer.port = 4161;
@@ -5,16 +5,11 @@ export declare class DigNetwork {
5
5
  private storeDir;
6
6
  private peerBlacklist;
7
7
  constructor(storeId: string);
8
- private uploadPreflight;
9
- uploadStoreHead(digPeer: DigPeer): Promise<void>;
10
- uploadStore(digPeer: DigPeer): Promise<void>;
11
8
  static subscribeToStore(storeId: string): Promise<void>;
9
+ static findPeerWithStoreKey(storeId: string, rootHash: string, key?: string, intialBlackList?: string[]): Promise<DigPeer | null>;
12
10
  static unsubscribeFromStore(storeId: string): void;
13
- downloadFiles(forceDownload?: boolean, renderProgressBar?: boolean, skipData?: boolean): Promise<void>;
11
+ syncStoreFromPeers(): Promise<void>;
14
12
  private fetchAvailablePeers;
15
- private downloadHeightFile;
16
- private downloadManifestFile;
17
- private downloadFileFromPeers;
18
- private runProgressBar;
13
+ downloadFileFromPeers(dataPath: string, filePath: string, overwrite: boolean): Promise<void>;
19
14
  }
20
15
  //# sourceMappingURL=DigNetwork.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"DigNetwork.d.ts","sourceRoot":"","sources":["../../src/DigNetwork/DigNetwork.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAMpC,qBAAa,UAAU;IACrB,OAAO,CAAC,SAAS,CAAY;IAC7B,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,aAAa,CAA2B;gBAEpC,OAAO,EAAE,MAAM;YAOb,eAAe;IA8ChB,eAAe,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAsDhD,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;WA6BrC,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;WAQtD,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAQ5C,aAAa,CACxB,aAAa,GAAE,OAAe,EAC9B,iBAAiB,GAAE,OAAc,EACjC,QAAQ,GAAE,OAAe,GACxB,OAAO,CAAC,IAAI,CAAC;YAqFF,mBAAmB;YAWnB,kBAAkB;YASlB,oBAAoB;YASpB,qBAAqB;YAuErB,cAAc;CAoB7B"}
1
+ {"version":3,"file":"DigNetwork.d.ts","sourceRoot":"","sources":["../../src/DigNetwork/DigNetwork.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAWpC,qBAAa,UAAU;I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