@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,6 +0,0 @@
1
- declare class DataLayerError extends Error {
2
- code: number;
3
- constructor(code: number, message: string);
4
- }
5
- export default DataLayerError;
6
- //# sourceMappingURL=DataLayerError.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"DataLayerError.d.ts","sourceRoot":"","sources":["../../src/DataIntegrityTree/DataLayerError.ts"],"names":[],"mappings":"AAAA,cAAM,cAAe,SAAQ,KAAK;IAC9B,IAAI,EAAE,MAAM,CAAC;gBAED,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;CAe1C;AAED,eAAe,cAAc,CAAC"}
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- class DataLayerError extends Error {
4
- constructor(code, message) {
5
- // Call the parent constructor with the message
6
- super(message);
7
- // Set the name of the error to the class name
8
- this.name = this.constructor.name;
9
- // Assign the custom code
10
- this.code = code;
11
- // Capture the stack trace (if available in the environment)
12
- if (Error.captureStackTrace) {
13
- Error.captureStackTrace(this, this.constructor);
14
- }
15
- }
16
- }
17
- exports.default = DataLayerError;
@@ -1,2 +0,0 @@
1
- export * from './DataIntegrityTree';
2
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/DataIntegrityTree/index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAqB,CAAC"}
@@ -1,17 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./DataIntegrityTree"), exports);
@@ -1,33 +0,0 @@
1
- import http from "http";
2
- import { Readable } from "stream";
3
- export declare class ContentServer {
4
- private ipAddress;
5
- private storeId;
6
- private static certPath;
7
- private static keyPath;
8
- private static readonly port;
9
- constructor(ipAddress: string, storeId: string);
10
- getKey(key: string, rootHash: string, challengeHex?: string): Promise<string>;
11
- getPaymentAddress(): Promise<string | null>;
12
- getWellKnown(): Promise<any>;
13
- getKnownStores(): Promise<any>;
14
- getStoresIndex(): Promise<any>;
15
- getKeysIndex(rootHash?: string): Promise<any>;
16
- headKey(key: string, rootHash?: string): Promise<{
17
- success: boolean;
18
- headers?: http.IncomingHttpHeaders;
19
- }>;
20
- headStore(options?: {
21
- hasRootHash: string;
22
- }): Promise<{
23
- success: boolean;
24
- headers?: http.IncomingHttpHeaders;
25
- }>;
26
- hasRootHash(rootHash: string): Promise<boolean>;
27
- streamKey(key: string, rootHash?: string): Promise<Readable>;
28
- private head;
29
- private fetchJson;
30
- private fetchWithRetries;
31
- private fetch;
32
- }
33
- //# sourceMappingURL=ContentServer.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ContentServer.d.ts","sourceRoot":"","sources":["../../src/DigNetwork/ContentServer.ts"],"names":[],"mappings":"AACA,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,CAAS;IAChC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAS;IAC/B,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAQ;gBAExB,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;IAYjC,MAAM,CACjB,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,MAAM,EAChB,YAAY,CAAC,EAAE,MAAM,GACpB,OAAO,CAAC,MAAM,CAAC;IAaL,iBAAiB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAe3C,YAAY,IAAI,OAAO,CAAC,GAAG,CAAC;IAM5B,cAAc,IAAI,OAAO,CAAC,GAAG,CAAC;IAM9B,cAAc,IAAI,OAAO,CAAC,GAAG,CAAC;IAM9B,YAAY,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC;IAY7C,OAAO,CAClB,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,IAAI,CAAC,mBAAmB,CAAA;KAAE,CAAC;IAYvD,SAAS,CAAC,OAAO,CAAC,EAAE;QAAE,WAAW,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC;QACjE,OAAO,EAAE,OAAO,CAAC;QACjB,OAAO,CAAC,EAAE,IAAI,CAAC,mBAAmB,CAAC;KACpC,CAAC;IAUW,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAUrD,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;YAgDrD,IAAI;YA0EJ,SAAS;YAMT,gBAAgB;YAiChB,KAAK;CA6GpB"}
@@ -1,308 +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.ContentServer = void 0;
7
- const fs_1 = __importDefault(require("fs"));
8
- const http_1 = __importDefault(require("http"));
9
- const url_1 = require("url");
10
- const ssl_1 = require("../utils/ssl");
11
- class ContentServer {
12
- constructor(ipAddress, storeId) {
13
- this.ipAddress = ipAddress;
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
- }
20
- }
21
- // Method to get the content of a specified key from the peer, with optional challenge query
22
- async getKey(key, rootHash, challengeHex) {
23
- // Construct the base URL
24
- let url = `https://${this.ipAddress}:${ContentServer.port}/chia.${this.storeId}.${rootHash}/${key}`;
25
- // If a challenge is provided, append it as a query parameter
26
- if (challengeHex) {
27
- url += `?challenge=${challengeHex}`;
28
- }
29
- return this.fetchWithRetries(url);
30
- }
31
- // Method to get the payment address from the peer
32
- async getPaymentAddress() {
33
- console.log(`Fetching payment address from peer ${this.ipAddress}...`);
34
- try {
35
- const wellKnown = await this.getWellKnown();
36
- return wellKnown.xch_address;
37
- }
38
- catch (error) {
39
- console.error(`Failed to fetch payment address from ${this.ipAddress}: ${error.message}`);
40
- return null;
41
- }
42
- }
43
- // Method to get the .well-known information
44
- async getWellKnown() {
45
- const url = `https://${this.ipAddress}:${ContentServer.port}/.well-known`;
46
- return this.fetchJson(url);
47
- }
48
- // Method to get the list of known stores
49
- async getKnownStores() {
50
- const url = `https://${this.ipAddress}:${ContentServer.port}/.well-known/stores`;
51
- return this.fetchJson(url);
52
- }
53
- // Method to get the index of all stores
54
- async getStoresIndex() {
55
- const url = `https://${this.ipAddress}:${ContentServer.port}/`;
56
- return this.fetchJson(url);
57
- }
58
- // Method to get the index of keys in a store
59
- async getKeysIndex(rootHash) {
60
- let udi = `chia.${this.storeId}`;
61
- if (rootHash) {
62
- udi += `.${rootHash}`;
63
- }
64
- const url = `https://${this.ipAddress}:${ContentServer.port}/${udi}`;
65
- return this.fetchJson(url);
66
- }
67
- // Method to check if a specific key exists (HEAD request)
68
- async headKey(key, rootHash) {
69
- let udi = `chia.${this.storeId}`;
70
- if (rootHash) {
71
- udi += `.${rootHash}`;
72
- }
73
- const url = `https://${this.ipAddress}:${ContentServer.port}/${udi}/${key}`;
74
- return this.head(url);
75
- }
76
- // Method to check if a specific store exists (HEAD request)
77
- async headStore(options) {
78
- let url = `https://${this.ipAddress}:${ContentServer.port}/chia.${this.storeId}`;
79
- if (options?.hasRootHash) {
80
- url += `?hasRootHash=${options.hasRootHash}`;
81
- }
82
- return this.head(url);
83
- }
84
- async hasRootHash(rootHash) {
85
- const { success, headers } = await this.headStore({
86
- hasRootHash: rootHash,
87
- });
88
- if (success) {
89
- return headers?.["x-has-root-hash"] === "true";
90
- }
91
- return false;
92
- }
93
- streamKey(key, rootHash) {
94
- let udi = `chia.${this.storeId}`;
95
- if (rootHash) {
96
- udi += `.${rootHash}`;
97
- }
98
- return new Promise((resolve, reject) => {
99
- const url = `https://${this.ipAddress}:${ContentServer.port}/${udi}/${key}`;
100
- const urlObj = new url_1.URL(url);
101
- const requestOptions = {
102
- hostname: urlObj.hostname,
103
- port: urlObj.port || ContentServer.port,
104
- path: urlObj.pathname + urlObj.search,
105
- method: "GET",
106
- };
107
- const request = http_1.default.request(requestOptions, (response) => {
108
- if (response.statusCode === 200) {
109
- resolve(response); // Resolve with the readable stream
110
- }
111
- else if (response.statusCode === 301 || response.statusCode === 302) {
112
- // Handle redirects
113
- const redirectUrl = response.headers.location;
114
- if (redirectUrl) {
115
- this.streamKey(redirectUrl).then(resolve).catch(reject);
116
- }
117
- else {
118
- reject(new Error("Redirected without a location header"));
119
- }
120
- }
121
- else {
122
- reject(new Error(`Failed to retrieve data from ${url}. Status code: ${response.statusCode}`));
123
- }
124
- });
125
- request.on("error", (error) => {
126
- console.error(`GET Request error for ${url}:`, error);
127
- reject(error);
128
- });
129
- request.end();
130
- });
131
- }
132
- // Helper method to perform HEAD requests
133
- async head(url, maxRedirects = 5) {
134
- return new Promise((resolve, reject) => {
135
- try {
136
- // Parse the input URL
137
- const urlObj = new url_1.URL(url);
138
- const requestOptions = {
139
- hostname: urlObj.hostname,
140
- port: urlObj.port ||
141
- (urlObj.protocol === "http:" ? 80 : ContentServer.port),
142
- path: urlObj.pathname + urlObj.search,
143
- method: "HEAD",
144
- key: fs_1.default.readFileSync(ContentServer.keyPath),
145
- cert: fs_1.default.readFileSync(ContentServer.certPath),
146
- rejectUnauthorized: false,
147
- };
148
- const request = http_1.default.request(requestOptions, (response) => {
149
- const { statusCode, headers } = response;
150
- // If status code is 2xx, return success
151
- if (statusCode && statusCode >= 200 && statusCode < 300) {
152
- resolve({ success: true, headers });
153
- }
154
- // Handle 3xx redirection
155
- else if (statusCode &&
156
- statusCode >= 300 &&
157
- statusCode < 400 &&
158
- headers.location) {
159
- if (maxRedirects > 0) {
160
- let redirectUrl = headers.location;
161
- // Check if the redirect URL is relative
162
- if (!/^https?:\/\//i.test(redirectUrl)) {
163
- // Resolve the relative URL based on the original URL
164
- redirectUrl = new url_1.URL(redirectUrl, url).toString();
165
- console.log(`Resolved relative redirect to: ${redirectUrl}`);
166
- }
167
- else {
168
- console.log(`Redirecting to: ${redirectUrl}`);
169
- }
170
- // Recursively follow the redirection
171
- this.head(redirectUrl, maxRedirects - 1)
172
- .then(resolve)
173
- .catch(reject);
174
- }
175
- else {
176
- reject({ success: false, message: "Too many redirects" });
177
- }
178
- }
179
- else {
180
- // For other status codes, consider it a failure
181
- resolve({ success: false });
182
- }
183
- });
184
- request.on("error", (error) => {
185
- console.error(`HEAD ${url}:`, error.message);
186
- reject({ success: false });
187
- });
188
- request.end();
189
- }
190
- catch (err) {
191
- console.error(`Invalid URL: ${url}`, err);
192
- reject({ success: false, message: "Invalid URL" });
193
- }
194
- });
195
- }
196
- // Helper method to fetch JSON data from a URL
197
- async fetchJson(url) {
198
- const response = await this.fetchWithRetries(url);
199
- return JSON.parse(response);
200
- }
201
- // Helper method to fetch content with retries and redirection handling
202
- async fetchWithRetries(url) {
203
- let attempt = 0;
204
- const maxRetries = 1;
205
- const initialDelay = 2000; // 2 seconds
206
- const maxDelay = 10000; // 10 seconds
207
- const delayMultiplier = 1.5;
208
- let delay = initialDelay;
209
- while (attempt < maxRetries) {
210
- try {
211
- return await this.fetch(url);
212
- }
213
- catch (error) {
214
- if (attempt < maxRetries - 1) {
215
- console.warn(`Attempt ${attempt + 1} failed: ${error.message}. Retrying in ${delay / 1000} seconds...`);
216
- await new Promise((resolve) => setTimeout(resolve, delay));
217
- delay = Math.min(maxDelay, delay * delayMultiplier);
218
- }
219
- else {
220
- console.error(`Failed to retrieve data from ${url}. Aborting.`);
221
- throw new Error(`Failed to retrieve data: ${error.message}`);
222
- }
223
- }
224
- attempt++;
225
- }
226
- throw new Error(`Failed to retrieve data from ${url} after ${maxRetries} attempts.`);
227
- }
228
- // Core method to fetch content from a URL with a 5-second inactivity timeout
229
- async fetch(url, maxRedirects = 5) {
230
- return new Promise((resolve, reject) => {
231
- const urlObj = new url_1.URL(url);
232
- const timeoutDuration = 5000; // 5 seconds
233
- let timeout = null; // Initialize timeout
234
- const requestOptions = {
235
- hostname: urlObj.hostname,
236
- port: urlObj.port || ContentServer.port,
237
- path: urlObj.pathname + urlObj.search, // Include query params
238
- method: "GET",
239
- key: fs_1.default.readFileSync(ContentServer.keyPath),
240
- cert: fs_1.default.readFileSync(ContentServer.certPath),
241
- rejectUnauthorized: false,
242
- };
243
- const request = http_1.default.request(requestOptions, (response) => {
244
- let data = "";
245
- // Set timeout for inactivity
246
- timeout = setTimeout(() => {
247
- console.error(`Request timeout: No data received for ${timeoutDuration / 1000} seconds.`);
248
- request.destroy(); // Use destroy instead of abort
249
- reject(new Error(`Request timed out after ${timeoutDuration / 1000} seconds of inactivity`));
250
- }, timeoutDuration);
251
- const resetTimeout = () => {
252
- if (timeout) {
253
- clearTimeout(timeout);
254
- }
255
- timeout = setTimeout(() => {
256
- console.error(`Request timeout: No data received for ${timeoutDuration / 1000} seconds.`);
257
- request.destroy(); // Use destroy instead of abort
258
- reject(new Error(`Request timed out after ${timeoutDuration / 1000} seconds of inactivity`));
259
- }, timeoutDuration);
260
- };
261
- if (response.statusCode === 200) {
262
- response.on("data", (chunk) => {
263
- data += chunk;
264
- resetTimeout(); // Reset the timeout every time data is received
265
- });
266
- response.on("end", () => {
267
- if (timeout) {
268
- clearTimeout(timeout);
269
- }
270
- resolve(data);
271
- });
272
- }
273
- else if ((response.statusCode === 301 || response.statusCode === 302) &&
274
- response.headers.location) {
275
- // Handle redirects
276
- if (maxRedirects > 0) {
277
- const redirectUrl = new url_1.URL(response.headers.location, url); // Resolve relative URLs based on the original URL
278
- if (timeout) {
279
- clearTimeout(timeout);
280
- }
281
- this.fetch(redirectUrl.toString(), maxRedirects - 1)
282
- .then(resolve)
283
- .catch(reject);
284
- }
285
- else {
286
- reject(new Error("Too many redirects"));
287
- }
288
- }
289
- else {
290
- if (timeout) {
291
- clearTimeout(timeout);
292
- }
293
- reject(new Error(`Failed to retrieve data from ${url}. Status code: ${response.statusCode}`));
294
- }
295
- });
296
- request.on("error", (error) => {
297
- if (timeout) {
298
- clearTimeout(timeout);
299
- }
300
- console.error(`GET ${url}:`, error.message);
301
- reject(error);
302
- });
303
- request.end();
304
- });
305
- }
306
- }
307
- exports.ContentServer = ContentServer;
308
- ContentServer.port = 4161;
@@ -1,82 +0,0 @@
1
- export declare class DigChallenge {
2
- private readonly SEGMENT_SIZE;
3
- private readonly NUMBER_OF_SEGMENTS;
4
- private readonly HASH_ALGORITHM;
5
- private readonly fileHash;
6
- private readonly storeId;
7
- private readonly hexKey;
8
- private readonly rootHash;
9
- private filePath;
10
- private fileSize;
11
- constructor(storeId: string, hexKey: string, rootHash: string, segmentSize?: number, numberOfSegments?: number, hashAlgorithm?: string);
12
- /**
13
- * Initializes file info like file size, based on the resolved filePath.
14
- */
15
- private initFileInfo;
16
- /**
17
- * Generates a challenge by selecting random segments from the file using the instance's seed.
18
- * The response includes the seed, selected segments, key (SHA-256), storeId, and rootHash.
19
- *
20
- * @param seed A random seed for generating the challenge.
21
- * @returns An object containing the seed, segments, storeId, key (SHA-256), and rootHash.
22
- */
23
- generateChallenge(seed: string): Promise<{
24
- seed: string;
25
- segments: number[];
26
- key: string;
27
- storeId: string;
28
- rootHash: string;
29
- }>;
30
- /**
31
- * Creates a challenge response by reading the file and hashing the selected segments.
32
- *
33
- * @param challenge The challenge object containing the seed, segments, storeId, and key (SHA-256).
34
- * @returns A promise that resolves to the challenge response hash.
35
- */
36
- createChallengeResponse(challenge: {
37
- seed: string;
38
- segments: number[];
39
- }): Promise<string>;
40
- /**
41
- * Verifies that the server's response matches the client's calculated response.
42
- *
43
- * @param clientResponse The client's calculated challenge response.
44
- * @param serverResponse The server's challenge response.
45
- * @returns True if the responses match, false otherwise.
46
- */
47
- verifyChallengeResponse(clientResponse: string, serverResponse: string): boolean;
48
- /**
49
- * Serializes a challenge object into a hex string.
50
- * This converts the challenge into a format suitable for transport or storage.
51
- *
52
- * @param challenge The challenge object to serialize.
53
- * @returns A hex string representing the serialized challenge.
54
- */
55
- static serializeChallenge(challenge: {
56
- seed: string;
57
- segments: number[];
58
- key: string;
59
- storeId: string;
60
- rootHash: string;
61
- }): string;
62
- /**
63
- * Deserializes a hex string into a challenge object.
64
- * This converts the hex-encoded string back into a challenge object.
65
- *
66
- * @param hexString The hex string representing the serialized challenge.
67
- * @returns The deserialized challenge object.
68
- */
69
- static deserializeChallenge(hexString: string): {
70
- seed: string;
71
- segments: number[];
72
- key: string;
73
- storeId: string;
74
- rootHash: string;
75
- };
76
- /**
77
- * Generates a random seed using a cryptographically secure random number generator.
78
- * @returns A random seed in hexadecimal format.
79
- */
80
- static generateSeed(): string;
81
- }
82
- //# sourceMappingURL=DigChallenge.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"DigChallenge.d.ts","sourceRoot":"","sources":["../../src/DigNetwork/DigChallenge.ts"],"names":[],"mappings":"AAMA,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAS;IACtC,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAS;IAC5C,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAS;IACxC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,QAAQ,CAAa;gBAG3B,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,WAAW,SAAO,EAClB,gBAAgB,SAAK,EACrB,aAAa,SAAW;IAwB1B;;OAEG;YACW,YAAY;IAK1B;;;;;;OAMG;IACU,iBAAiB,CAC5B,IAAI,EAAE,MAAM,GACX,OAAO,CAAC;QACT,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,MAAM,EAAE,CAAC;QACnB,GAAG,EAAE,MAAM,CAAC;QACZ,OAAO,EAAE,MAAM,CAAC;QAChB,QAAQ,EAAE,MAAM,CAAC;KAClB,CAAC;IAyBF;;;;;OAKG;IACU,uBAAuB,CAAC,SAAS,EAAE;QAC9C,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,MAAM,EAAE,CAAC;KACpB,GAAG,OAAO,CAAC,MAAM,CAAC;IAiBnB;;;;;;OAMG;IACI,uBAAuB,CAC5B,cAAc,EAAE,MAAM,EACtB,cAAc,EAAE,MAAM,GACrB,OAAO;IAIV;;;;;;OAMG;WACW,kBAAkB,CAAC,SAAS,EAAE;QAC1C,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,MAAM,EAAE,CAAC;QACnB,GAAG,EAAE,MAAM,CAAC;QACZ,OAAO,EAAE,MAAM,CAAC;QAChB,QAAQ,EAAE,MAAM,CAAC;KAClB,GAAG,MAAM;IAKV;;;;;;OAMG;WACW,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG;QACrD,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,MAAM,EAAE,CAAC;QACnB,GAAG,EAAE,MAAM,CAAC;QACZ,OAAO,EAAE,MAAM,CAAC;QAChB,QAAQ,EAAE,MAAM,CAAC;KAClB;IAKD;;;OAGG;WACW,YAAY,IAAI,MAAM;CAGrC"}
@@ -1,144 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.DigChallenge = void 0;
27
- const crypto = __importStar(require("crypto"));
28
- const fs = __importStar(require("fs"));
29
- const blockchain_1 = require("../blockchain");
30
- const hashUtils_1 = require("../utils/hashUtils");
31
- const config_1 = require("../utils/config");
32
- class DigChallenge {
33
- constructor(storeId, hexKey, rootHash, segmentSize = 1024, numberOfSegments = 10, hashAlgorithm = "sha256") {
34
- this.fileSize = 0;
35
- this.storeId = storeId;
36
- this.hexKey = hexKey;
37
- this.rootHash = rootHash;
38
- this.SEGMENT_SIZE = segmentSize; // Size of each segment to hash (default 1 KB)
39
- this.NUMBER_OF_SEGMENTS = numberOfSegments; // Number of segments to select for the challenge
40
- this.HASH_ALGORITHM = hashAlgorithm; // Hash algorithm (default sha256)
41
- const dataStore = blockchain_1.DataStore.from(storeId);
42
- const sha256 = dataStore.Tree.getSHA256(hexKey, rootHash);
43
- if (!sha256) {
44
- throw new Error("Invalid hexKey or root hash");
45
- }
46
- this.fileHash = sha256;
47
- this.filePath = (0, hashUtils_1.getFilePathFromSha256)(sha256, `${config_1.DIG_FOLDER_PATH}/stores/${storeId}/data`);
48
- }
49
- /**
50
- * Initializes file info like file size, based on the resolved filePath.
51
- */
52
- async initFileInfo() {
53
- const fileStat = await fs.promises.stat(this.filePath);
54
- this.fileSize = fileStat.size;
55
- }
56
- /**
57
- * Generates a challenge by selecting random segments from the file using the instance's seed.
58
- * The response includes the seed, selected segments, key (SHA-256), storeId, and rootHash.
59
- *
60
- * @param seed A random seed for generating the challenge.
61
- * @returns An object containing the seed, segments, storeId, key (SHA-256), and rootHash.
62
- */
63
- async generateChallenge(seed) {
64
- if (!this.fileSize) {
65
- await this.initFileInfo(); // Ensure file info is available
66
- }
67
- // Use the seed to create a deterministic random value
68
- const random = crypto.createHash("sha256").update(seed).digest("hex");
69
- const randomSeed = parseInt(random, 16);
70
- const segments = [];
71
- for (let i = 0; i < this.NUMBER_OF_SEGMENTS; i++) {
72
- const segmentPosition = (randomSeed + i) % (this.fileSize - this.SEGMENT_SIZE); // Ensure valid segment position
73
- segments.push(segmentPosition);
74
- }
75
- return {
76
- seed,
77
- segments,
78
- key: this.hexKey,
79
- storeId: this.storeId,
80
- rootHash: this.rootHash,
81
- };
82
- }
83
- /**
84
- * Creates a challenge response by reading the file and hashing the selected segments.
85
- *
86
- * @param challenge The challenge object containing the seed, segments, storeId, and key (SHA-256).
87
- * @returns A promise that resolves to the challenge response hash.
88
- */
89
- async createChallengeResponse(challenge) {
90
- const fileHandle = await fs.promises.open(this.filePath, "r");
91
- const hash = crypto.createHash(this.HASH_ALGORITHM);
92
- try {
93
- for (const segmentPosition of challenge.segments) {
94
- const buffer = Buffer.alloc(this.SEGMENT_SIZE);
95
- await fileHandle.read(buffer, 0, this.SEGMENT_SIZE, segmentPosition);
96
- hash.update(buffer);
97
- }
98
- }
99
- finally {
100
- await fileHandle.close();
101
- }
102
- return hash.digest("hex");
103
- }
104
- /**
105
- * Verifies that the server's response matches the client's calculated response.
106
- *
107
- * @param clientResponse The client's calculated challenge response.
108
- * @param serverResponse The server's challenge response.
109
- * @returns True if the responses match, false otherwise.
110
- */
111
- verifyChallengeResponse(clientResponse, serverResponse) {
112
- return clientResponse === serverResponse;
113
- }
114
- /**
115
- * Serializes a challenge object into a hex string.
116
- * This converts the challenge into a format suitable for transport or storage.
117
- *
118
- * @param challenge The challenge object to serialize.
119
- * @returns A hex string representing the serialized challenge.
120
- */
121
- static serializeChallenge(challenge) {
122
- const challengeString = JSON.stringify(challenge);
123
- return Buffer.from(challengeString).toString("hex");
124
- }
125
- /**
126
- * Deserializes a hex string into a challenge object.
127
- * This converts the hex-encoded string back into a challenge object.
128
- *
129
- * @param hexString The hex string representing the serialized challenge.
130
- * @returns The deserialized challenge object.
131
- */
132
- static deserializeChallenge(hexString) {
133
- const challengeString = Buffer.from(hexString, "hex").toString();
134
- return JSON.parse(challengeString);
135
- }
136
- /**
137
- * Generates a random seed using a cryptographically secure random number generator.
138
- * @returns A random seed in hexadecimal format.
139
- */
140
- static generateSeed() {
141
- return crypto.randomBytes(32).toString("hex");
142
- }
143
- }
144
- exports.DigChallenge = DigChallenge;
@@ -1,14 +0,0 @@
1
- import { DigPeer } from "./DigPeer";
2
- export declare class DigNetwork {
3
- private dataStore;
4
- private serverCoin;
5
- private storeDir;
6
- private peerBlacklist;
7
- constructor(storeId: string);
8
- static subscribeToStore(storeId: string): Promise<void>;
9
- static findPeerWithStoreKey(storeId: string, rootHash: string, key?: string, intialBlackList?: string[]): Promise<DigPeer | null>;
10
- static unsubscribeFromStore(storeId: string): void;
11
- syncStoreFromPeers(maxRootsToProcess?: number): Promise<void>;
12
- fetchAvailablePeers(): Promise<DigPeer[]>;
13
- }
14
- //# sourceMappingURL=DigNetwork.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"DigNetwork.d.ts","sourceRoot":"","sources":["../../src/DigNetwork/DigNetwork.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AASpC,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;WAOP,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;WAQhD,oBAAoB,CACtC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,GAAG,CAAC,EAAE,MAAM,EACZ,eAAe,GAAE,MAAM,EAAO,GAC7B,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;WA2DZ,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAO5C,kBAAkB,CAAC,iBAAiB,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiG7D,mBAAmB,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;CAUvD"}