-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbin.js
More file actions
executable file
·72 lines (65 loc) · 1.85 KB
/
bin.js
File metadata and controls
executable file
·72 lines (65 loc) · 1.85 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
#!/usr/bin/env node
import { Transform } from 'node:stream'
import { createReadStream } from 'node:fs'
import { BitcoinBlock } from './bitcoin-block.js'
/** @typedef {import('node:fs').ReadStream} ReadStream */
/**
* @param {ReadStream} stream
* @returns {Promise<Buffer>}
*/
async function streamToBuffer (stream) {
return new Promise((resolve, reject) => {
/** @type {Uint8Array[]} */
const chunks = []
stream
.on('error', reject)
.pipe(new Transform({
transform (chunk, _, callback) {
chunks.push(chunk)
callback()
}
}))
.on('finish', function () {
resolve(Buffer.concat(chunks))
})
.on('error', reject)
})
}
/**
* @param {Buffer} buf
* @returns {Buffer}
*/
function ensureBinary (buf) {
for (let i = 0; i < buf.length; i++) {
if (buf[i] < 48 || buf[i] > 102) { // not hex
return buf
}
}
// probably hex, convert it
return Buffer.from(buf.toString('ascii'), 'hex')
}
/**
* @param {ReadStream} stream
* @param {'min'|'header'|'full'} [type]
*/
async function toJson (stream, type) {
let block = await streamToBuffer(stream)
block = ensureBinary(block)
const decoded = BitcoinBlock.decode(block)
const porcelain = decoded.toPorcelain(type)
console.log(JSON.stringify(porcelain, null, 2))
}
async function run () {
if (process.argv[2] === 'to-json' || process.argv[2] === 'to-json-min') {
const stream = process.argv.length > 3 ? createReadStream(process.argv[3]) : process.stdin
await toJson(/** @type {ReadStream} */ (stream), process.argv[2] === 'to-json-min' ? 'min' : 'full')
} else {
console.error(`No such command [${process.argv[2] || ''}]`)
console.error('Usage: bitcoin-block <to-json | to-json-min> [file] (or stdin)')
process.exit(1)
}
}
run().catch((err) => {
console.error(err.stack)
process.exit(1)
})