-
Notifications
You must be signed in to change notification settings - Fork 78
/
BitcoinRpcProvider.js
182 lines (149 loc) · 5.32 KB
/
BitcoinRpcProvider.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
import { isArray, flatten } from 'lodash'
import BigNumber from 'bignumber.js'
import JsonRpcProvider from '@liquality/jsonrpc-provider'
import { addressToString } from '@liquality/utils'
import { version } from '../package.json'
export default class BitcoinRpcProvider extends JsonRpcProvider {
constructor (uri, username, password, numberOfBlockConfirmation = 1, defaultFeePerByte = 3) {
super(uri, username, password)
this._numberOfBlockConfirmation = numberOfBlockConfirmation
this._defaultFeePerByte = defaultFeePerByte
}
async decodeRawTransaction (rawTransaction) {
const data = await this.jsonrpc('decoderawtransaction', rawTransaction)
const { txid: hash, vout } = data
const value = vout.reduce((p, n) => p + parseInt(n.value), 0)
const output = { hash, value, _raw: { hex: rawTransaction, data } }
return output
}
async getFeePerByte (numberOfBlocks = this._numberOfBlockConfirmation) {
try {
const { feerate } = await this.jsonrpc('estimatesmartfee', numberOfBlocks)
if (feerate && feerate > 0) {
return Math.ceil((feerate * 1e8) / 1024)
}
throw new Error('Invalid estimated fee')
} catch (e) {
return this._defaultFeePerByte
}
}
async sendTransaction (to, value) {
to = addressToString(to)
value = BigNumber(value).dividedBy(1e8).toNumber()
return this.jsonrpc('sendtoaddress', to, value)
}
async isAddressUsed (address) {
const amountReceived = await this.getReceivedByAddress(address)
return amountReceived > 0
}
async getBalance (addresses) {
if (!isArray(addresses)) {
addresses = [ addresses ]
}
const _utxos = await this.getUnspentTransactions(addresses)
const utxos = flatten(_utxos)
return utxos
.reduce((acc, utxo) => acc.plus(utxo.satoshis), new BigNumber(0))
}
async getUnspentTransactions (addresses) {
addresses = addresses.map(addressToString)
const utxos = await this.jsonrpc('listunspent', 0, 9999999, addresses)
return utxos.map(utxo => ({ ...utxo, satoshis: BigNumber(utxo.amount).times(1e8).toNumber() }))
}
async getReceivedByAddress (address) {
address = addressToString(address)
return this.jsonrpc('getreceivedbyaddress', address)
}
async importAddresses (addresses) {
const request = addresses.map(address => ({ scriptPubKey: { address }, timestamp: 0 }))
return this.jsonrpc('importmulti', request)
}
async getTransactionHex (transactionHash) {
return this.jsonrpc('getrawtransaction', transactionHash)
}
async generateBlock (numberOfBlocks) {
const newAddress = await this.jsonrpc('getnewaddress')
return this.jsonrpc('generatetoaddress', numberOfBlocks, newAddress)
}
async getBlockByHash (blockHash, includeTx = false) {
const data = await this.jsonrpc('getblock', blockHash)
const {
hash,
height: number,
time: timestamp,
difficulty,
size,
previousblockhash: parentHash,
nonce,
confirmations
} = data
let { tx: transactions } = data
if (includeTx) {
const txs = transactions.map(this.getMethod('getTransactionByHash'))
transactions = await Promise.all(txs)
}
return {
hash,
number,
timestamp,
difficulty: parseFloat(BigNumber(difficulty).toFixed()),
size,
parentHash,
nonce,
transactions,
confirmations
}
}
async getBlockByNumber (blockNumber, includeTx) {
return this.getBlockByHash(await this.jsonrpc('getblockhash', blockNumber), includeTx)
}
async getBlockHeight () {
return this.jsonrpc('getblockcount')
}
async getTransactionByHash (transactionHash) {
return this.getRawTransactionByHash(transactionHash, true)
}
async getRawTransactionByHash (transactionHash, decode = false) {
const tx = await this.jsonrpc('getrawtransaction', transactionHash, decode ? 1 : 0)
if (!decode) return tx
const value = tx.vout.reduce((p, n) => p.plus(BigNumber(n.value).times(1e8)), BigNumber(0))
const result = {
hash: tx.txid,
value: value.toNumber(),
_raw: tx,
confirmations: 0
}
if (tx.confirmations > 0) {
const block = await this.getBlockByHash(tx.blockhash)
Object.assign(result, {
blockHash: block.hash,
blockNumber: block.number,
confirmations: tx.confirmations
})
}
return result
}
async sendRawTransaction (rawTransaction) {
return this.jsonrpc('sendrawtransaction', rawTransaction)
}
async sendBatchTransaction (transactions) {
let outputs = {}
for (const tx of transactions) {
outputs[addressToString(tx.to)] = BigNumber(tx.value).dividedBy(1e8).toNumber()
}
const rawTxOutputs = await this.createRawTransaction([], outputs)
const rawTxFunded = await this.fundRawTransaction(rawTxOutputs)
const rawTxSigned = await this.signRawTransaction(rawTxFunded.hex)
return this.sendRawTransaction(rawTxSigned.hex)
}
async signRawTransaction (hexstring, prevtxs, privatekeys, sighashtype) {
return this.jsonrpc('signrawtransaction', hexstring, prevtxs, privatekeys)
}
async createRawTransaction (transactions, outputs) {
return this.jsonrpc('createrawtransaction', transactions, outputs)
}
async fundRawTransaction (hexstring) {
return this.jsonrpc('fundrawtransaction', hexstring)
}
}
BitcoinRpcProvider.version = version