-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathstore_big_data.js
More file actions
363 lines (322 loc) · 15.5 KB
/
store_big_data.js
File metadata and controls
363 lines (322 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import { cryptoWaitReady } from '@polkadot/util-crypto';
import fs from 'fs'
import os from "os";
import path from "path";
import assert from "assert";
import {authorizeAccount, store, fetchCid, TX_MODE_FINALIZED_BLOCK, TX_MODE_IN_BLOCK} from "./api.js";
import { buildUnixFSDagPB, cidFromBytes } from "./cid_dag_metadata.js";
import {
setupKeyringAndSigners,
CHUNK_SIZE,
newSigner,
fileToDisk,
filesAreEqual,
generateTextImage,
waitForBlockProduction,
DEFAULT_IPFS_GATEWAY_URL,
} from "./common.js";
import {
logHeader,
logConnection,
logStep,
logSuccess,
logError,
logTestResult,
} from "./logger.js";
import { createClient } from 'polkadot-api';
import { getWsProvider } from "polkadot-api/ws";
import { bulletin } from './.papi/descriptors/dist/index.js';
// Command line arguments: [ws_url] [seed] [ipfs_gateway_url] [image_size]
// Note: --signer-disc=XX flag is also supported for parallel runs
// Note: --skip-authorize flag skips account authorization (for live networks)
// Note: --skip-ipfs-verify flag skips IPFS download verification
const args = process.argv.slice(2).filter(arg => !arg.startsWith('--'));
const NODE_WS = args[0] || 'ws://localhost:10000';
const SEED = args[1] || '//Alice';
const IPFS_GATEWAY_URL = args[2] || DEFAULT_IPFS_GATEWAY_URL;
// Image size preset: small, big32, big64, big96
const IMAGE_SIZE = args[3] || 'big64';
const NUM_SIGNERS = 16;
// Optional flags
const signerDiscriminator = process.argv.find(arg => arg.startsWith("--signer-disc="))?.split("=")[1] ?? null;
const SKIP_AUTHORIZE = process.argv.includes("--skip-authorize");
const SKIP_IPFS_VERIFY = process.argv.includes("--skip-ipfs-verify");
// -------------------- queue --------------------
const queue = [];
function pushToQueue(data) {
queue.push(data);
}
const resultQueue = [];
function pushToResultQueue(data) {
resultQueue.push(data);
}
// -------------------- statistics --------------------
const stats = {
startTime: null,
endTime: null,
blockNumbers: [], // Track all block numbers where txs were included
blockHashes: {}, // Map block number -> block hash for timestamp lookups
};
function waitForQueueLength(targetLength, timeoutMs = 300000) {
return new Promise((resolve, reject) => {
const start = Date.now();
const interval = setInterval(() => {
if (resultQueue.length >= targetLength) {
clearInterval(interval);
resolve(resultQueue.slice(0, targetLength));
} else if (Date.now() - start > timeoutMs) {
clearInterval(interval);
reject(new Error(`Timeout waiting for ${targetLength} entries in queue`));
}
}, 500); // check every 500ms
});
}
// -------------------- worker --------------------
async function startWorker(typedApi, workerId, signer) {
console.log(`Worker ${workerId} started`);
while (true) {
const job = queue.shift();
if (!job) {
await sleep(500);
continue;
}
try {
await processJob(typedApi, workerId, signer, job);
} catch (err) {
console.error(`Worker ${workerId} failed job`, err);
}
}
}
// -------------------- job processing --------------------
async function processJob(typedApi, workerId, signer, chunk) {
console.log(
`Worker ${workerId} submitting tx for chunk ${chunk.cid} of size ${chunk.len} bytes`
);
let { cid, blockHash, blockNumber } = await store(typedApi, signer.signer, chunk.bytes);
pushToResultQueue({ cid, blockNumber });
if (blockNumber !== undefined) {
stats.blockNumbers.push(blockNumber);
if (blockHash && !stats.blockHashes[blockNumber]) {
stats.blockHashes[blockNumber] = blockHash;
}
}
console.log(`Worker ${workerId} tx included in block #${blockNumber} with CID: ${cid}`);
}
// -------------------- helpers --------------------
function sleep(ms) {
return new Promise(r => setTimeout(r, ms));
}
function formatBytes(bytes) {
if (bytes >= 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MiB';
if (bytes >= 1024) return (bytes / 1024).toFixed(2) + ' KiB';
return bytes + ' B';
}
function formatDuration(ms) {
if (ms >= 60000) return (ms / 60000).toFixed(2) + ' min';
if (ms >= 1000) return (ms / 1000).toFixed(2) + ' s';
return ms + ' ms';
}
async function printStatistics(dataSize, typedApi) {
const numTxs = stats.blockNumbers.length;
const elapsed = stats.endTime - stats.startTime;
// Calculate startBlock and endBlock from actual transaction blocks
const startBlock = Math.min(...stats.blockNumbers);
const endBlock = Math.max(...stats.blockNumbers);
const blocksElapsed = endBlock - startBlock;
// Count transactions per block
const txsPerBlock = {};
for (const blockNum of stats.blockNumbers) {
txsPerBlock[blockNum] = (txsPerBlock[blockNum] || 0) + 1;
}
const numBlocksWithTxs = Object.keys(txsPerBlock).length;
const totalBlocksInRange = blocksElapsed + 1;
const avgTxsPerBlock = totalBlocksInRange > 0 ? (numTxs / totalBlocksInRange).toFixed(2) : 'N/A';
// Fetch block timestamps for all blocks in range
// Query at the last known block to ensure all previous blocks are visible
const lastKnownBlockHash = stats.blockHashes[endBlock];
const blockTimestamps = {};
for (let blockNum = startBlock; blockNum <= endBlock; blockNum++) {
try {
// Get block hash - either from stored or query at last known block
let blockHash = stats.blockHashes[blockNum];
if (!blockHash) {
blockHash = await typedApi.query.System.BlockHash.getValue(blockNum, { at: lastKnownBlockHash });
}
// Skip blocks with zero hash (pruned)
if (blockHash.match(/^(0x)?0+$/)) {
continue;
}
const timestamp = await typedApi.query.Timestamp.Now.getValue({ at: blockHash });
blockTimestamps[blockNum] = timestamp;
} catch (e) {
console.error(`Failed to fetch timestamp for block #${blockNum}:`, e.message);
}
}
console.log('\n');
// Calculate average block time from timestamps
const startTimestamp = blockTimestamps[startBlock];
const endTimestamp = blockTimestamps[endBlock];
const avgBlockTime = (startTimestamp && endTimestamp && blocksElapsed > 0)
? (Number(endTimestamp) - Number(startTimestamp)) / blocksElapsed
: null;
console.log('════════════════════════════════════════════════════════════════════════════════');
console.log('📊 STORAGE STATISTICS');
console.log('════════════════════════════════════════════════════════════════════════════════');
console.log(`│ File size │ ${formatBytes(dataSize).padEnd(25)} │`);
console.log(`│ Chunk/TX size │ ${formatBytes(CHUNK_SIZE).padEnd(25)} │`);
console.log(`│ Number of chunks │ ${numTxs.toString().padEnd(25)} │`);
console.log(`│ Avg txs per block │ ${`${avgTxsPerBlock} (${numTxs} txs in #${startBlock} → #${endBlock})`.padEnd(25)} │`);
console.log(`│ Avg block time │ ${(avgBlockTime ? formatDuration(avgBlockTime) : 'N/A').padEnd(25)} │`);
console.log(`│ Time elapsed │ ${formatDuration(elapsed).padEnd(25)} │`);
console.log(`│ Blocks elapsed │ ${`${blocksElapsed} (#${startBlock} → #${endBlock})`.padEnd(25)} │`);
console.log(`│ Throughput/sec │ ${(formatBytes(dataSize / (elapsed / 1000)) + '/s').padEnd(25)} │`);
console.log(`│ Throughput/block │ ${(formatBytes(dataSize / totalBlocksInRange) + '/block').padEnd(25)} │`);
console.log('════════════════════════════════════════════════════════════════════════════════');
console.log('📦 TRANSACTIONS PER BLOCK');
console.log('════════════════════════════════════════════════════════════════════════════════');
console.log('│ Block │ Time │ TXs │ Size │ Bar │');
console.log('├─────────────┼─────────────────────┼─────┼──────────────┼──────────────────────┤');
for (let blockNum = startBlock; blockNum <= endBlock; blockNum++) {
const count = txsPerBlock[blockNum] || 0;
const size = count > 0 ? formatBytes(count * CHUNK_SIZE) : '-';
const bar = count > 0 ? '█'.repeat(Math.min(count, 20)) : '';
const timestamp = blockTimestamps[blockNum];
const timeStr = timestamp ? new Date(Number(timestamp)).toISOString().replace('T', ' ').slice(0, 19) : '-';
console.log(`│ #${blockNum.toString().padEnd(10)} │ ${timeStr.padEnd(19)} │ ${count.toString().padStart(3)} │ ${size.padEnd(12)} │ ${bar.padEnd(20)} │`);
}
console.log('════════════════════════════════════════════════════════════════════════════════');
console.log('\n');
}
/**
* Read the file, chunk it and put to the queue for storing in Bulletin and return CIDs.
* Returns { chunks }
*/
export async function storeChunkedFile(api, filePath) {
// ---- 1️⃣ Read and split a file ----
const fileData = fs.readFileSync(filePath)
console.log(`📁 Read ${filePath}, size ${fileData.length} bytes`)
const chunks = []
for (let i = 0; i < fileData.length; i += CHUNK_SIZE) {
const chunk = fileData.subarray(i, i + CHUNK_SIZE)
const cid = await cidFromBytes(chunk)
chunks.push({ cid, bytes: chunk, len: chunk.length })
}
console.log(`✂️ Split into ${chunks.length} chunks`)
// Start timing for statistics
stats.startTime = Date.now();
// ---- 2️⃣ Store chunks in Bulletin ----
for (let i = 0; i < chunks.length; i++) {
pushToQueue(chunks[i]);
}
return { chunks, dataSize: fileData.length };
}
async function main() {
await cryptoWaitReady()
logHeader('STORE BIG DATA TEST');
logConnection(NODE_WS, SEED, IPFS_GATEWAY_URL);
let client, resultCode;
try {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "bulletinimggen-"));
const filePath = path.join(tmpDir, "image.jpeg");
const downloadedFilePath = path.join(tmpDir, "downloaded.jpeg");
const downloadedFileByDagPath = path.join(tmpDir, "downloadedByDag.jpeg");
generateTextImage(filePath, `Hello, Bulletin ${IMAGE_SIZE} - ` + new Date().toString(), IMAGE_SIZE);
// Init WS PAPI client and typed api.
client = createClient(getWsProvider(NODE_WS));
const bulletinAPI = client.getTypedApi(bulletin);
await waitForBlockProduction(bulletinAPI);
// Let's do parallelism with multiple accounts
const signers = Array.from({ length: NUM_SIGNERS }, (_, i) => {
if (!signerDiscriminator) {
return newSigner(`//Signer${i + 1}`)
} else {
console.log(`Using signerDiscriminator: "//Signer${signerDiscriminator}${i + 1}"`);
return newSigner(`//Signer${signerDiscriminator}${i + 1}`)
}
});
// Authorize accounts (skip for live networks with pre-authorized accounts)
if (!SKIP_AUTHORIZE) {
const { authorizationSigner, _ } = setupKeyringAndSigners(SEED, '//Bigdatasigner');
await authorizeAccount(
bulletinAPI,
authorizationSigner,
signers.map(a => a.address),
100,
BigInt(100 * 1024 * 1024), // 100 MiB
TX_MODE_FINALIZED_BLOCK,
);
}
// Start 8 workers
signers.forEach((signer, i) => {
startWorker(bulletinAPI, i, signer);
});
// push data to queue
// Read the file, chunk it, store in Bulletin and return CIDs.
let { chunks, dataSize } = await storeChunkedFile(bulletinAPI, filePath);
// wait for all chunks are stored
try {
console.log(`Waiting for all chunks ${chunks.length} to be stored!`);
await waitForQueueLength(chunks.length);
stats.endTime = Date.now();
console.log(`All chunks ${chunks.length} are stored!`);
} catch (err) {
stats.endTime = Date.now();
console.error(err.message);
throw new Error('❌ Storing chunks failed! Error:' + err.message);
}
console.log(`Storing DAG...`);
let { rootCid, dagBytes } = await buildUnixFSDagPB(chunks, 0xb220);
// Store with dag-pb codec (0x70) to match rootCid from buildUnixFSDagPB
let { cid } = await store(
bulletinAPI,
signers[0].signer,
dagBytes,
0x70, // dag-pb codec
0xb220, // blake2b-256
TX_MODE_IN_BLOCK
);
console.log(`Downloading...${cid} / ${rootCid}`);
assert.deepStrictEqual(cid, rootCid, '❌ CID mismatch between stored and computed DAG root');
// Print storage statistics
await printStatistics(dataSize, bulletinAPI);
// IPFS verification (skip with --skip-ipfs-verify)
if (!SKIP_IPFS_VERIFY) {
let downloadedContent = await fetchCid(IPFS_GATEWAY_URL, rootCid);
console.log(`✅ Reconstructed file size: ${downloadedContent.length} bytes`);
await fileToDisk(downloadedFileByDagPath, downloadedContent);
filesAreEqual(filePath, downloadedFileByDagPath);
assert.strictEqual(
dataSize,
downloadedContent.length,
'❌ Failed to download all the data!'
);
// Check all chunks are there.
console.log(`Downloading by chunks...`);
let downloadedChunks = [];
for (const chunk of chunks) {
// Download the chunk from IPFS.
let block = await fetchCid(IPFS_GATEWAY_URL, chunk.cid);
downloadedChunks.push(block);
}
let fullBuffer = Buffer.concat(downloadedChunks);
console.log(`✅ Reconstructed file size: ${fullBuffer.length} bytes`);
await fileToDisk(downloadedFilePath, fullBuffer);
filesAreEqual(filePath, downloadedFilePath);
assert.strictEqual(
dataSize,
fullBuffer.length,
'❌ Failed to download all the data!'
);
}
logTestResult(true, SKIP_IPFS_VERIFY ? 'Store Big Data Test (Storage Only)' : 'Store Big Data Test');
resultCode = 0;
} catch (error) {
logError(`Error: ${error.message}`);
console.error(error);
resultCode = 1;
} finally {
if (client) client.destroy();
process.exit(resultCode);
}
}
await main();