-
Notifications
You must be signed in to change notification settings - Fork 23
/
rpc.js
107 lines (89 loc) · 2.29 KB
/
rpc.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
let debug = require('./debug')('indexd:rpc')
function rpcd (rpc, method, params, done) {
debug(method, params)
rpc(method, params, (err, result) => {
if (err) debug(method, params, err)
if (err) return done(err)
done(null, result)
})
}
function augment (tx) {
delete tx.hex
tx.txId = tx.txid
delete tx.txid
tx.vin.forEach((input) => {
input.prevTxId = input.txid
delete input.txid
})
tx.vout.forEach((output) => {
output.script = Buffer.from(output.scriptPubKey.hex, 'hex')
delete output.scriptPubKey
output.value = Math.round(output.value * 1e8)
output.vout = output.n
delete output.n
})
tx.ins = tx.vin
tx.outs = tx.vout
delete tx.vin
delete tx.vout
return tx
}
function block (rpc, blockId, done) {
rpcd(rpc, 'getblock', [blockId, 2], (err, block) => {
if (err) return done(err)
block.blockId = blockId
delete block.hash
block.nextBlockId = block.nextblockhash
delete block.nextblockhash
block.prevBlockId = block.previousblockhash
delete block.prevblockhash
block.medianTime = block.mediantime
delete block.mediantime
block.transactions = block.tx.map(t => augment(t))
delete block.tx
done(null, block)
})
}
function blockIdAtHeight (rpc, height, done) {
rpcd(rpc, 'getblockhash', [height], done)
}
function headerJSON (rpc, blockId, done) {
rpcd(rpc, 'getblockheader', [blockId, true], (err, header) => {
if (err) return done(err)
header.blockId = blockId
delete header.hash
header.nextBlockId = header.nextblockhash
delete header.nextblockhash
done(null, header)
})
}
function mempool (rpc, done) {
rpcd(rpc, 'getrawmempool', [false], done)
}
function tip (rpc, done) {
rpcd(rpc, 'getchaintips', [], (err, tips) => {
if (err) return done(err)
let {
hash: blockId,
height
} = tips.filter(x => x.status === 'active').pop()
done(null, { blockId, height })
})
}
function transaction (rpc, txId, next, forgiving) {
rpcd(rpc, 'getrawtransaction', [txId, true], (err, tx) => {
if (err) {
if (forgiving && /No such mempool or blockchain transaction/.test(err)) return next()
return next(err)
}
next(null, augment(tx))
})
}
module.exports = {
block,
blockIdAtHeight,
headerJSON,
mempool,
tip,
transaction
}