@dignetwork/dig-sdk 0.0.1-alpha.10 → 0.0.1-alpha.101

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 (68) 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 +93 -34
  4. package/dist/DigNetwork/ContentServer.d.ts +10 -5
  5. package/dist/DigNetwork/ContentServer.d.ts.map +1 -1
  6. package/dist/DigNetwork/ContentServer.js +89 -24
  7. package/dist/DigNetwork/DigNetwork.d.ts +3 -9
  8. package/dist/DigNetwork/DigNetwork.d.ts.map +1 -1
  9. package/dist/DigNetwork/DigNetwork.js +98 -189
  10. package/dist/DigNetwork/DigPeer.d.ts +8 -3
  11. package/dist/DigNetwork/DigPeer.d.ts.map +1 -1
  12. package/dist/DigNetwork/DigPeer.js +68 -114
  13. package/dist/DigNetwork/PropagationServer.d.ts +73 -33
  14. package/dist/DigNetwork/PropagationServer.d.ts.map +1 -1
  15. package/dist/DigNetwork/PropagationServer.js +508 -360
  16. package/dist/blockchain/DataStore.d.ts +18 -7
  17. package/dist/blockchain/DataStore.d.ts.map +1 -1
  18. package/dist/blockchain/DataStore.js +78 -98
  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 +2 -1
  22. package/dist/blockchain/FullNodePeer.d.ts.map +1 -1
  23. package/dist/blockchain/FullNodePeer.js +34 -11
  24. package/dist/blockchain/ServerCoin.d.ts +13 -5
  25. package/dist/blockchain/ServerCoin.d.ts.map +1 -1
  26. package/dist/blockchain/ServerCoin.js +88 -25
  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 +51 -18
  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 +5 -4
  33. package/dist/types.d.ts +2 -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/Environment.d.ts +18 -0
  39. package/dist/utils/Environment.d.ts.map +1 -0
  40. package/dist/utils/Environment.js +85 -0
  41. package/dist/utils/FileTransfer.d.ts +47 -0
  42. package/dist/utils/FileTransfer.d.ts.map +1 -0
  43. package/dist/utils/FileTransfer.js +209 -0
  44. package/dist/utils/NconfManager.js +2 -1
  45. package/dist/utils/StoreArchiveManager.d.ts +45 -0
  46. package/dist/utils/StoreArchiveManager.d.ts.map +1 -0
  47. package/dist/utils/StoreArchiveManager.js +153 -0
  48. package/dist/utils/asyncPool.d.ts +9 -0
  49. package/dist/utils/asyncPool.d.ts.map +1 -0
  50. package/dist/utils/asyncPool.js +23 -0
  51. package/dist/utils/config.d.ts +4 -3
  52. package/dist/utils/config.d.ts.map +1 -1
  53. package/dist/utils/config.js +12 -7
  54. package/dist/utils/directoryUtils.d.ts +0 -6
  55. package/dist/utils/directoryUtils.d.ts.map +1 -1
  56. package/dist/utils/directoryUtils.js +30 -11
  57. package/dist/utils/index.d.ts +1 -1
  58. package/dist/utils/index.d.ts.map +1 -1
  59. package/dist/utils/index.js +1 -1
  60. package/dist/utils/merkle.d.ts +2 -0
  61. package/dist/utils/merkle.d.ts.map +1 -0
  62. package/dist/utils/merkle.js +28 -0
  63. package/dist/utils/network.d.ts.map +1 -1
  64. package/dist/utils/network.js +26 -10
  65. package/package.json +13 -3
  66. package/dist/utils/deltaUtils.d.ts +0 -2
  67. package/dist/utils/deltaUtils.d.ts.map +0 -1
  68. package/dist/utils/deltaUtils.js +0 -83
@@ -4,412 +4,560 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.PropagationServer = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const cli_progress_1 = __importDefault(require("cli-progress"));
9
+ const form_data_1 = __importDefault(require("form-data"));
7
10
  const fs_1 = __importDefault(require("fs"));
11
+ const fs_extra_1 = __importDefault(require("fs-extra"));
8
12
  const https_1 = __importDefault(require("https"));
9
- const url_1 = require("url");
13
+ const os_1 = __importDefault(require("os"));
14
+ const path_1 = __importDefault(require("path"));
15
+ const progress_stream_1 = __importDefault(require("progress-stream"));
16
+ const asyncPool_1 = require("../utils/asyncPool");
17
+ const nanospinner_1 = require("nanospinner");
18
+ const hashUtils_1 = require("../utils/hashUtils");
10
19
  const ssl_1 = require("../utils/ssl");
20
+ const colorette_1 = require("colorette");
21
+ const merkle_1 = require("../utils/merkle");
22
+ const stream_1 = require("stream");
11
23
  const credentialsUtils_1 = require("../utils/credentialsUtils");
12
- const spinnerUtils_1 = require("../utils/spinnerUtils");
24
+ const config_1 = require("../utils/config");
13
25
  const blockchain_1 = require("../blockchain");
26
+ // Helper function to trim long filenames with ellipsis and ensure consistent padding
27
+ function formatFilename(filename, maxLength = 30) {
28
+ if (!filename) {
29
+ return "Unknown File".padEnd(maxLength, " ");
30
+ }
31
+ if (filename.length > maxLength) {
32
+ return `...${filename.slice(-(maxLength - 3))}`.padEnd(maxLength, " ");
33
+ }
34
+ return filename.padEnd(maxLength, " ");
35
+ }
14
36
  class PropagationServer {
15
37
  constructor(ipAddress, storeId) {
16
- this.ipAddress = ipAddress;
17
38
  this.storeId = storeId;
18
- if (!PropagationServer.certPath || !PropagationServer.keyPath) {
19
- const { certPath, keyPath } = (0, ssl_1.getOrCreateSSLCerts)();
20
- PropagationServer.certPath = certPath;
21
- PropagationServer.keyPath = keyPath;
22
- }
23
- }
24
- // Method to upload a file to the propagation server
25
- async pushFile(filePath, relativePath) {
26
- const { nonce, username, password } = await this.getUploadDetails();
27
- const wallet = await blockchain_1.Wallet.load("default");
28
- const keyOwnershipSig = await wallet.createKeyOwnershipSignature(nonce);
29
- const publicKey = await wallet.getPublicSyntheticKey();
30
- const uploadUrl = `https://${this.ipAddress}:${PropagationServer.port}/${this.storeId}/${relativePath}`;
31
- await this.retryOperation(() => this.uploadFileDirect(filePath, uploadUrl, username, password, keyOwnershipSig, publicKey.toString("hex"), nonce), `Upload failed for ${relativePath}`);
32
- }
33
- // Method to subscribe to a store on the propagation server
34
- async subscribeToStore() {
35
- const url = `https://${this.ipAddress}:${PropagationServer.port}/subscribe`;
36
- const data = JSON.stringify({ storeId: this.storeId });
37
- await this.postRequest(url, data);
38
- }
39
- // Method to unsubscribe from a store on the propagation server
40
- async unsubscribeFromStore() {
41
- const url = `https://${this.ipAddress}:${PropagationServer.port}/unsubscribe`;
42
- const data = JSON.stringify({ storeId: this.storeId });
43
- await this.postRequest(url, data);
44
- }
45
- // Method to check the status of a store on the propagation server
46
- async getStoreStatus() {
47
- const url = `https://${this.ipAddress}:${PropagationServer.port}/status/${this.storeId}`;
48
- return this.fetchJson(url);
49
- }
50
- async streamStoreData(dataPath) {
51
- const url = `https://${this.ipAddress}:${PropagationServer.port}/${this.storeId}/${dataPath}`;
52
- return this.createReadStreamWithRetries(url);
53
- }
54
- // Method to retrieve a store's key
55
- async getStoreData(dataPath) {
56
- const url = `https://${this.ipAddress}:${PropagationServer.port}/${this.storeId}/${dataPath}`;
57
- return this.fetch(url);
39
+ this.sessionId = "";
40
+ this.publicKey = "";
41
+ this.ipAddress = ipAddress;
42
+ // Get or create SSL certificates
43
+ const { certPath, keyPath } = (0, ssl_1.getOrCreateSSLCerts)();
44
+ this.certPath = certPath;
45
+ this.keyPath = keyPath;
58
46
  }
59
- async getStatus() {
60
- const url = `https://${this.ipAddress}:${PropagationServer.port}/status/${this.storeId}`;
61
- const statusJson = await this.fetch(url);
62
- return JSON.parse(statusJson);
47
+ /**
48
+ * Initialize the Wallet instance.
49
+ */
50
+ async initializeWallet() {
51
+ this.wallet = await blockchain_1.Wallet.load("default");
52
+ this.publicKey = (await this.wallet.getPublicSyntheticKey()).toString("hex");
63
53
  }
64
- // Method to check if a specific store exists (HEAD request)
65
- async headStore() {
66
- const url = `https://${this.ipAddress}:${PropagationServer.port}/${this.storeId}`;
67
- return this.head(url);
54
+ /**
55
+ * Create an Axios HTTPS Agent with self-signed certificate allowance.
56
+ */
57
+ createHttpsAgent() {
58
+ return new https_1.default.Agent({
59
+ cert: fs_1.default.readFileSync(this.certPath),
60
+ key: fs_1.default.readFileSync(this.keyPath),
61
+ rejectUnauthorized: false,
62
+ });
68
63
  }
69
- // In PropagationServer.ts:
70
- async isStoreSynced() {
71
- const status = await this.getStatus();
72
- return status.synced === true;
64
+ /**
65
+ * Adds a custom inactivity timeout for large file transfers.
66
+ */
67
+ addInactivityTimeout(stream, timeoutMs) {
68
+ let timeoutId;
69
+ const resetTimeout = () => {
70
+ clearTimeout(timeoutId);
71
+ timeoutId = setTimeout(() => {
72
+ stream.destroy(new Error(`Inactivity timeout after ${timeoutMs / 1000} seconds`));
73
+ }, timeoutMs);
74
+ };
75
+ // Reset timeout every time data is received
76
+ stream.on("data", resetTimeout);
77
+ // Set the initial timeout
78
+ resetTimeout();
79
+ // Clear the timeout when the stream ends
80
+ stream.on("end", () => clearTimeout(timeoutId));
81
+ stream.on("error", () => clearTimeout(timeoutId)); // Handle errors
82
+ return stream;
73
83
  }
74
- // Method to handle upload details including nonce
75
- async getUploadDetails() {
76
- let username;
77
- let password;
78
- if (!username || !password) {
79
- const credentials = await (0, credentialsUtils_1.promptCredentials)(this.ipAddress);
80
- username = credentials.username;
81
- password = credentials.password;
84
+ /**
85
+ * Check if the store and optional root hash exist by making a HEAD request.
86
+ */
87
+ async checkStoreExists(rootHash) {
88
+ const spinner = (0, nanospinner_1.createSpinner)(`Checking if store ${this.storeId} exists...`).start();
89
+ try {
90
+ const config = {
91
+ httpsAgent: this.createHttpsAgent(),
92
+ };
93
+ let url = `https://${this.ipAddress}:${PropagationServer.port}/${this.storeId}`;
94
+ if (rootHash) {
95
+ url += `?hasRootHash=${rootHash}`;
96
+ }
97
+ const response = await axios_1.default.head(url, config);
98
+ // Extract store existence and root hash existence from headers
99
+ const storeExists = response.headers["x-store-exists"] === "true";
100
+ const rootHashExists = response.headers["x-has-root-hash"] === "true";
101
+ if (storeExists) {
102
+ spinner.success({
103
+ text: (0, colorette_1.green)(`Store ${this.storeId} exists on peer: ${this.ipAddress}`),
104
+ });
105
+ }
106
+ else {
107
+ spinner.error({
108
+ text: (0, colorette_1.yellow)(`Store ${this.storeId} does not exist on ${this.ipAddress}. Credentials will be required to push.`),
109
+ });
110
+ }
111
+ return { storeExists, rootHashExists };
82
112
  }
83
- const uploadDetails = await this.fetchUploadDetails(username, password);
84
- if (!uploadDetails) {
85
- throw new Error("Failed to retrieve upload details.");
113
+ catch (error) {
114
+ spinner.error({ text: (0, colorette_1.red)("Error checking if store exists:") });
115
+ console.error((0, colorette_1.red)(error.message));
116
+ throw error;
86
117
  }
87
- return { ...uploadDetails, username, password };
88
118
  }
89
- // Method to send a POST request
90
- async postRequest(url, data) {
91
- return new Promise((resolve, reject) => {
92
- const urlObj = new url_1.URL(url);
93
- const options = {
94
- hostname: urlObj.hostname,
95
- port: urlObj.port || PropagationServer.port,
96
- path: urlObj.pathname,
97
- method: "POST",
119
+ /**
120
+ * Start an upload session by sending a POST request with the rootHash.dat file.
121
+ */
122
+ async startUploadSession(rootHash) {
123
+ const spinner = (0, nanospinner_1.createSpinner)(`Starting upload session for store ${this.storeId}...`).start();
124
+ try {
125
+ const formData = new form_data_1.default();
126
+ const datFilePath = path_1.default.join(config_1.STORE_PATH, this.storeId, `${rootHash}.dat`);
127
+ // Ensure the rootHash.dat file exists
128
+ if (!fs_1.default.existsSync(datFilePath)) {
129
+ throw new Error(`File not found: ${datFilePath}`);
130
+ }
131
+ formData.append("file", fs_1.default.createReadStream(datFilePath), {
132
+ filename: `${rootHash}.dat`,
133
+ });
134
+ const config = {
135
+ httpsAgent: this.createHttpsAgent(),
98
136
  headers: {
99
- "Content-Type": "application/json",
100
- "Content-Length": Buffer.byteLength(data),
137
+ ...formData.getHeaders(),
101
138
  },
102
- key: fs_1.default.readFileSync(PropagationServer.keyPath),
103
- cert: fs_1.default.readFileSync(PropagationServer.certPath),
104
- rejectUnauthorized: false,
105
139
  };
106
- const req = https_1.default.request(options, (res) => {
107
- if (res.statusCode === 200) {
108
- resolve();
109
- }
110
- else {
111
- reject(new Error(`POST request failed with status ${res.statusCode}: ${res.statusMessage}`));
112
- }
113
- });
114
- req.on("error", (err) => {
115
- reject(err);
116
- });
117
- req.write(data);
118
- req.end();
119
- });
120
- }
121
- // Method to fetch upload details from the server
122
- // Method to fetch upload details from the server
123
- async fetchUploadDetails(username, password) {
124
- const remote = `https://${this.ipAddress}:${PropagationServer.port}/${this.storeId}`;
125
- return (0, spinnerUtils_1.waitForPromise)(() => {
126
- return new Promise((resolve, reject) => {
127
- const url = new url_1.URL(remote);
128
- const options = {
129
- hostname: url.hostname,
130
- port: url.port,
131
- path: url.pathname,
132
- method: "HEAD",
133
- headers: {
134
- Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`,
135
- },
136
- key: fs_1.default.readFileSync(PropagationServer.keyPath),
137
- cert: fs_1.default.readFileSync(PropagationServer.certPath),
138
- rejectUnauthorized: false, // Allow self-signed certificates
140
+ // Add Basic Auth if username and password are present
141
+ if (this.username && this.password) {
142
+ config.auth = {
143
+ username: this.username,
144
+ password: this.password,
139
145
  };
140
- const req = https_1.default.request(options, (res) => {
141
- if (res.statusCode === 200) {
142
- // Check if the headers are present and valid
143
- const nonce = res.headers["x-nonce"];
144
- const lastUploadedHash = res.headers?.["x-last-uploaded-hash"] ||
145
- "0000000000000000000000000000000000000000000000000000000000000000";
146
- const generationIndex = res.headers?.["x-generation-index"] || 0;
147
- console.log({ nonce, lastUploadedHash, generationIndex });
148
- if (nonce) {
149
- resolve({
150
- nonce: nonce,
151
- lastUploadedHash: lastUploadedHash,
152
- generationIndex: Number(generationIndex),
153
- });
154
- }
155
- else {
156
- reject(new Error("Missing required headers in the response."));
157
- }
158
- }
159
- else {
160
- reject(new Error(`Failed to perform preflight check: ${res.statusCode} ${res.statusMessage}`));
161
- }
162
- });
163
- req.on("error", (err) => {
164
- console.error(err.message);
165
- resolve(false); // Resolve to false if there is an error
166
- });
167
- req.end();
146
+ }
147
+ const url = `https://${this.ipAddress}:${PropagationServer.port}/upload/${this.storeId}?roothash=${rootHash}`;
148
+ const response = await axios_1.default.post(url, formData, config);
149
+ this.sessionId = response.data.sessionId;
150
+ spinner.success({
151
+ text: (0, colorette_1.green)(`Upload session started for Root Hash: ${(0, colorette_1.cyan)(rootHash)} with session ID ${this.sessionId}`),
168
152
  });
169
- }, "Performing remote preflight", "Preflight succeeded.", "Error on preflight.");
153
+ }
154
+ catch (error) {
155
+ spinner.error({ text: (0, colorette_1.red)("Error starting upload session:") });
156
+ console.error((0, colorette_1.red)(error.message));
157
+ throw error;
158
+ }
170
159
  }
171
- // Core method to upload a file directly to the server using a stream
172
- async uploadFileDirect(filePath, uploadUrl, username, password, keyOwnershipSig, publicKey, nonce) {
173
- const fileStream = fs_1.default.createReadStream(filePath);
174
- const fileSize = fs_1.default.statSync(filePath).size;
175
- return new Promise((resolve, reject) => {
176
- const url = new url_1.URL(uploadUrl);
177
- const options = {
178
- hostname: url.hostname,
179
- port: url.port,
180
- path: url.pathname,
181
- method: "PUT",
182
- headers: {
183
- "Content-Type": "application/octet-stream",
184
- "Content-Length": fileSize,
185
- Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`,
186
- "x-key-ownership-sig": keyOwnershipSig,
187
- "x-public-key": publicKey,
188
- "x-nonce": nonce,
189
- },
190
- key: fs_1.default.readFileSync(PropagationServer.keyPath),
191
- cert: fs_1.default.readFileSync(PropagationServer.certPath),
192
- rejectUnauthorized: false,
160
+ /**
161
+ * Request a nonce for a file by sending a HEAD request to the server.
162
+ */
163
+ async getFileNonce(filename) {
164
+ try {
165
+ const config = {
166
+ httpsAgent: this.createHttpsAgent(),
193
167
  };
194
- const req = https_1.default.request(options, (res) => {
195
- if (res.statusCode === 200) {
196
- resolve();
197
- }
198
- else {
199
- reject(new Error(`Upload failed with status ${res.statusCode}: ${res.statusMessage}`));
200
- }
168
+ const url = `https://${this.ipAddress}:${PropagationServer.port}/upload/${this.storeId}/${this.sessionId}/${filename}`;
169
+ const response = await axios_1.default.head(url, config);
170
+ // Check for 'x-file-exists' header
171
+ const fileExists = response.headers["x-file-exists"] === "true";
172
+ // If file exists, no need to generate a nonce
173
+ const nonce = response.headers["x-nonce"];
174
+ return { nonce, fileExists };
175
+ }
176
+ catch (error) {
177
+ console.error((0, colorette_1.red)(`Error generating nonce for file ${filename}:`), error.message);
178
+ throw error;
179
+ }
180
+ }
181
+ /**
182
+ * Upload a file to the server by sending a PUT request.
183
+ * Logs progress using a local cli-progress bar.
184
+ */
185
+ async uploadFile(label, dataPath) {
186
+ const filePath = path_1.default.join(config_1.STORE_PATH, this.storeId, dataPath);
187
+ const { nonce, fileExists } = await this.getFileNonce(dataPath);
188
+ if (fileExists) {
189
+ console.log((0, colorette_1.blue)(`File ${label} already exists. Skipping upload.`));
190
+ return;
191
+ }
192
+ const wallet = await blockchain_1.Wallet.load("default");
193
+ const keyOwnershipSig = await wallet.createKeyOwnershipSignature(nonce);
194
+ const publicKey = await wallet.getPublicSyntheticKey();
195
+ // Get the file size
196
+ const fileSize = fs_1.default.statSync(filePath).size;
197
+ let progressBar;
198
+ try {
199
+ // Create a new progress bar for the file
200
+ progressBar = new cli_progress_1.default.SingleBar({
201
+ format: `${(0, colorette_1.blue)("[{bar}]")} | ${(0, colorette_1.yellow)("{filename}")} | {percentage}% | {value}/{total} bytes`,
202
+ hideCursor: true,
203
+ barsize: 30,
204
+ align: "left",
205
+ autopadding: true,
206
+ noTTYOutput: false,
207
+ stopOnComplete: true,
208
+ clearOnComplete: false,
209
+ }, cli_progress_1.default.Presets.legacy);
210
+ progressBar.start(fileSize, 0, {
211
+ filename: formatFilename(label),
201
212
  });
202
- req.on("error", (err) => {
203
- reject(err);
213
+ // Create the read stream
214
+ const fileReadStream = fs_1.default.createReadStream(filePath);
215
+ // Create a progress stream
216
+ const progressStream = (0, progress_stream_1.default)({
217
+ length: fileSize,
218
+ time: 500, // Adjust as needed
204
219
  });
205
- fileStream.pipe(req);
206
- fileStream.on("error", (err) => {
207
- reject(err);
220
+ progressStream.on("progress", (progress) => {
221
+ progressBar.update(progress.transferred);
208
222
  });
209
- req.on("end", () => {
210
- resolve();
223
+ // Add inactivity timeout to the progress stream
224
+ const passThroughStream = this.addInactivityTimeout(new stream_1.PassThrough(), PropagationServer.inactivityTimeout);
225
+ // Pipe the read stream through the progress stream into the PassThrough stream
226
+ fileReadStream.pipe(progressStream).pipe(passThroughStream);
227
+ // Use form-data to construct the request body
228
+ const formData = new form_data_1.default();
229
+ formData.append("file", passThroughStream);
230
+ const headers = {
231
+ ...formData.getHeaders(),
232
+ "x-nonce": nonce,
233
+ "x-public-key": publicKey.toString("hex"),
234
+ "x-key-ownership-sig": keyOwnershipSig,
235
+ };
236
+ const config = {
237
+ headers: headers,
238
+ httpsAgent: this.createHttpsAgent(),
239
+ maxContentLength: Infinity,
240
+ maxBodyLength: Infinity,
241
+ };
242
+ const url = `https://${this.ipAddress}:${PropagationServer.port}/upload/${this.storeId}/${this.sessionId}/${dataPath}`;
243
+ // Create a promise that resolves when the progress stream ends
244
+ const progressPromise = new Promise((resolve, reject) => {
245
+ progressStream.on("end", resolve);
246
+ progressStream.on("error", reject);
211
247
  });
212
- });
213
- }
214
- // Generic retry operation handler to reduce redundancy
215
- async retryOperation(operation, errorMessage) {
216
- let attempt = 0;
217
- let delay = PropagationServer.initialDelay;
218
- while (attempt < PropagationServer.maxRetries) {
219
- try {
220
- return await operation();
221
- }
222
- catch (error) {
223
- if (attempt < PropagationServer.maxRetries - 1) {
224
- console.warn(`Attempt ${attempt + 1} failed: ${error.message}. Retrying in ${delay / 1000} seconds...`);
225
- await new Promise((resolve) => setTimeout(resolve, delay));
226
- delay = Math.min(PropagationServer.maxDelay, delay * PropagationServer.delayMultiplier);
227
- }
228
- else {
229
- console.error(`${errorMessage}. Aborting.`);
230
- throw error;
231
- }
248
+ // Start the upload request
249
+ const uploadPromise = axios_1.default.put(url, formData, config);
250
+ // Wait for both the upload and the progress stream to finish
251
+ await Promise.all([uploadPromise, progressPromise]);
252
+ }
253
+ catch (error) {
254
+ throw error;
255
+ }
256
+ finally {
257
+ if (progressBar) {
258
+ progressBar.stop();
232
259
  }
233
- attempt++;
234
260
  }
235
- throw new Error(errorMessage);
236
261
  }
237
- // Core method to fetch content from a URL
238
- async fetch(url) {
239
- return new Promise((resolve, reject) => {
240
- const urlObj = new url_1.URL(url);
241
- const options = {
242
- hostname: urlObj.hostname,
243
- port: urlObj.port,
244
- path: urlObj.pathname + urlObj.search,
245
- method: "GET",
246
- key: fs_1.default.readFileSync(PropagationServer.keyPath),
247
- cert: fs_1.default.readFileSync(PropagationServer.certPath),
248
- rejectUnauthorized: false,
249
- };
250
- const request = https_1.default.request(options, (response) => {
251
- let data = "";
252
- if (response.statusCode === 200) {
253
- response.on("data", (chunk) => {
254
- data += chunk;
255
- });
256
- response.on("end", () => {
257
- resolve(data);
258
- });
259
- }
260
- else if (response.statusCode === 301 || response.statusCode === 302) {
261
- const redirectUrl = response.headers.location;
262
- if (redirectUrl) {
263
- this.fetch(redirectUrl).then(resolve).catch(reject);
264
- }
265
- else {
266
- reject(new Error("Redirected without a location header"));
262
+ /**
263
+ * Commit the upload session by sending a POST request to the server.
264
+ */
265
+ async commitUploadSession() {
266
+ const spinner = (0, nanospinner_1.createSpinner)(`Committing upload session for store ${this.storeId}...`).start();
267
+ try {
268
+ const config = {
269
+ httpsAgent: this.createHttpsAgent(),
270
+ auth: this.username && this.password
271
+ ? {
272
+ username: this.username,
273
+ password: this.password,
267
274
  }
268
- }
269
- else {
270
- reject(new Error(`Failed to retrieve data from ${url}. Status code: ${response.statusCode}`));
271
- }
272
- });
273
- request.on("error", (error) => {
274
- console.error(`Request error for ${url}:`, error);
275
- reject(error);
275
+ : undefined,
276
+ };
277
+ const url = `https://${this.ipAddress}:${PropagationServer.port}/commit/${this.storeId}/${this.sessionId}`;
278
+ const response = await axios_1.default.post(url, {}, config);
279
+ spinner.success({
280
+ text: (0, colorette_1.green)(`Upload session ${this.sessionId} successfully committed.`),
276
281
  });
277
- request.end();
282
+ return response.data;
283
+ }
284
+ catch (error) {
285
+ spinner.error({ text: (0, colorette_1.red)("Error committing upload session:") });
286
+ console.error((0, colorette_1.red)(error.message));
287
+ throw error;
288
+ }
289
+ }
290
+ /**
291
+ * Static function to handle the entire upload process for multiple files based on rootHash.
292
+ */
293
+ static async uploadStore(storeId, rootHash, ipAddress) {
294
+ const propagationServer = new PropagationServer(ipAddress, storeId);
295
+ // Initialize wallet
296
+ await propagationServer.initializeWallet();
297
+ // Check if the store exists
298
+ const { storeExists, rootHashExists } = await propagationServer.checkStoreExists(rootHash);
299
+ // If the store does not exist, prompt for credentials
300
+ if (!storeExists) {
301
+ console.log((0, colorette_1.red)(`Store ${storeId} does not exist. Prompting for credentials...`));
302
+ const credentials = await (0, credentialsUtils_1.promptCredentials)(propagationServer.ipAddress);
303
+ propagationServer.username = credentials.username;
304
+ propagationServer.password = credentials.password;
305
+ }
306
+ if (rootHashExists) {
307
+ console.log((0, colorette_1.blue)(`Root hash ${rootHash} already exists in the store. Skipping upload.`));
308
+ return;
309
+ }
310
+ // Start the upload session
311
+ await propagationServer.startUploadSession(rootHash);
312
+ const dataStore = blockchain_1.DataStore.from(storeId);
313
+ const files = await dataStore.getFileSetForRootHash(rootHash);
314
+ // Prepare upload tasks
315
+ const uploadTasks = files.map((file) => ({
316
+ label: file.name,
317
+ dataPath: file.path,
318
+ }));
319
+ // Limit the number of concurrent uploads
320
+ const concurrencyLimit = 10; // Adjust this number as needed
321
+ await (0, asyncPool_1.asyncPool)(concurrencyLimit, uploadTasks, async (task) => {
322
+ await propagationServer.uploadFile(task.label, task.dataPath);
278
323
  });
324
+ // Commit the session after all files have been uploaded
325
+ await propagationServer.commitUploadSession();
326
+ console.log((0, colorette_1.green)(`✔ All files have been uploaded to for Root Hash: ${(0, colorette_1.cyan)(rootHash)}.`));
279
327
  }
280
- // Helper method to perform HEAD requests
281
- async head(url) {
282
- return new Promise((resolve, reject) => {
283
- const urlObj = new url_1.URL(url);
284
- const options = {
285
- hostname: urlObj.hostname,
286
- port: urlObj.port || PropagationServer.port,
287
- path: urlObj.pathname + urlObj.search,
288
- method: "HEAD",
289
- key: fs_1.default.readFileSync(PropagationServer.keyPath),
290
- cert: fs_1.default.readFileSync(PropagationServer.certPath),
291
- rejectUnauthorized: false,
292
- };
293
- const request = https_1.default.request(options, (response) => {
294
- if (response.statusCode === 200) {
295
- resolve(true);
296
- }
297
- else {
298
- resolve(false);
299
- }
328
+ /**
329
+ * Fetch a file from the server by sending a GET request and return its content in memory.
330
+ * Logs progress using a local cli-progress bar.
331
+ */
332
+ async fetchFile(dataPath) {
333
+ const url = `https://${this.ipAddress}:${PropagationServer.port}/fetch/${this.storeId}/${dataPath}`;
334
+ const config = {
335
+ responseType: "stream",
336
+ httpsAgent: this.createHttpsAgent(),
337
+ };
338
+ let progressBar;
339
+ try {
340
+ const response = await axios_1.default.get(url, config);
341
+ const totalLengthHeader = response.headers["content-length"];
342
+ const totalLength = totalLengthHeader
343
+ ? parseInt(totalLengthHeader, 10)
344
+ : null;
345
+ if (!totalLength) {
346
+ throw new Error("Content-Length header is missing");
347
+ }
348
+ // Create a new progress bar for the file
349
+ progressBar = new cli_progress_1.default.SingleBar({
350
+ format: `${(0, colorette_1.blue)("[{bar}]")} | ${(0, colorette_1.yellow)("{filename}")} | {percentage}% | {value}/{total} bytes`,
351
+ hideCursor: true,
352
+ barsize: 30,
353
+ align: "left",
354
+ autopadding: true,
355
+ noTTYOutput: false,
356
+ stopOnComplete: true,
357
+ clearOnComplete: false,
358
+ }, cli_progress_1.default.Presets.legacy);
359
+ progressBar.start(totalLength, 0, {
360
+ filename: formatFilename(dataPath),
300
361
  });
301
- request.on("error", (error) => {
302
- console.error(`Request error for ${url}:`, error);
303
- reject(false);
362
+ let dataBuffers = [];
363
+ const progressStream = (0, progress_stream_1.default)({
364
+ length: totalLength,
365
+ time: 500, // Adjust as needed
304
366
  });
305
- request.end();
306
- });
307
- }
308
- // Helper method to fetch JSON data from a URL
309
- async fetchJson(url) {
310
- const response = await this.fetch(url);
311
- return JSON.parse(response);
367
+ progressStream.on("progress", (progress) => {
368
+ progressBar.update(progress.transferred);
369
+ });
370
+ // Add inactivity timeout to the progress stream
371
+ const passThroughStream = this.addInactivityTimeout(new stream_1.PassThrough(), PropagationServer.inactivityTimeout);
372
+ response.data.pipe(progressStream).pipe(passThroughStream);
373
+ progressStream.on("data", (chunk) => {
374
+ dataBuffers.push(chunk);
375
+ });
376
+ // Wait for the progress stream to finish
377
+ await new Promise((resolve, reject) => {
378
+ progressStream.on("end", resolve);
379
+ progressStream.on("error", reject);
380
+ });
381
+ return Buffer.concat(dataBuffers);
382
+ }
383
+ catch (error) {
384
+ throw error;
385
+ }
386
+ finally {
387
+ if (progressBar) {
388
+ progressBar.stop();
389
+ }
390
+ }
312
391
  }
313
- // Helper method to fetch content with retries and redirection handling
314
- /*private async fetchWithRetries(url: string): Promise<string> {
315
- let attempt = 0;
316
- const maxRetries = 5;
317
- const initialDelay = 2000; // 2 seconds
318
- const maxDelay = 10000; // 10 seconds
319
- const delayMultiplier = 1.5;
320
- let delay = initialDelay;
321
-
322
- while (attempt < maxRetries) {
392
+ /**
393
+ * Get details of a file, including whether it exists and its size.
394
+ */
395
+ async getFileDetails(dataPath, rootHash) {
323
396
  try {
324
- return await this.fetch(url);
325
- } catch (error: any) {
326
- if (attempt < maxRetries - 1) {
327
- console.warn(
328
- `Attempt ${attempt + 1} failed: ${error.message}. Retrying in ${
329
- delay / 1000
330
- } seconds...`
331
- );
332
- await new Promise((resolve) => setTimeout(resolve, delay));
333
- delay = Math.min(maxDelay, delay * delayMultiplier);
334
- } else {
335
- console.error(`Failed to retrieve data from ${url}. Aborting.`);
336
- throw new Error(`Failed to retrieve data: ${error.message}`);
337
- }
397
+ const config = {
398
+ httpsAgent: this.createHttpsAgent(),
399
+ };
400
+ const url = `https://${this.ipAddress}:${PropagationServer.port}/store/${this.storeId}/${rootHash}/${dataPath}`;
401
+ const response = await axios_1.default.head(url, config);
402
+ // Check the headers for file existence and size
403
+ const fileExists = response.headers["x-file-exists"] === "true";
404
+ const fileSize = parseInt(response.headers["x-file-size"], 10);
405
+ return {
406
+ exists: fileExists,
407
+ size: fileExists ? fileSize : 0,
408
+ };
338
409
  }
339
- attempt++;
340
- }
341
- throw new Error(
342
- `Failed to retrieve data from ${url} after ${maxRetries} attempts.`
343
- );
344
- }*/
345
- // Helper method to create a stream with retry logic
346
- async createReadStreamWithRetries(url) {
347
- let attempt = 0;
348
- const maxRetries = 1;
349
- const initialDelay = PropagationServer.initialDelay;
350
- const maxDelay = PropagationServer.maxDelay;
351
- const delayMultiplier = PropagationServer.delayMultiplier;
352
- let delay = initialDelay;
353
- while (attempt < maxRetries) {
354
- try {
355
- return await this.createReadStream(url); // Stream data chunk by chunk
410
+ catch (error) {
411
+ console.error((0, colorette_1.red)(`✖ Error checking file details for ${dataPath}:`), error.message);
412
+ throw error;
413
+ }
414
+ }
415
+ /**
416
+ * Download a file from the server by sending a GET request.
417
+ * Logs progress using a local cli-progress bar.
418
+ */
419
+ async downloadFile(label, dataPath, rootHash, baseDir) {
420
+ const url = `https://${this.ipAddress}:${PropagationServer.port}/fetch/${this.storeId}/${dataPath}`;
421
+ let downloadPath = path_1.default.join(baseDir, dataPath);
422
+ // Ensure that the directory for the file exists
423
+ fs_1.default.mkdirSync(path_1.default.dirname(downloadPath), { recursive: true });
424
+ const config = {
425
+ responseType: "stream",
426
+ httpsAgent: this.createHttpsAgent(),
427
+ };
428
+ let progressBar;
429
+ try {
430
+ const response = await axios_1.default.get(url, config);
431
+ const totalLengthHeader = response.headers["content-length"];
432
+ const totalLength = totalLengthHeader
433
+ ? parseInt(totalLengthHeader, 10)
434
+ : null;
435
+ if (!totalLength) {
436
+ throw new Error("Content-Length header is missing");
356
437
  }
357
- catch (error) {
358
- if (attempt < maxRetries - 1) {
359
- console.warn(`Attempt ${attempt + 1} failed: ${error.message}. Retrying in ${delay / 1000} seconds...`);
360
- await new Promise((resolve) => setTimeout(resolve, delay));
361
- delay = Math.min(maxDelay, delay * delayMultiplier);
362
- }
363
- else {
364
- console.error(`Failed to create stream from ${url}. Aborting.`);
365
- throw new Error(`Failed to create stream: ${error.message}`);
438
+ // Create a new progress bar for the file
439
+ progressBar = new cli_progress_1.default.SingleBar({
440
+ format: `${(0, colorette_1.blue)("[{bar}]")} | ${(0, colorette_1.yellow)("{filename}")} | {percentage}% | {value}/{total} bytes`,
441
+ hideCursor: true,
442
+ barsize: 30,
443
+ align: "left",
444
+ autopadding: true,
445
+ noTTYOutput: false,
446
+ stopOnComplete: true,
447
+ clearOnComplete: false,
448
+ }, cli_progress_1.default.Presets.legacy);
449
+ progressBar.start(totalLength, 0, {
450
+ filename: formatFilename(label),
451
+ });
452
+ const fileWriteStream = fs_1.default.createWriteStream(downloadPath);
453
+ const progressStream = (0, progress_stream_1.default)({
454
+ length: totalLength,
455
+ time: 500, // Adjust as needed
456
+ });
457
+ progressStream.on("progress", (progress) => {
458
+ progressBar.update(progress.transferred);
459
+ });
460
+ // Add inactivity timeout to the progress stream
461
+ const passThroughStream = this.addInactivityTimeout(new stream_1.PassThrough(), PropagationServer.inactivityTimeout);
462
+ response.data
463
+ .pipe(progressStream)
464
+ .pipe(passThroughStream)
465
+ .pipe(fileWriteStream);
466
+ // Wait for both the file write stream and the progress stream to finish
467
+ await Promise.all([
468
+ new Promise((resolve, reject) => {
469
+ fileWriteStream.on("finish", resolve);
470
+ fileWriteStream.on("error", reject);
471
+ }),
472
+ new Promise((resolve, reject) => {
473
+ progressStream.on("end", resolve);
474
+ progressStream.on("error", reject);
475
+ }),
476
+ ]);
477
+ if (dataPath.includes("/data")) {
478
+ const integrity = await (0, merkle_1.merkleIntegrityCheck)(path_1.default.join(baseDir, `${rootHash}.dat`), baseDir, dataPath, rootHash);
479
+ if (!integrity) {
480
+ throw new Error(`Integrity check failed for file: ${dataPath}`);
366
481
  }
482
+ console.log("integrity check");
483
+ }
484
+ }
485
+ catch (error) {
486
+ throw error;
487
+ }
488
+ finally {
489
+ if (progressBar) {
490
+ progressBar.stop();
367
491
  }
368
- attempt++;
369
492
  }
370
- throw new Error(`Failed to create stream from ${url} after ${maxRetries} attempts.`);
371
493
  }
372
- // Helper method to fetch a readable stream from a URL
373
- async createReadStream(url) {
374
- return new Promise((resolve, reject) => {
375
- const urlObj = new url_1.URL(url);
376
- const options = {
377
- hostname: urlObj.hostname,
378
- port: urlObj.port || PropagationServer.port,
379
- path: urlObj.pathname + urlObj.search,
380
- method: "GET",
381
- key: fs_1.default.readFileSync(PropagationServer.keyPath),
382
- cert: fs_1.default.readFileSync(PropagationServer.certPath),
383
- rejectUnauthorized: false,
384
- };
385
- const request = https_1.default.request(options, (response) => {
386
- if (response.statusCode === 200) {
387
- resolve(response); // Return the response stream chunk by chunk
388
- }
389
- else if (response.statusCode === 301 || response.statusCode === 302) {
390
- const redirectUrl = response.headers.location;
391
- if (redirectUrl) {
392
- this.createReadStream(redirectUrl).then(resolve).catch(reject);
393
- }
394
- else {
395
- reject(new Error("Redirected without a location header"));
494
+ /**
495
+ * Static function to handle downloading multiple files from a DataStore based on file paths.
496
+ */
497
+ static async downloadStore(storeId, rootHash, ipAddress) {
498
+ const propagationServer = new PropagationServer(ipAddress, storeId);
499
+ // Initialize wallet
500
+ await propagationServer.initializeWallet();
501
+ // Check if the store exists
502
+ const { storeExists, rootHashExists } = await propagationServer.checkStoreExists(rootHash);
503
+ if (!storeExists || !rootHashExists) {
504
+ throw new Error(`Store ${storeId} does not exist.`);
505
+ }
506
+ // Fetch the rootHash.dat file
507
+ const datFileContent = await propagationServer.fetchFile(`${rootHash}.dat`);
508
+ const root = JSON.parse(datFileContent.toString());
509
+ // Prepare download tasks
510
+ const downloadTasks = [];
511
+ for (const [fileKey, fileData] of Object.entries(root.files)) {
512
+ const dataPath = (0, hashUtils_1.getFilePathFromSha256)(root.files[fileKey].sha256, "data");
513
+ const label = Buffer.from(fileKey, "hex").toString("utf-8");
514
+ downloadTasks.push({ label, dataPath });
515
+ }
516
+ // Limit the number of concurrent downloads
517
+ const concurrencyLimit = 10; // Adjust this number as needed
518
+ // Create a temporary directory
519
+ const tempDir = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), "downloadStore-"));
520
+ try {
521
+ // Download files to the temporary directory
522
+ await (0, asyncPool_1.asyncPool)(concurrencyLimit, downloadTasks, async (task) => {
523
+ await propagationServer.downloadFile(task.label, task.dataPath, rootHash, tempDir);
524
+ });
525
+ // Save the rootHash.dat file to the temporary directory
526
+ if (!fs_1.default.existsSync(tempDir)) {
527
+ fs_1.default.mkdirSync(tempDir, { recursive: true });
528
+ }
529
+ fs_1.default.writeFileSync(path_1.default.join(tempDir, `${rootHash}.dat`), datFileContent);
530
+ // Integrity check for the downloaded files was done during the download
531
+ // Here we want to make sure we got all the files or we reject the download session
532
+ for (const [fileKey, fileData] of Object.entries(root.files)) {
533
+ const dataPath = (0, hashUtils_1.getFilePathFromSha256)(root.files[fileKey].sha256, "data");
534
+ if (!fs_1.default.existsSync(path_1.default.join(tempDir, dataPath))) {
535
+ if (!fs_1.default.existsSync(path_1.default.join(config_1.STORE_PATH, storeId, dataPath))) {
536
+ throw new Error(`Missing file: ${Buffer.from(fileKey, "hex")}, aborting session.`);
396
537
  }
397
538
  }
398
- else {
399
- reject(new Error(`Failed to retrieve stream from ${url}. Status code: ${response.statusCode}`));
400
- }
401
- });
402
- request.on("error", (error) => {
403
- console.error(`Request error for ${url}:`, error);
404
- reject(error);
539
+ }
540
+ // After all downloads are complete, copy from temp directory to the main directory
541
+ const destinationDir = path_1.default.join(config_1.STORE_PATH, storeId);
542
+ fs_extra_1.default.copySync(tempDir, destinationDir, {
543
+ overwrite: false, // Prevents overwriting existing files
544
+ errorOnExist: false, // No error if file already exists
405
545
  });
406
- request.end();
407
- });
546
+ // Generate the manifest file in the main directory
547
+ const dataStore = blockchain_1.DataStore.from(storeId);
548
+ await dataStore.cacheStoreCreationHeight();
549
+ await dataStore.generateManifestFile();
550
+ console.log((0, colorette_1.green)(`✔ All files have been downloaded to ${storeId}.`));
551
+ }
552
+ catch (error) {
553
+ console.log((0, colorette_1.red)("✖ Error downloading files:"), error);
554
+ }
555
+ finally {
556
+ // Clean up the temporary directory
557
+ fs_extra_1.default.removeSync(tempDir);
558
+ }
408
559
  }
409
560
  }
410
561
  exports.PropagationServer = PropagationServer;
411
- PropagationServer.port = 4159;
412
- PropagationServer.maxRetries = 5;
413
- PropagationServer.initialDelay = 2000; // 2 seconds
414
- PropagationServer.maxDelay = 10000; // 10 seconds
415
- PropagationServer.delayMultiplier = 1.5;
562
+ PropagationServer.port = 4159; // Static port used for all requests
563
+ PropagationServer.inactivityTimeout = 5000; // Inactivity timeout in milliseconds (5 seconds)