@dignetwork/dig-sdk 0.0.1-alpha.11 → 0.0.1-alpha.111

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