├── .coveralls.yml ├── .travis.yml ├── .gitignore ├── LICENSE ├── package.json ├── README.md ├── lib └── index.js └── test └── index.js /.coveralls.yml: -------------------------------------------------------------------------------- 1 | repo_token: QwBzswlfN6Ip1yWdnRwZHaRgdBC440VcS -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - '0.10' 4 | before_install: 5 | - export DISPLAY=:99.0 6 | - sh -e /etc/init.d/xvfb start 7 | install: 8 | - npm install 9 | after_script: 10 | - npm run coverage 11 | - cat ./coverage/lcov.info | ./node_modules/.bin/coveralls 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # Compiled binary addons (http://nodejs.org/api/addons.html) 20 | build/Release 21 | 22 | # Dependency directory 23 | # Commenting this out is preferred by some people, see 24 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- 25 | node_modules 26 | 27 | # Users Environment Variables 28 | .lock-wscript 29 | 30 | # intelliJ project files 31 | .idea 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013-2018 BitPay, Inc. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bitcoind-rpc", 3 | "description": "Bitcoin Client Library to connect to Bitcoin Core via RPC", 4 | "version": "0.9.0", 5 | "author": { 6 | "name": "Stephen Pair", 7 | "email": "stephen@bitpay.com" 8 | }, 9 | "contributors": [ 10 | { 11 | "name": "Jeff Garzik", 12 | "email": "jgarzik@bitpay.com" 13 | }, 14 | { 15 | "name": "Manuel Araoz", 16 | "email": "manuelaraoz@gmail.com" 17 | }, 18 | { 19 | "name": "Matias Alejo Garcia", 20 | "email": "ematiu@gmail.com" 21 | }, 22 | { 23 | "name": "Braydon Fuller", 24 | "email": "braydon@bitpay.com" 25 | } 26 | ], 27 | "keywords": [ 28 | "bitcoin", 29 | "rpc" 30 | ], 31 | "repository": { 32 | "type": "git", 33 | "url": "https://github.com/bitpay/bitcoind-rpc" 34 | }, 35 | "license": "MIT", 36 | "main": "lib/index.js", 37 | "scripts": { 38 | "test": "node_modules/.bin/mocha test -R spec", 39 | "coverage": "node_modules/.bin/istanbul cover node_modules/.bin/_mocha -- --recursive" 40 | }, 41 | "devDependencies": { 42 | "async": "^0.9.0", 43 | "chai": "^1.10.0", 44 | "coveralls": "^2.11.2", 45 | "istanbul": "^0.4.5", 46 | "mocha": "^2.1.0", 47 | "sinon": "^1.12.2" 48 | }, 49 | "bugs": { 50 | "url": "https://github.com/bitpay/bitcoind-rpc/issues" 51 | }, 52 | "homepage": "https://github.com/bitpay/bitcoind-rpc" 53 | } 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | bitcoind-rpc.js 2 | =============== 3 | 4 | [![NPM Package](https://img.shields.io/npm/v/bitcoind-rpc.svg?style=flat-square)](https://www.npmjs.org/package/bitcoind-rpc) 5 | [![Build Status](https://img.shields.io/travis/bitpay/bitcoind-rpc.svg?branch=master&style=flat-square)](https://travis-ci.org/bitpay/bitcoind-rpc) 6 | [![Coverage Status](https://img.shields.io/coveralls/bitpay/bitcoind-rpc.svg?style=flat-square)](https://coveralls.io/r/bitpay/bitcoind-rpc?branch=master) 7 | 8 | A client library to connect to Bitcoin Core RPC in JavaScript. 9 | 10 | ## Get Started 11 | 12 | bitcoind-rpc.js runs on [node](http://nodejs.org/), and can be installed via [npm](https://npmjs.org/): 13 | 14 | ```bash 15 | npm install bitcoind-rpc 16 | ``` 17 | 18 | ## Examples 19 | 20 | ```javascript 21 | var run = function() { 22 | var bitcore = require('bitcore'); 23 | var RpcClient = require('bitcoind-rpc'); 24 | 25 | var config = { 26 | protocol: 'http', 27 | user: 'user', 28 | pass: 'pass', 29 | host: '127.0.0.1', 30 | port: '18332', 31 | }; 32 | 33 | // config can also be an url, e.g.: 34 | // var config = 'http://user:pass@127.0.0.1:18332'; 35 | 36 | var rpc = new RpcClient(config); 37 | 38 | var txids = []; 39 | 40 | function showNewTransactions() { 41 | rpc.getRawMemPool(function (err, ret) { 42 | if (err) { 43 | console.error(err); 44 | return setTimeout(showNewTransactions, 10000); 45 | } 46 | 47 | function batchCall() { 48 | ret.result.forEach(function (txid) { 49 | if (txids.indexOf(txid) === -1) { 50 | rpc.getRawTransaction(txid); 51 | } 52 | }); 53 | } 54 | 55 | rpc.batch(batchCall, function(err, rawtxs) { 56 | if (err) { 57 | console.error(err); 58 | return setTimeout(showNewTransactions, 10000); 59 | } 60 | 61 | rawtxs.map(function (rawtx) { 62 | var tx = new bitcore.Transaction(rawtx.result); 63 | console.log('\n\n\n' + tx.id + ':', tx.toObject()); 64 | }); 65 | 66 | txids = ret.result; 67 | setTimeout(showNewTransactions, 2500); 68 | }); 69 | }); 70 | } 71 | 72 | showNewTransactions(); 73 | }; 74 | ``` 75 | 76 | ## License 77 | 78 | **Code released under [the MIT license](https://github.com/bitpay/bitcore/blob/master/LICENSE).** 79 | 80 | Copyright 2013-2018 BitPay, Inc. 81 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var http = require('http'); 4 | var https = require('https'); 5 | var url = require('url'); 6 | 7 | function decodeURL(str) { 8 | var parsedUrl = url.parse(str); 9 | var hostname = parsedUrl.hostname; 10 | var port = parseInt(parsedUrl.port, 10); 11 | var protocol = parsedUrl.protocol; 12 | // strip trailing ":" 13 | protocol = protocol.substring(0, protocol.length - 1); 14 | var auth = parsedUrl.auth; 15 | var parts = auth.split(':'); 16 | var user = parts[0] ? decodeURIComponent(parts[0]) : null; 17 | var pass = parts[1] ? decodeURIComponent(parts[1]) : null; 18 | var opts = { 19 | host: hostname, 20 | port: port, 21 | protocol: protocol, 22 | user: user, 23 | pass: pass, 24 | }; 25 | return opts; 26 | } 27 | 28 | function RpcClient(opts) { 29 | // opts can ba an URL string 30 | if (typeof opts === 'string') { 31 | opts = decodeURL(opts); 32 | } 33 | opts = opts || {}; 34 | this.host = opts.host || '127.0.0.1'; 35 | this.port = opts.port || 8332; 36 | this.user = opts.user || 'user'; 37 | this.pass = opts.pass || 'pass'; 38 | this.protocol = opts.protocol === 'http' ? http : https; 39 | this.batchedCalls = null; 40 | this.disableAgent = opts.disableAgent || false; 41 | 42 | var isRejectUnauthorized = typeof opts.rejectUnauthorized !== 'undefined'; 43 | this.rejectUnauthorized = isRejectUnauthorized ? opts.rejectUnauthorized : true; 44 | 45 | if(RpcClient.config.log) { 46 | this.log = RpcClient.config.log; 47 | } else { 48 | this.log = RpcClient.loggers[RpcClient.config.logger || 'normal']; 49 | } 50 | 51 | } 52 | 53 | var cl = console.log.bind(console); 54 | 55 | var noop = function() {}; 56 | 57 | RpcClient.loggers = { 58 | none: {info: noop, warn: noop, err: noop, debug: noop}, 59 | normal: {info: cl, warn: cl, err: cl, debug: noop}, 60 | debug: {info: cl, warn: cl, err: cl, debug: cl} 61 | }; 62 | 63 | RpcClient.config = { 64 | logger: 'normal' // none, normal, debug 65 | }; 66 | 67 | function rpc(request, callback) { 68 | 69 | var self = this; 70 | request = JSON.stringify(request); 71 | 72 | var userInfo = this.user + ':' + this.pass; 73 | var buf = (Buffer.from && Buffer.from !== Uint8Array.from) ? Buffer.from(userInfo) : new Buffer(userInfo); 74 | this.auth = buf.toString('base64'); 75 | 76 | var options = { 77 | host: self.host, 78 | path: '/', 79 | method: 'POST', 80 | port: self.port, 81 | rejectUnauthorized: self.rejectUnauthorized, 82 | agent: self.disableAgent ? false : undefined 83 | }; 84 | 85 | if (self.httpOptions) { 86 | for (var k in self.httpOptions) { 87 | options[k] = self.httpOptions[k]; 88 | } 89 | } 90 | 91 | var called = false; 92 | 93 | var errorMessage = 'Bitcoin JSON-RPC: '; 94 | 95 | var req = this.protocol.request(options, function(res) { 96 | 97 | var buf = ''; 98 | res.on('data', function(data) { 99 | buf += data; 100 | }); 101 | 102 | res.on('end', function() { 103 | 104 | if (called) { 105 | return; 106 | } 107 | called = true; 108 | 109 | if (res.statusCode === 401) { 110 | callback(new Error(errorMessage + 'Connection Rejected: 401 Unnauthorized')); 111 | return; 112 | } 113 | if (res.statusCode === 403) { 114 | callback(new Error(errorMessage + 'Connection Rejected: 403 Forbidden')); 115 | return; 116 | } 117 | if (res.statusCode === 500 && buf.toString('utf8') === 'Work queue depth exceeded') { 118 | var exceededError = new Error('Bitcoin JSON-RPC: ' + buf.toString('utf8')); 119 | exceededError.code = 429; // Too many requests 120 | callback(exceededError); 121 | return; 122 | } 123 | 124 | var parsedBuf; 125 | try { 126 | parsedBuf = JSON.parse(buf); 127 | } catch(e) { 128 | self.log.err(e.stack); 129 | self.log.err(buf); 130 | self.log.err('HTTP Status code:' + res.statusCode); 131 | var err = new Error(errorMessage + 'Error Parsing JSON: ' + e.message); 132 | callback(err); 133 | return; 134 | } 135 | 136 | callback(parsedBuf.error, parsedBuf); 137 | 138 | }); 139 | }); 140 | 141 | req.on('error', function(e) { 142 | var err = new Error(errorMessage + 'Request Error: ' + e.message); 143 | if (!called) { 144 | called = true; 145 | callback(err); 146 | } 147 | }); 148 | 149 | req.setHeader('Content-Length', request.length); 150 | req.setHeader('Content-Type', 'application/json'); 151 | req.setHeader('Authorization', 'Basic ' + self.auth); 152 | req.write(request); 153 | req.end(); 154 | } 155 | 156 | RpcClient.prototype.batch = function(batchCallback, resultCallback) { 157 | this.batchedCalls = []; 158 | batchCallback(); 159 | rpc.call(this, this.batchedCalls, resultCallback); 160 | this.batchedCalls = null; 161 | }; 162 | 163 | RpcClient.callspec = { 164 | abandonTransaction: 'str', 165 | abortRescan: '', 166 | addMultiSigAddress: '', 167 | addNode: '', 168 | analyzePSBT: 'str', 169 | backupWallet: '', 170 | bumpFee: 'str', 171 | clearBanned: '', 172 | combinePSBT: 'obj', 173 | combineRawTransaction: 'obj', 174 | convertToPSBT: 'str', 175 | createMultiSig: '', 176 | createPSBT: 'obj', 177 | createRawTransaction: 'obj obj', 178 | createWallet: 'str', 179 | decodePSBT: 'str', 180 | decodeScript: 'str', 181 | decodeRawTransaction: '', 182 | deriveAddresses: 'str', 183 | disconnectNode: '', 184 | dumpPrivKey: '', 185 | dumpWallet: 'str', 186 | encryptWallet: '', 187 | enumerateSigners: '', 188 | estimateFee: '', // deprecated 189 | estimateSmartFee: 'int str', 190 | estimatePriority: 'int', // deprecated 191 | generate: 'int', // deprecated 192 | generateBlock: 'str obj', 193 | generateToAddress: 'int str', 194 | generateToDescriptor: 'int str', 195 | getAccount: '', // deprecated 196 | getAccountAddress: 'str', // deprecated 197 | getAddedNodeInfo: '', 198 | getAddressMempool: 'obj', // deprecated 199 | getAddressUtxos: 'obj', // deprecated 200 | getAddressBalance: 'obj', // deprecated 201 | getAddressDeltas: 'obj', // deprecated 202 | getAddressesByLabel: 'str', 203 | getAddressInfo: 'str', 204 | getAddressTxids: 'obj', // deprecated 205 | getAddressesByAccount: '', // deprecated 206 | getBalance: 'str int', 207 | getBalances: '', 208 | getBestBlockHash: '', 209 | getBlockDeltas: 'str', // deprecated 210 | getBlock: 'str int', 211 | getBlockchainInfo: '', 212 | getBlockCount: '', 213 | getBlockFilter: 'str', 214 | getBlockHashes: 'int int obj', // deprecated 215 | getBlockHash: 'int', 216 | getBlockHeader: 'str', 217 | getBlockNumber: '', // deprecated 218 | getBlockStats: 'str', 219 | getBlockTemplate: '', 220 | getConnectionCount: '', 221 | getChainTips: '', 222 | getChainTxStats: '', 223 | getDescriptorInfo: 'str', 224 | getDifficulty: '', 225 | getGenerate: '', // deprecated 226 | getHashesPerSec: '', // deprecated 227 | getIndexInfo: '', 228 | getInfo: '', // deprecated 229 | getMemoryInfo: '', 230 | getMemoryPool: '', // deprecated 231 | getMemPoolAncestors: 'str', 232 | getMemPoolDescendants: 'str', 233 | getMemPoolEntry: 'str', 234 | getMemPoolInfo: '', 235 | getMiningInfo: '', 236 | getNetTotals: '', 237 | getNetworkHashPS: '', 238 | getNetworkInfo: '', 239 | getNewAddress: 'str str', 240 | getNodeAddresses: '', 241 | getPeerInfo: '', 242 | getRawChangeAddress: '', 243 | getRawMemPool: 'bool', 244 | getRawTransaction: 'str int', 245 | getReceivedByAccount: 'str int', // deprecated 246 | getReceivedByAddress: 'str int', 247 | getReceivedByLabel: 'str', 248 | getRpcInfo: '', 249 | getSpentInfo: 'obj', 250 | getTransaction: '', 251 | getTxOut: 'str int bool', 252 | getTxOutProof: '', 253 | getTxOutSetInfo: '', 254 | getUnconfirmedBalance: '', 255 | getWalletInfo: '', 256 | getWork: '', 257 | getZmqNotifications: '', 258 | finalizePSBT: 'str', 259 | fundRawTransaction: 'str', 260 | help: '', 261 | importAddress: 'str str bool', 262 | importDescriptors: 'str', 263 | importMulti: 'obj obj', 264 | importPrivKey: 'str str bool', 265 | importPrunedFunds: 'str, str', 266 | importPubKey: 'str', 267 | importWallet: 'str', 268 | invalidateBlock: 'str', 269 | joinPSBTs: 'obj', 270 | keyPoolRefill: '', 271 | listAccounts: 'int', 272 | listAddressGroupings: '', 273 | listBanned: '', 274 | listDescriptors: '', 275 | listLabels: '', 276 | listLockUnspent: 'bool', 277 | listReceivedByAccount: 'int bool', 278 | listReceivedByAddress: 'int bool', 279 | listReceivedByLabel: '', 280 | listSinceBlock: 'str int', 281 | listTransactions: 'str int int', 282 | listUnspent: 'int int', 283 | listWalletDir: '', 284 | listWallets: '', 285 | loadWallet: 'str', 286 | lockUnspent: '', 287 | logging: '', 288 | move: 'str str float int str', 289 | ping: '', 290 | preciousBlock: 'str', 291 | prioritiseTransaction: 'str float int', 292 | pruneBlockChain: 'int', 293 | psbtBumpFee: 'str', 294 | removePrunedFunds: 'str', 295 | reScanBlockChain: '', 296 | saveMemPool: '', 297 | send: 'obj', 298 | setHDSeed: '', 299 | setLabel: 'str str', 300 | setWalletFlag: 'str', 301 | scanTxOutSet: 'str', 302 | sendFrom: 'str str float int str str', 303 | sendMany: 'str obj int str', //not sure this is will work 304 | sendRawTransaction: 'str', 305 | sendToAddress: 'str float str str', 306 | setAccount: '', 307 | setBan: 'str str', 308 | setNetworkActive: 'bool', 309 | setGenerate: 'bool int', 310 | setTxFee: 'float', 311 | signMessage: '', 312 | signMessageWithPrivKey: 'str str', 313 | signRawTransaction: '', 314 | signRawTransactionWithKey: 'str obj', 315 | signRawTransactionWithWallet: 'str', 316 | stop: '', 317 | submitBlock: 'str', 318 | submitHeader: 'str', 319 | testMemPoolAccept: 'obj', 320 | unloadWallet: '', 321 | upgradeWallet: '', 322 | uptime: '', 323 | utxoUpdatePSBT: 'str', 324 | validateAddress: '', 325 | verifyChain: '', 326 | verifyMessage: '', 327 | verifyTxOutProof: 'str', 328 | walletCreateFundedPSBT: '', 329 | walletDisplayAddress: 'str', 330 | walletLock: '', 331 | walletPassPhrase: 'string int', 332 | walletPassphraseChange: '', 333 | walletProcessPSBT: 'str' 334 | }; 335 | 336 | var slice = function(arr, start, end) { 337 | return Array.prototype.slice.call(arr, start, end); 338 | }; 339 | 340 | function generateRPCMethods(constructor, apiCalls, rpc) { 341 | 342 | function createRPCMethod(methodName, argMap) { 343 | return function() { 344 | 345 | var limit = arguments.length - 1; 346 | 347 | if (this.batchedCalls) { 348 | limit = arguments.length; 349 | } 350 | 351 | for (var i = 0; i < limit; i++) { 352 | if(argMap[i]) { 353 | arguments[i] = argMap[i](arguments[i]); 354 | } 355 | } 356 | 357 | if (this.batchedCalls) { 358 | this.batchedCalls.push({ 359 | jsonrpc: '2.0', 360 | method: methodName, 361 | params: slice(arguments), 362 | id: getRandomId() 363 | }); 364 | } else { 365 | rpc.call(this, { 366 | method: methodName, 367 | params: slice(arguments, 0, arguments.length - 1), 368 | id: getRandomId() 369 | }, arguments[arguments.length - 1]); 370 | } 371 | 372 | }; 373 | }; 374 | 375 | var types = { 376 | str: function(arg) { 377 | return arg.toString(); 378 | }, 379 | int: function(arg) { 380 | return parseFloat(arg); 381 | }, 382 | float: function(arg) { 383 | return parseFloat(arg); 384 | }, 385 | bool: function(arg) { 386 | return (arg === true || arg == '1' || arg == 'true' || arg.toString().toLowerCase() == 'true'); 387 | }, 388 | obj: function(arg) { 389 | if(typeof arg === 'string') { 390 | return JSON.parse(arg); 391 | } 392 | return arg; 393 | } 394 | }; 395 | 396 | for(var k in apiCalls) { 397 | var spec = []; 398 | if (apiCalls[k].length) { 399 | spec = apiCalls[k].split(' '); 400 | for (var i = 0; i < spec.length; i++) { 401 | if(types[spec[i]]) { 402 | spec[i] = types[spec[i]]; 403 | } else { 404 | spec[i] = types.str; 405 | } 406 | } 407 | } 408 | var methodName = k.toLowerCase(); 409 | constructor.prototype[k] = createRPCMethod(methodName, spec); 410 | constructor.prototype[methodName] = constructor.prototype[k]; 411 | } 412 | 413 | } 414 | 415 | function getRandomId() { 416 | return parseInt(Math.random() * 100000); 417 | } 418 | 419 | generateRPCMethods(RpcClient, RpcClient.callspec, rpc); 420 | 421 | module.exports = RpcClient; 422 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var chai = require('chai'); 4 | var RpcClient = require('../'); 5 | var util = require('util'); 6 | var EventEmitter = require('events').EventEmitter; 7 | var sinon = require('sinon'); 8 | var should = chai.should(); 9 | var http = require('http'); 10 | var https = require('https'); 11 | var async = require('async'); 12 | 13 | if(!setImmediate) setImmediate = setTimeout; 14 | 15 | describe('RpcClient', function() { 16 | 17 | it('should initialize the main object', function() { 18 | should.exist(RpcClient); 19 | }); 20 | 21 | it('should be able to create instance', function() { 22 | var s = new RpcClient(); 23 | should.exist(s); 24 | }); 25 | 26 | it('default to rejectUnauthorized as true', function() { 27 | var s = new RpcClient(); 28 | should.exist(s); 29 | s.rejectUnauthorized.should.equal(true); 30 | }); 31 | 32 | it('should be able to define a custom logger', function() { 33 | var customLogger = { 34 | info: function(){}, 35 | warn: function(){}, 36 | err: function(){}, 37 | debug: function(){} 38 | }; 39 | RpcClient.config.log = customLogger; 40 | var s = new RpcClient(); 41 | s.log.should.equal(customLogger); 42 | RpcClient.config.log = false; 43 | }); 44 | 45 | it('should be able to define the logger to normal', function() { 46 | RpcClient.config.logger = 'normal'; 47 | var s = new RpcClient(); 48 | s.log.should.equal(RpcClient.loggers.normal); 49 | }); 50 | 51 | it('should be able to define the logger to none', function() { 52 | RpcClient.config.logger = 'none'; 53 | var s = new RpcClient(); 54 | s.log.should.equal(RpcClient.loggers.none); 55 | }); 56 | 57 | function FakeResponse(){ 58 | EventEmitter.call(this); 59 | } 60 | util.inherits(FakeResponse, EventEmitter); 61 | 62 | function FakeRequest(){ 63 | EventEmitter.call(this); 64 | return this; 65 | } 66 | util.inherits(FakeRequest, EventEmitter); 67 | FakeRequest.prototype.setHeader = function() {}; 68 | FakeRequest.prototype.write = function(data) { 69 | this.data = data; 70 | }; 71 | FakeRequest.prototype.end = function() {}; 72 | 73 | it('should use https', function() { 74 | 75 | var client = new RpcClient({ 76 | user: 'user', 77 | pass: 'pass', 78 | port: 8332, 79 | }); 80 | client.protocol.should.equal(https); 81 | 82 | }); 83 | 84 | it('should use http', function() { 85 | 86 | var client = new RpcClient({ 87 | user: 'user', 88 | pass: 'pass', 89 | host: 'localhost', 90 | port: 8332, 91 | protocol: 'http' 92 | }); 93 | client.protocol.should.equal(http); 94 | 95 | }); 96 | 97 | it('should accept URL', function() { 98 | var client = new RpcClient('http://abc:def@ghi.xyz:1337'); 99 | client.protocol.should.equal(http); 100 | client.host.should.equal('ghi.xyz'); 101 | client.port.should.equal(1337); 102 | client.user.should.equal('abc'); 103 | client.pass.should.equal('def'); 104 | }); 105 | 106 | it('should call a method and receive response', function(done) { 107 | 108 | var client = new RpcClient({ 109 | user: 'user', 110 | pass: 'pass', 111 | host: 'localhost', 112 | port: 8332, 113 | rejectUnauthorized: true, 114 | disableAgent: true 115 | }); 116 | 117 | var requestStub = sinon.stub(client.protocol, 'request', function(options, callback){ 118 | var res = new FakeResponse(); 119 | var req = new FakeRequest(); 120 | setImmediate(function(){ 121 | res.emit('data', '{}'); 122 | res.emit('end'); 123 | }); 124 | callback(res); 125 | return req; 126 | }); 127 | 128 | client.setTxFee(0.01, function(error, parsedBuf) { 129 | requestStub.restore(); 130 | should.not.exist(error); 131 | should.exist(parsedBuf); 132 | done(); 133 | }); 134 | 135 | }); 136 | 137 | it('accept many values for bool', function(done) { 138 | 139 | var client = new RpcClient({ 140 | user: 'user', 141 | pass: 'pass', 142 | host: 'localhost', 143 | port: 8332, 144 | rejectUnauthorized: true, 145 | disableAgent: false 146 | }); 147 | 148 | var requestStub = sinon.stub(client.protocol, 'request', function(options, callback){ 149 | var res = new FakeResponse(); 150 | var req = new FakeRequest(); 151 | setImmediate(function(){ 152 | res.emit('data', req.data); 153 | res.emit('end'); 154 | }); 155 | callback(res); 156 | return req; 157 | }); 158 | 159 | async.eachSeries([true, 'true', 1, '1', 'True'], function(i, next) { 160 | client.importAddress('n28S35tqEMbt6vNad7A5K3mZ7vdn8dZ86X', '', i, function(error, parsedBuf) { 161 | should.not.exist(error); 162 | should.exist(parsedBuf); 163 | parsedBuf.params[2].should.equal(true); 164 | next(); 165 | }); 166 | }, function(err) { 167 | requestStub.restore(); 168 | done(); 169 | }); 170 | 171 | }); 172 | 173 | it('should process object arguments', function(done) { 174 | 175 | var client = new RpcClient({ 176 | user: 'user', 177 | pass: 'pass', 178 | host: 'localhost', 179 | port: 8332, 180 | rejectUnauthorized: true, 181 | disableAgent: false 182 | }); 183 | 184 | var requestStub = sinon.stub(client.protocol, 'request', function(options, callback){ 185 | var res = new FakeResponse(); 186 | var req = new FakeRequest(); 187 | setImmediate(function(){ 188 | res.emit('data', req.data); 189 | res.emit('end'); 190 | }); 191 | callback(res); 192 | return req; 193 | }); 194 | 195 | var obj = {'n28S35tqEMbt6vNad7A5K3mZ7vdn8dZ86X': 1}; 196 | async.eachSeries([obj, JSON.stringify(obj)], function(i, next) { 197 | client.sendMany('account', i, function(error, parsedBuf) { 198 | should.not.exist(error); 199 | should.exist(parsedBuf); 200 | parsedBuf.params[1].should.have.property('n28S35tqEMbt6vNad7A5K3mZ7vdn8dZ86X', 1); 201 | next(); 202 | }); 203 | }, function(err) { 204 | requestStub.restore(); 205 | done(); 206 | }); 207 | 208 | }); 209 | 210 | it('should batch calls for a method and receive a response', function(done) { 211 | 212 | var client = new RpcClient({ 213 | user: 'user', 214 | pass: 'pass', 215 | host: 'localhost', 216 | port: 8332, 217 | rejectUnauthorized: true, 218 | disableAgent: false 219 | }); 220 | 221 | var requestStub = sinon.stub(client.protocol, 'request', function(options, callback){ 222 | var res = new FakeResponse(); 223 | setImmediate(function(){ 224 | res.emit('data', '[{}, {}, {}]'); 225 | res.emit('end'); 226 | }); 227 | callback(res); 228 | return new FakeRequest(); 229 | }); 230 | 231 | client.batchedCalls = []; 232 | client.listReceivedByAccount(1, true); 233 | client.listReceivedByAccount(2, true); 234 | client.listReceivedByAccount(3, true); 235 | client.batchedCalls.length.should.equal(3); 236 | client.batch(function(){ 237 | // batch started 238 | }, function(error, result){ 239 | // batch ended 240 | requestStub.restore(); 241 | should.not.exist(error); 242 | should.exist(result); 243 | result.length.should.equal(3); 244 | done(); 245 | }); 246 | 247 | }); 248 | 249 | it('should handle connection rejected 401 unauthorized', function(done) { 250 | 251 | var client = new RpcClient({ 252 | user: 'user', 253 | pass: 'pass', 254 | host: 'localhost', 255 | port: 8332, 256 | rejectUnauthorized: true, 257 | disableAgent: true 258 | }); 259 | 260 | var requestStub = sinon.stub(client.protocol, 'request', function(options, callback){ 261 | var res = new FakeResponse(); 262 | res.statusCode = 401; 263 | setImmediate(function(){ 264 | res.emit('end'); 265 | }); 266 | callback(res); 267 | return new FakeRequest(); 268 | }); 269 | 270 | client.getBalance('n28S35tqEMbt6vNad7A5K3mZ7vdn8dZ86X', 6, function(error, parsedBuf) { 271 | requestStub.restore(); 272 | should.exist(error); 273 | error.message.should.equal('Bitcoin JSON-RPC: Connection Rejected: 401 Unnauthorized'); 274 | done(); 275 | }); 276 | 277 | }); 278 | 279 | it('should handle connection rejected 401 forbidden', function(done) { 280 | 281 | var client = new RpcClient({ 282 | user: 'user', 283 | pass: 'pass', 284 | host: 'localhost', 285 | port: 8332, 286 | rejectUnauthorized: true, 287 | disableAgent: true 288 | }); 289 | 290 | var requestStub = sinon.stub(client.protocol, 'request', function(options, callback){ 291 | var res = new FakeResponse(); 292 | res.statusCode = 403; 293 | setImmediate(function(){ 294 | res.emit('end'); 295 | }); 296 | callback(res); 297 | return new FakeRequest(); 298 | }); 299 | 300 | client.getDifficulty(function(error, parsedBuf) { 301 | requestStub.restore(); 302 | should.exist(error); 303 | error.message.should.equal('Bitcoin JSON-RPC: Connection Rejected: 403 Forbidden'); 304 | done(); 305 | }); 306 | 307 | }); 308 | 309 | it('should handle 500 work limit exceeded error', function(done) { 310 | 311 | var client = new RpcClient({ 312 | user: 'user', 313 | pass: 'pass', 314 | host: 'localhost', 315 | port: 8332, 316 | rejectUnauthorized: true, 317 | disableAgent: true 318 | }); 319 | 320 | var requestStub = sinon.stub(client.protocol, 'request', function(options, callback){ 321 | var res = new FakeResponse(); 322 | res.statusCode = 500; 323 | setImmediate(function(){ 324 | res.emit('data', 'Work queue depth exceeded'); 325 | res.emit('end'); 326 | }); 327 | callback(res); 328 | return new FakeRequest(); 329 | }); 330 | 331 | client.getDifficulty(function(error, parsedBuf) { 332 | requestStub.restore(); 333 | should.exist(error); 334 | error.message.should.equal('Bitcoin JSON-RPC: Work queue depth exceeded'); 335 | done(); 336 | }); 337 | 338 | }); 339 | 340 | it('should handle EPIPE error case 1', function(done) { 341 | 342 | var client = new RpcClient({ 343 | user: 'user', 344 | pass: 'pass', 345 | host: 'localhost', 346 | port: 8332, 347 | rejectUnauthorized: true, 348 | disableAgent: true 349 | }); 350 | 351 | var requestStub = sinon.stub(client.protocol, 'request', function(options, callback){ 352 | var req = new FakeRequest(); 353 | setImmediate(function(){ 354 | req.emit('error', new Error('write EPIPE')); 355 | }); 356 | var res = new FakeResponse(); 357 | setImmediate(function(){ 358 | res.emit('data', '{}'); 359 | res.emit('end'); 360 | }); 361 | callback(res); 362 | return req; 363 | }); 364 | 365 | client.getDifficulty(function(error, parsedBuf) { 366 | requestStub.restore(); 367 | should.exist(error); 368 | error.message.should.equal('Bitcoin JSON-RPC: Request Error: write EPIPE'); 369 | done(); 370 | }); 371 | 372 | }); 373 | 374 | it('should handle EPIPE error case 2', function(done) { 375 | 376 | var client = new RpcClient({ 377 | user: 'user', 378 | pass: 'pass', 379 | host: 'localhost', 380 | port: 8332, 381 | rejectUnauthorized: true, 382 | disableAgent: true 383 | }); 384 | 385 | var requestStub = sinon.stub(client.protocol, 'request', function(options, callback){ 386 | var res = new FakeResponse(); 387 | setImmediate(function(){ 388 | res.emit('data', '{}'); 389 | res.emit('end'); 390 | }); 391 | var req = new FakeRequest(); 392 | setImmediate(function(){ 393 | req.emit('error', new Error('write EPIPE')); 394 | }); 395 | callback(res); 396 | req.on('error', function(err) { 397 | requestStub.restore(); 398 | done(); 399 | }); 400 | return req; 401 | }); 402 | 403 | client.getDifficulty(function(error, parsedBuf) {}); 404 | 405 | }); 406 | 407 | it('should handle ECONNREFUSED error', function(done) { 408 | 409 | var client = new RpcClient({ 410 | user: 'user', 411 | pass: 'pass', 412 | host: 'localhost', 413 | port: 8332, 414 | rejectUnauthorized: true, 415 | disableAgent: true 416 | }); 417 | 418 | var requestStub = sinon.stub(client.protocol, 'request', function(options, callback){ 419 | var res = new FakeResponse(); 420 | var req = new FakeRequest(); 421 | setImmediate(function(){ 422 | req.emit('error', new Error('connect ECONNREFUSED')); 423 | }); 424 | callback(res); 425 | return req; 426 | }); 427 | 428 | client.getDifficulty(function(error, parsedBuf) { 429 | requestStub.restore(); 430 | should.exist(error); 431 | error.message.should.equal('Bitcoin JSON-RPC: Request Error: connect ECONNREFUSED'); 432 | done(); 433 | }); 434 | 435 | }); 436 | 437 | it('should callback with error if invalid json', function(done) { 438 | 439 | var client = new RpcClient({ 440 | user: 'user', 441 | pass: 'pass', 442 | host: 'localhost', 443 | port: 8332, 444 | rejectUnauthorized: true, 445 | disableAgent: true 446 | }); 447 | 448 | var requestStub = sinon.stub(client.protocol, 'request', function(options, callback){ 449 | var res = new FakeResponse(); 450 | setImmediate(function(){ 451 | res.emit('data', 'not a json string'); 452 | res.emit('end'); 453 | }); 454 | var req = new FakeRequest(); 455 | callback(res); 456 | return req; 457 | }); 458 | 459 | client.getDifficulty(function(error, parsedBuf) { 460 | requestStub.restore(); 461 | should.exist(error); 462 | error.message.should.equal('Bitcoin JSON-RPC: Error Parsing JSON: Unexpected token o in JSON at position 1'); 463 | done(); 464 | }); 465 | 466 | }); 467 | 468 | it('should callback with error if blank response', function(done) { 469 | 470 | var client = new RpcClient({ 471 | user: 'user', 472 | pass: 'pass', 473 | host: 'localhost', 474 | port: 8332, 475 | rejectUnauthorized: true, 476 | disableAgent: true 477 | }); 478 | 479 | var requestStub = sinon.stub(client.protocol, 'request', function(options, callback){ 480 | var res = new FakeResponse(); 481 | setImmediate(function(){ 482 | res.emit('data', ''); 483 | res.emit('end'); 484 | }); 485 | var req = new FakeRequest(); 486 | callback(res); 487 | return req; 488 | }); 489 | 490 | client.getDifficulty(function(error, parsedBuf) { 491 | requestStub.restore(); 492 | should.exist(error); 493 | error.message.should.equal('Bitcoin JSON-RPC: Error Parsing JSON: Unexpected end of JSON input'); 494 | done(); 495 | }); 496 | 497 | }); 498 | 499 | it('should add additional http options', function(done) { 500 | 501 | var client = new RpcClient({ 502 | user: 'user', 503 | pass: 'pass', 504 | host: 'localhost', 505 | port: 8332, 506 | rejectUnauthorized: true, 507 | disableAgent: true 508 | }); 509 | 510 | client.httpOptions = { 511 | port: 20001 512 | }; 513 | 514 | var calledPort = false; 515 | 516 | var requestStub = sinon.stub(client.protocol, 'request', function(options, callback){ 517 | calledPort = options.port; 518 | var res = new FakeResponse(); 519 | setImmediate(function(){ 520 | res.emit('data', '{}'); 521 | res.emit('end'); 522 | }); 523 | var req = new FakeRequest(); 524 | callback(res); 525 | return req; 526 | }); 527 | 528 | client.getDifficulty(function(error, parsedBuf) { 529 | should.not.exist(error); 530 | should.exist(parsedBuf); 531 | calledPort.should.equal(20001); 532 | requestStub.restore(); 533 | done(); 534 | }); 535 | 536 | }); 537 | 538 | }); 539 | --------------------------------------------------------------------------------