@dignetwork/dig-sdk 0.0.1-alpha.8 → 0.0.1-alpha.80

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