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 |
|
/**
* Module dependencies.
*/
import Parser from './parser';
import Promise from 'bluebird';
import Requester from './requester';
import _ from 'lodash';
import debugnyan from 'debugnyan';
import methods from './methods';
import requestLogger from './logging/request-logger';
import semver from 'semver';
/**
* Source arguments to find out if a callback has been passed.
*/
function source(...args) {
const last = _.last(args);
let callback;
if (_.isFunction(last)) {
callback = last;
args = _.dropRight(args);
}
return [args, callback];
}
/**
* List of networks and their default port mapping.
*/
const networks = {
mainnet: 8332,
regtest: 18332,
testnet: 18332
};
/**
* Constructor.
*/
class Client {
constructor({
agentOptions,
headers = false,
host = 'localhost',
logger = debugnyan('bitcoin-core'),
network = 'mainnet',
password,
port,
ssl = false,
timeout = 30000,
username,
version,
wallet
} = {}) {
if (!_.has(networks, network)) {
throw new Error(`Invalid network name "${network}"`, { network });
}
this.agentOptions = agentOptions;
this.auth = (password || username) && { pass: password, user: username };
this.headers = headers;
this.host = host;
this.password = password;
this.port = port || networks[network];
this.timeout = timeout;
this.ssl = {
enabled: _.get(ssl, 'enabled', ssl),
strict: _.get(ssl, 'strict', _.get(ssl, 'enabled', ssl))
};
this.wallet = wallet;
this.version = version;
this.methods = _.transform(methods, (result, method, name) => {
result[_.toLower(name)] = {
features: _.transform(method.features, (result, constraint, name) => {
result[name] = {
supported: version ? semver.satisfies(version, constraint) : true
};
}, {}),
supported: version ? semver.satisfies(version, method.version) : true
};
}, {});
const request = requestLogger(logger);
this.request = Promise.promisifyAll(request.defaults({
agentOptions: this.agentOptions,
baseUrl: `${this.ssl.enabled ? 'https' : 'http'}://${this.host}:${this.port}`,
json: true,
strictSSL: this.ssl.strict,
timeout: this.timeout
}), { multiArgs: true });
this.requester = new Requester({ methods: this.methods, version });
this.parser = new Parser({ headers: this.headers });
}
/**
* Execute `rpc` command.
*/
command(...args) {
let body;
let callback;
let multiwallet;
let [input, ...parameters] = args; // eslint-disable-line prefer-const
const lastArg = _.last(parameters);
const isBatch = Array.isArray(input);
if (_.isFunction(lastArg)) {
callback = lastArg;
parameters = _.dropRight(parameters);
}
if (isBatch) {
multiwallet = _.some(input, command => {
return _.get(this.methods[command.method], 'features.multiwallet.supported', false) === true;
});
body = input.map((method, index) => this.requester.prepare({
method: method.method,
parameters: method.parameters,
suffix: index
}));
} else {
multiwallet = _.get(this.methods[input], 'features.multiwallet.supported', false) === true;
body = this.requester.prepare({ method: input, parameters });
}
return Promise.try(() => {
return this.request.postAsync({
auth: _.pickBy(this.auth, _.identity),
body: JSON.stringify(body),
json: false,
uri: `${multiwallet && this.wallet ? `/wallet/${this.wallet}` : '/'}`
})
.bind(this)
.then(this.parser.rpc);
}).asCallback(callback);
}
/**
* Given a transaction hash, returns a transaction in binary, hex-encoded binary, or JSON formats.
*/
getTransactionByHash(...args) {
const [[hash, { extension = 'json' } = {}], callback] = source(...args);
return Promise.try(() => {
return this.request.getAsync(`/rest/tx/${hash}.${extension}`)
.bind(this)
.then(this.parser.rest);
}).asCallback(callback);
}
/**
* Given a block hash, returns a block, in binary, hex-encoded binary or JSON formats.
* With `summary` set to `false`, the JSON response will only contain the transaction
* hash instead of the complete transaction details. The option only affects the JSON response.
*/
getBlockByHash(...args) {
const [[hash, { summary = false, extension = 'json' } = {}], callback] = source(...args);
return Promise.try(() => {
return this.request.getAsync(`/rest/block${summary ? '/notxdetails/' : '/'}${hash}.${extension}`)
.bind(this)
.then(this.parser.rest);
}).asCallback(callback);
}
/**
* Given a block hash, returns amount of blockheaders in upward direction.
*/
getBlockHeadersByHash(...args) {
const [[hash, count, { extension = 'json' } = {}], callback] = source(...args);
return Promise.try(() => {
if (!_.includes(['bin', 'hex'], extension)) {
throw new Error(`Extension "${extension}" is not supported`);
}
return this.request.getAsync(`/rest/headers/${count}/${hash}.${extension}`)
.bind(this)
.then(this.parser.rest);
}).asCallback(callback);
}
/**
* Returns various state info regarding block chain processing.
* Only supports JSON as output format.
*/
getBlockchainInformation(...args) {
const [, callback] = source(...args);
return this.request.getAsync(`/rest/chaininfo.json`)
.bind(this)
.then(this.parser.rest)
.asCallback(callback);
}
/**
* Query unspent transaction outputs for a given set of outpoints.
* See BIP64 for input and output serialisation:
* - https://github.com/bitcoin/bips/blob/master/bip-0064.mediawiki
*/
getUnspentTransactionOutputs(...args) {
const [[outpoints, { extension = 'json' } = {}], callback] = source(...args);
const sets = _.flatten([outpoints]).map(outpoint => {
return `${outpoint.id}-${outpoint.index}`;
}).join('/');
return this.request.getAsync(`/rest/getutxos/checkmempool/${sets}.${extension}`)
.bind(this)
.then(this.parser.rest)
.asCallback(callback);
}
/**
* Returns transactions in the transaction memory pool.
* Only supports JSON as output format.
*/
getMemoryPoolContent(...args) {
const [, callback] = source(...args);
return this.request.getAsync('/rest/mempool/contents.json')
.bind(this)
.then(this.parser.rest)
.asCallback(callback);
}
/**
* Returns various information about the transaction memory pool.
* Only supports JSON as output format.
*
* - size: the number of transactions in the transaction memory pool.
* - bytes: size of the transaction memory pool in bytes.
* - usage: total transaction memory pool memory usage.
*/
getMemoryPoolInformation(...args) {
const [, callback] = source(...args);
return this.request.getAsync('/rest/mempool/info.json')
.bind(this)
.then(this.parser.rest)
.asCallback(callback);
}
}
/**
* Add all known RPC methods.
*/
_.forOwn(methods, (options, method) => {
Client.prototype[method] = _.partial(Client.prototype.command, method.toLowerCase());
});
/**
* Export Client class.
*/
export default Client;
|