forked from bcoin-org/bcoin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
blockstore.js
476 lines (388 loc) · 11.7 KB
/
blockstore.js
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/*!
* bench/blockstore.js - benchmark blockstore for bcoin
*
* This can be run to benchmark the performance of the blockstore
* module for writing, reading and pruning block data. Results are
* written to stdout as JSON or formated bench results.
*
* Usage:
* node ./blockstore.js [--maxfile=<bytes>] [--total=<bytes>]
* [--location=<path>] [--store=<name>]
* [--output=<name>] [--unsafe]
*
* Options:
* - `maxfile` The maximum file size (applies to "file" store).
* - `total` The total number of block bytes to write.
* - `location` The location to store block data.
* - `store` This can be "file" or "level".
* - `output` This can be "json", "bench" or "benchjson".
* - `unsafe` This will allocate block data directly from memory
* instead of random, it is faster.
*
* Copyright (c) 2019, Braydon Fuller (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
process.title = 'blockstore-bench';
const {isAbsolute} = require('path');
const {mkdirp} = require('bfile');
const random = require('bcrypto/lib/random');
const {BufferMap} = require('buffer-map');
const {
FileBlockStore,
LevelBlockStore
} = require('../lib/blockstore');
const config = {
'maxfile': {
value: true,
parse: a => parseInt(a),
valid: a => Number.isSafeInteger(a),
fallback: 128 * 1024 * 1024
},
'total': {
value: true,
parse: a => parseInt(a),
valid: a => Number.isSafeInteger(a),
fallback: 3 * 1024 * 1024 * 1024
},
'location': {
value: true,
valid: a => isAbsolute(a),
fallback: '/tmp/bcoin-bench-blockstore'
},
'store': {
value: true,
valid: a => (a === 'file' || a === 'level'),
fallback: 'file'
},
'output': {
value: true,
valid: a => (a === 'json' || a === 'bench' || a === 'benchjson'),
fallback: 'bench'
},
'unsafe': {
value: false,
valid: a => (a === true || a === false),
fallback: false
}
};
/**
* These block sizes were generated from bitcoin mainnet blocks by putting
* sizes into bins of 256 ^ (2 * n) as the upper bound and calculating
* the percentage of each and then distributing to roughly match the
* percentage of the following:
*
* |-------------|------------|
* | percentage | bytes |
* |-------------|------------|
* | 23.4055 | 1048576 |
* | 15.5338 | 256 |
* | 12.2182 | 262144 |
* | 8.4079 | 524288 |
* | 7.1289 | 131072 |
* | 6.9197 | 65536 |
* | 6.7073 | 2097152 |
* | 4.6753 | 32768 |
* | 3.9695 | 4096 |
* | 3.3885 | 16384 |
* | 2.6526 | 8192 |
* | 2.0048 | 512 |
* | 1.587 | 1024 |
* | 1.3976 | 2048 |
* | 0.0032 | 4194304 |
* |-------------|------------|
*/
const distribution = [
1048576, 256, 256, 524288, 262144, 256, 131072, 256, 524288, 256, 131072,
1048576, 262144, 1048576, 2097152, 256, 1048576, 65536, 256, 262144, 8192,
32768, 32768, 256, 1048576, 524288, 2097152, 1024, 1048576, 1048576, 131072,
131072, 262144, 512, 1048576, 1048576, 1024, 1048576, 1048576, 262144, 2048,
262144, 256, 1048576, 131072, 4096, 524288, 65536, 4096, 65536, 131072,
2097152, 2097152, 2097152, 256, 524288, 4096, 262144, 65536, 65536, 262144,
16384, 1048576, 32768, 262144, 1048576, 256, 131072, 1048576, 1048576,
1048576, 8192, 1048576, 256, 16384, 1048576, 256, 256, 524288, 256, 32768,
16384, 32768, 1048576, 512, 4096, 1048576, 1048576, 524288, 65536, 2097152,
512, 262144, 8192, 524288, 131072, 65536, 16384, 2048, 262144, 1048576,
1048576, 256, 524288, 262144, 4194304, 262144, 2097152
];
(async () => {
let settings = null;
try {
settings = processArgs(process.argv, config);
} catch (err) {
console.log(err.message);
process.exit(1);
}
await mkdirp(settings.location);
let store = null;
let output = null;
if (settings.store === 'file') {
store = new FileBlockStore({
location: settings.location,
maxFileLength: settings.maxfile
});
} else if (settings.store === 'level') {
store = new LevelBlockStore({
location: settings.location
});
}
if (settings.output === 'bench') {
output = new BenchOutput();
} else if (settings.output === 'benchjson') {
output = new BenchJSONOutput();
} else if (settings.output === 'json') {
output = new JSONOutput();
}
await store.open();
const hashes = [];
const lengths = new BufferMap();
output.start();
// 1. Write data to the block store
let written = 0;
async function write() {
for (const length of distribution) {
const hash = random.randomBytes(32);
let raw = null;
if (settings.unsafe) {
raw = Buffer.allocUnsafe(length);
} else {
raw = random.randomBytes(length);
}
const start = process.hrtime();
await store.write(hash, raw);
const elapsed = process.hrtime(start);
hashes.push(hash);
lengths.set(hash, length);
written += length;
output.result('write', start, elapsed, length);
if (written >= settings.total)
break;
}
}
while (written < settings.total)
await write();
// 2. Read data from the block store
for (const hash of hashes) {
const start = process.hrtime();
const raw = await store.read(hash);
const elapsed = process.hrtime(start);
output.result('read', start, elapsed, raw.length);
}
// 3. Read data not in the order it was written (random)
for (let i = 0; i < hashes.length; i++) {
const rand = random.randomInt() / 0xffffffff * (hashes.length - 1) | 0;
const hash = hashes[rand];
const start = process.hrtime();
const raw = await store.read(hash);
const elapsed = process.hrtime(start);
output.result('randomread', start, elapsed, raw.length);
}
// 4. Prune data from the block store
for (const hash of hashes) {
const start = process.hrtime();
await store.prune(hash);
const elapsed = process.hrtime(start);
const length = lengths.get(hash);
output.result('prune', start, elapsed, length);
}
output.end();
await store.close();
})().catch((err) => {
console.error(err);
process.exit(1);
});
class JSONOutput {
constructor() {
this.time = process.hrtime();
this.index = 0;
}
start() {
process.stdout.write('[');
}
result(type, start, elapsed, length) {
if (this.index > 0)
process.stdout.write(',');
const since = [start[0] - this.time[0], start[1] - this.time[1]];
const smicro = hrToMicro(since);
const emicro = hrToMicro(elapsed);
process.stdout.write(`{"type":"${type}","start":${smicro},`);
process.stdout.write(`"elapsed":${emicro},"length":${length},`);
process.stdout.write(`"index":${this.index}}`);
this.index += 1;
}
end() {
process.stdout.write(']');
}
}
class BenchOutput {
constructor() {
this.time = process.hrtime();
this.index = 0;
this.results = {};
this.interval = null;
this.stdout = process.stdout;
}
start() {
this.stdout.write('Starting benchmark...\n');
this.interval = setInterval(() => {
this.stdout.write(`Operation count=${this.index}\n`);
}, 5000);
}
result(type, start, elapsed, length) {
const micro = hrToMicro(elapsed);
if (!this.results[type])
this.results[type] = {};
if (!this.results[type][length])
this.results[type][length] = [];
this.results[type][length].push(micro);
this.index += 1;
}
end() {
clearInterval(this.interval);
this.stdout.write('Benchmark finished.\n');
function format(value) {
if (typeof value === 'number')
value = value.toFixed(2);
if (typeof value !== 'string')
value = value.toString();
while (value.length < 15)
value = `${value} `;
return value;
}
function title(value) {
if (typeof value !== 'string')
value = value.toString();
while (value.length < 85)
value = ` ${value} `;
if (value.length > 85)
value = value.slice(0, 85);
return value;
}
for (const type in this.results) {
this.stdout.write('\n');
this.stdout.write(`${title(type)}\n`);
this.stdout.write(`${'='.repeat(85)}\n`);
this.stdout.write(`${format('length')}`);
this.stdout.write(`${format('operations')}`);
this.stdout.write(`${format('min')}`);
this.stdout.write(`${format('max')}`);
this.stdout.write(`${format('average')}`);
this.stdout.write(`${format('median')}`);
this.stdout.write('\n');
this.stdout.write(`${'-'.repeat(85)}\n`);
for (const length in this.results[type]) {
const cal = calculate(this.results[type][length]);
this.stdout.write(`${format(length)}`);
this.stdout.write(`${format(cal.operations.toString())}`);
this.stdout.write(`${format(cal.min)}`);
this.stdout.write(`${format(cal.max)}`);
this.stdout.write(`${format(cal.average)}`);
this.stdout.write(`${format(cal.median)}`);
this.stdout.write('\n');
}
this.stdout.write('\n');
}
this.stdout.write('\n');
}
}
class BenchJSONOutput {
constructor() {
this.time = null;
this.results = {};
this.stdout = process.stdout;
}
start() {
this.time = process.hrtime();
}
result(type, start, elapsed, length) {
const micro = hrToMicro(elapsed);
if (!this.results[type])
this.results[type] = {};
if (!this.results[type][length])
this.results[type][length] = [];
this.results[type][length].push(micro);
}
end() {
const report = {
summary: [],
time: hrToMicro(process.hrtime(this.time)),
elapsed: 0
};
for (const type in this.results) {
for (const length in this.results[type]) {
const cal = calculate(this.results[type][length]);
report.elapsed += cal.total;
report.summary.push({
type: type,
length: length,
operations: cal.operations,
min: cal.min,
max: cal.max,
average: cal.average,
median: cal.median
});
}
}
this.stdout.write(JSON.stringify(report, null, 2));
this.stdout.write('\n');
}
}
function hrToMicro(time) {
return (time[0] * 1000000) + (time[1] / 1000);
}
function calculate(times) {
times.sort((a, b) => a - b);
let min = Infinity;
let max = 0;
let total = 0;
for (const micro of times) {
if (micro < min)
min = micro;
if (micro > max)
max = micro;
total += micro;
}
const average = total / times.length;
const median = times[times.length / 2 | 0];
const operations = times.length;
return {
total,
operations,
min,
max,
average,
median
};
}
function processArgs(argv, config) {
const args = {};
for (const key in config)
args[key] = config[key].fallback;
for (let i = 2; i < process.argv.length; i++) {
const arg = process.argv[i];
const match = arg.match(/^(\-){1,2}([a-z]+)(\=)?(.*)?$/);
if (!match) {
throw new Error(`Unexpected argument: ${arg}.`);
} else {
const key = match[2];
let value = match[4];
if (!config[key])
throw new Error(`Invalid argument: ${arg}.`);
if (config[key].value && !value) {
value = process.argv[i + 1];
i++;
} else if (!config[key].value && !value) {
value = true;
} else if (!config[key].value && value) {
throw new Error(`Unexpected value: ${key}=${value}`);
}
if (config[key].parse)
value = config[key].parse(value);
if (value)
args[key] = value;
if (!config[key].valid(args[key]))
throw new Error(`Invalid value: ${key}=${value}`);
}
}
return args;
}