Merge branch 'master' of github.com:bitpay/bitcore into clean

Conflicts:
	examples/PeerManager.js
	examples/SendTx.js
	lib/Connection.js
	lib/PeerManager.js
This commit is contained in:
Eric Martindale 2014-04-17 16:38:30 -04:00
commit 0ae2fc73ab
10 changed files with 342 additions and 227 deletions

159
README.md
View File

@ -8,6 +8,7 @@ A pure, powerful core for your bitcoin project.
Bitcore is a complete, native interface to the Bitcoin network, and provides the core functionality needed to develop apps for bitcoin. Bitcore is a complete, native interface to the Bitcoin network, and provides the core functionality needed to develop apps for bitcoin.
#Principles #Principles
Bitcoin is a powerful new peer-to-peer platform for the next generation of financial technology. The decentralized nature of the Bitcoin network allows for highly resilient bitcoin infrastructure, and the developer community needs reliable, open-source tools to implement bitcoin apps and services. Bitcoin is a powerful new peer-to-peer platform for the next generation of financial technology. The decentralized nature of the Bitcoin network allows for highly resilient bitcoin infrastructure, and the developer community needs reliable, open-source tools to implement bitcoin apps and services.
**Bitcore unchains developers from fallible, centralized APIs, and provides the tools to interact with the real Bitcoin network.** **Bitcore unchains developers from fallible, centralized APIs, and provides the tools to interact with the real Bitcoin network.**
@ -15,11 +16,13 @@ Bitcoin is a powerful new peer-to-peer platform for the next generation of finan
#Get Started #Get Started
Bitcore runs on [node](http://nodejs.org/), and can be installed via [npm](https://npmjs.org/): Bitcore runs on [node](http://nodejs.org/), and can be installed via [npm](https://npmjs.org/):
``` ```
npm install bitcore npm install bitcore
``` ```
It is a collection of objects useful to bitcoin applications; class-like idioms are enabled via [Soop](https://github.com/bitpay/soop). In most cases, a developer will require the object's class directly. For instance: It is a collection of objects useful to bitcoin applications; class-like idioms are enabled via [Soop](https://github.com/bitpay/soop). In most cases, a developer will require the object's class directly. For instance:
``` ```
var bitcore = require('bitcore'); var bitcore = require('bitcore');
var Address = bitcore.Address; var Address = bitcore.Address;
@ -32,7 +35,9 @@ var PeerManager = bitcore.PeerManager;
Some examples are provided at the [examples](/examples) path. Here are some snippets: Some examples are provided at the [examples](/examples) path. Here are some snippets:
## Validating an address ## Validating an address
Validating a Bitcoin address: Validating a Bitcoin address:
```js ```js
var bitcore = require('bitcore'); var bitcore = require('bitcore');
var Address = bitcore.Address; var Address = bitcore.Address;
@ -51,15 +56,15 @@ addrs.forEach(function(addr) {
console.log(addr.data + ' is ' + (valid ? '' : 'not ') + 'valid'); console.log(addr.data + ' is ' + (valid ? '' : 'not ') + 'valid');
}); });
``` ```
## Monitoring Blocks and Transactions ## Monitoring Blocks and Transactions
For this example you need a running bitcoind instance with RPC enabled. For this example you need a running bitcoind instance with RPC enabled.
```js ```js
var bitcore = require('bitcore'); var bitcore = require('../bitcore');
var networks = bitcore.networks;
var Peer = bitcore.Peer; var Peer = bitcore.Peer;
var PeerManager = require('soop').load('../PeerManager', { var PeerManager = bitcore.PeerManager;
network: networks.testnet
});
var handleBlock = function(info) { var handleBlock = function(info) {
console.log('** Block Received **'); console.log('** Block Received **');
@ -81,7 +86,9 @@ var handleInv = function(info) {
info.conn.sendGetData(invs); info.conn.sendGetData(invs);
}; };
var peerman = new PeerManager(); var peerman = new PeerManager({
network: 'testnet'
});
peerman.addPeer(new Peer('127.0.0.1', 18333)); peerman.addPeer(new Peer('127.0.0.1', 18333));
@ -96,9 +103,10 @@ peerman.start();
PeerManager will emit the following events: 'version', 'verack', 'addr', 'getaddr', 'error' 'disconnect'; and will relay events like: 'tx', 'block', 'inv'. Please see [PeerManager.js](PeerManager.js), [Peer.js](Peer.js) and [Connection.js](Connection.js) PeerManager will emit the following events: 'version', 'verack', 'addr', 'getaddr', 'error' 'disconnect'; and will relay events like: 'tx', 'block', 'inv'. Please see [PeerManager.js](PeerManager.js), [Peer.js](Peer.js) and [Connection.js](Connection.js)
## Consuming bitcoind RPC ## Consuming bitcoind RPC
For this example you need a running bitcoind instance with RPC enabled. For this example you need a running bitcoind instance with RPC enabled.
```js ```js
var bitcore = require('bitcore'); var bitcore = require('bitcore');
var RpcClient = bitcore.RpcClient; var RpcClient = bitcore.RpcClient;
@ -123,98 +131,113 @@ rpc.getBlock(hash, function(err, ret) {
console.log(ret); console.log(ret);
}); });
``` ```
Check the list of all supported RPC call at [RpcClient.js](RpcClient.js) Check the list of all supported RPC call at [RpcClient.js](RpcClient.js)
## Creating and sending a Transaction through P2P ## Creating and sending a Transaction through P2P
The fee of the transaction can be given in `opts` or it will be determined The fee of the transaction can be given in `opts` or it will be determined
by the transaction size. Documentation on the paramets of `TransactionBuilder` by the transaction size. Documentation on the parameters of `TransactionBuilder`
can be found on the source file. can be found on the source file.
```js ```js
var bitcore = require('bitcore'); var bitcore = require('bitcore');
var networks = bitcore.networks;
var Peer = bitcore.Peer; var Peer = bitcore.Peer;
var TransactionBuilder = bitcore.TransactionBuilder; var TransactionBuilder = bitcore.TransactionBuilder;
var PeerManager = require('soop').load('../PeerManager', { var PeerManager = bitcore.PeerManager;
network: networks.testnet
});
// this can be get from insight.bitcore.io API o blockchain.info // Unspent transactions can be found via the insight.bitcore.io or blockchain.info APIs
var unspent = [{
'txid': '707108b5ba4f78dc951df4647a03365bf36432ea57fb641676045c5044daaea7',
'vout': 0,
'address': 'n3QDC7DzsMmN4mcyp3k7XGPX7zFXXHG387',
'scriptPubKey': '76a914f00c4a92ee2314ab08ac0283dc8d07d9bf2be32388ac',
'amount': 0.12345600,
'confirmations': 43537
}, {
'txid': '87a158d32833cb555aea27b6a21af569ccaeb8f9b19691e05f1e6c2b3440bdb3',
'vout': 1,
'address': 'mxdrp9s4mVxS9X4RBYiLe99v59V81XA5C3',
'scriptPubKey': '76a914bbc87986da6b17c7876db4efacf59a95e14f6cf588ac',
'amount': 0.05749800,
'confirmations': 43536
}
var unspent = [
{
"address": "n4g2TFaQo8UgedwpkYdcQFF6xE2Ei9Czvy",
"txid": "2ac165fa7a3a2b535d106a0041c7568d03b531e58aeccdd3199d7289ab12cfc1",
"scriptPubKey": "76a914fe021bac469a5c49915b2a8ffa7390a9ce5580f988ac",
"vout": 1,
"amount": 1.0101,
"confirmations":7
},
{
"address": "mhNCT9TwZAGF1tLPpZdqfkTmtBkY282YDW",
"txid": "2ac165fa7a3a2b535d106a0041c7568d03b531e58aeccdd3199d7289ab12cfc2",
"scriptPubKey": "76a9141448534cb1a1ec44665b0eb2326e570814afe3f188ac",
"vout": 0,
"confirmations": 1,
"amount": 10
},
]; ];
//private keys in WIF format (see TransactionBuilder.js for other options) // Private keys in WIF format (see TransactionBuilder.js for other options)
var keys = [ var keys = [
"cSq7yo4fvsbMyWVN945VUGUWMaSazZPWqBVJZyoGsHmNq6W4HVBV", 'cQA75LXhV5JkMT8wkkqjR87SnHK4doh3c21p7PAd5tp8tc1tRBAY',
"cPa87VgwZfowGZYaEenoQeJgRfKW6PhZ1R65EHTkN1K19cSvc92G", 'cRz85dz9AiDieRpEwoucfXXQa1jdHHghcv6YnnVVGZ3MQyR1X4u2',
"cPQ9DSbBRLva9av5nqeF5AGrh3dsdW8p2E5jS4P8bDWZAoQTeeKB" 'cSq7yo4fvsbMyWVN945VUGUWMaSazZPWqBVJZyoGsHmNq6W4HVBV',
'cPa87VgwZfowGZYaEenoQeJgRfKW6PhZ1R65EHTkN1K19cSvc92G',
'cPQ9DSbBRLva9av5nqeF5AGrh3dsdW8p2E5jS4P8bDWZAoQTeeKB'
]; ];
var peerman = new PeerManager({
var peerman = new PeerManager(); network: 'testnet'
});
peerman.addPeer(new Peer('127.0.0.1', 18333)); peerman.addPeer(new Peer('127.0.0.1', 18333));
peerman.on('connect', function() { peerman.on('connect', function() {
var conn = peerman.getActiveConnection(); var conn = peerman.getActiveConnection();
if (conn) { if (conn) {
var outs = [{address:toAddress, amount:amt}]; // define transaction output
var opts = {remainderOut: {address: changeAddressString}}; var outs = [{
var Builder = bitcore.TransactionBuilder; address: 'mhNCT9TwZAGF1tLPpZdqfkTmtBkY282YDW',
amount: 0.1337
var tx = new Builder(opts) }];
.setUnspent(Unspent) // set change address
var opts = {
remainderOut: {
address: 'n4g2TFaQo8UgedwpkYdcQFF6xE2Ei9Czvy'
}
};
var tx = new TransactionBuilder(opts)
.setUnspent(unspent)
.setOutputs(outs) .setOutputs(outs)
.sign(keys) .sign(keys)
.build(); .build();
/* create and signing can be done in multiple steps using: /* Create and signing can be done in multiple steps:
* *
* var builder = new bitcore.TransactionBuilder(opts) * var builder = new bitcore.TransactionBuilder(opts)
* .setUnspent(utxos) * .setUnspent(utxos)
* .setOutputs(outs); * .setOutputs(outs);
* //later
* builder.sign(key1);
* // get partially signed tx
* var tx = builder.build();
* *
* //later * // Sign with the first key
* builder.sign(key1);
* var tx = builder.build(); // Partially signed transaction
*
* // Sign with the second key
* builder.sign(key2); * builder.sign(key2);
* if (builder.isFullySigned()){ * if (builder.isFullySigned()){
* var tx = builder.build(); * var tx = builder.build();
* } * }
* *
* The selected Unspent Outputs for the transaction can be retrieved with: * var selectedUnspent = build.getSelectedUnspent(); // Retrieve selected unspent outputs from the transaction
* var selectedUnspent = build.getSelectedUnspent();
*/ */
conn.sendTx(tx.serialize().toString('hex'));
var txid = tx.getHash().toString('hex');
console.log('Created transaction with txid '+txid);
var raw_tx = tx.serialize().toString('hex');
console.log('Transaction raw hex dump:');
console.log('-------------------------------------');
console.log(raw_tx);
console.log('-------------------------------------');
// finally, send transaction to the bitcoin network
conn.sendTx(tx);
// for now, the network won't respond in any case
// (transaction accepted, transaction rejected)
// in the future, we may listen to 'reject' message
// see https://gist.github.com/gavinandresen/7079034
} }
conn.on('reject', function() {
console.log('Transaction Rejected');
});
}); });
peerman.start(); peerman.start();
``` ```
## Parsing a Script ## Parsing a Script
Gets an address strings from a ScriptPubKey Buffer Gets an address strings from a ScriptPubKey Buffer
@ -265,25 +288,26 @@ console.log(getAddrStr(s)[0]); // mkZBYBiq6DNoQEKakpMJegyDbw2YiNQnHT
``` ```
#Security #Security
Please use at your own risk. Please use at your own risk.
Bitcore is still under heavy development and not quite ready for "drop-in" production use. If you find a security issue, please email security@bitcore.io. Bitcore is still under heavy development and not quite ready for "drop-in" production use. If you find a security issue, please email security@bitcore.io.
#Contributing #Contributing
Bitcore needs some developer love. Please send pull requests for bug fixes, code optimization, and ideas for improvement. Bitcore needs some developer love. Please send pull requests for bug fixes, code optimization, and ideas for improvement.
#Browser support #Browser support
## Building the browser bundle ## Building the browser bundle
To build bitcore full bundle for the browser:
(this is automatically executed after you run `npm install`) To build bitcore full bundle for the browser (this is automatically executed after you run `npm install`):
``` ```
node browser/build.js -a node browser/build.js -a
``` ```
This will generate a `browser/bundle.js` file which you can include
in your HTML to use bitcore in the browser.
## This will generate a `browser/bundle.js` file which you can include in your HTML to use bitcore in the browser.
##Example browser usage ##Example browser usage
@ -303,19 +327,17 @@ From example/simple.html
</html> </html>
``` ```
You can check a more complex usage example at examples/example.html You can check a more complex usage example at examples/example.html.
## Generating a customized browser bundle ## Generating a customized browser bundle
To generate a customized bitcore bundle, you can specify
which submodules you want to include in it with the -s option: To generate a customized bitcore bundle, you can specify which submodules you want to include in it with the -s option:
``` ```
node browser/build.js -s Transaction,Address node browser/build.js -s Transaction,Address
``` ```
This will generate a `browser/bundle.js` containing only the Transaction
and Address class, with all their dependencies. This will generate a `browser/bundle.js` containing only the Transaction and Address class, with all their dependencies. Use this option if you are not using the whole bitcore library, to optimize the bundle size, script loading time, and general resource usage.
Use this option if you are not using the whole bitcore library, to optimize
the bundle size, script loading time, and general resource usage.
## Tests ## Tests
@ -341,13 +363,10 @@ npm run-script coverage
And then open coverage/lcov-report/index.html in your browser. And then open coverage/lcov-report/index.html in your browser.
#License #License
**Code released under [the MIT license](https://github.com/bitpay/bitcore/blob/master/LICENSE).** **Code released under [the MIT license](https://github.com/bitpay/bitcore/blob/master/LICENSE).**
Copyright 2013-2014 BitPay, Inc. Bitcore is a trademark maintained by BitPay, Inc. Copyright 2013-2014 BitPay, Inc. Bitcore is a trademark maintained by BitPay, Inc.
[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/bitpay/bitcore/trend.png)](https://bitdeli.com/free "Bitdeli Badge") [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/bitpay/bitcore/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

34
examples/ConnectionTor.js Normal file
View File

@ -0,0 +1,34 @@
var Peer = require('../Peer');
var Connection = require('../Connection');
var dns = require('dns');
// get a peer from dns seed
dns.resolve('dnsseed.bluematt.me', function(err, seeds) {
// use the first peer
var peer = new Peer(seeds[0], 8333);
//Custom peer:
//var peer = new Peer('180.153.139.246', '8888');
// create a connection without an existing socket
// but specify a socks5 proxy to create a socket
// that's bound to that proxy in it's place
var connection = new Connection(null, peer, {
proxy: { host: '127.0.0.1', port: 9050 }
});
connection.open();
connection.on('connect', function(data) {
console.log('connected through socks5!');
});
connection.on('error', function(err) {
console.log('There was an error running this example.');
console.log('Are you running Tor? Tor must running for this example to work.');
console.log('If you still get an error, you may need to use a different proxy from here:');
console.log('http://sockslist.net/');
//console.log(err);
});
});

View File

@ -3,11 +3,8 @@
var run = function() { var run = function() {
// Replace '../bitcore' with 'bitcore' if you use this code elsewhere. // Replace '../bitcore' with 'bitcore' if you use this code elsewhere.
var bitcore = require('../bitcore'); var bitcore = require('../bitcore');
var networks = bitcore.networks;
var Peer = bitcore.Peer; var Peer = bitcore.Peer;
var PeerManager = require('soop').load('../lib/PeerManager', { var PeerManager = bitcore.PeerManager;
network: networks.testnet
});
var handleBlock = function(info) { var handleBlock = function(info) {
console.log('** Block Received **'); console.log('** Block Received **');
@ -29,7 +26,9 @@ var run = function() {
info.conn.sendGetData(invs); info.conn.sendGetData(invs);
}; };
var peerman = new PeerManager(); var peerman = new PeerManager({
network: 'testnet'
});
peerman.addPeer(new Peer('127.0.0.1', 18333)); peerman.addPeer(new Peer('127.0.0.1', 18333));

View File

@ -3,71 +3,102 @@
var run = function() { var run = function() {
// Replace '../bitcore' with 'bitcore' if you use this code elsewhere. // Replace '../bitcore' with 'bitcore' if you use this code elsewhere.
var bitcore = require('../bitcore'); var bitcore = require('../bitcore');
var networks = bitcore.networks;
var Peer = bitcore.Peer; var Peer = bitcore.Peer;
var Transaction = bitcore.Transaction;
var Address = bitcore.Address; var TransactionBuilder = bitcore.TransactionBuilder;
var Script = bitcore.Script; var PeerManager = bitcore.PeerManager;
var coinUtil = bitcore.util;
var PeerManager = require('soop').load('../lib/PeerManager', { // Unspent transactions can be found via the insight.bitcore.io or blockchain.info APIs
network: networks.testnet var unspent = [{
'txid': '707108b5ba4f78dc951df4647a03365bf36432ea57fb641676045c5044daaea7',
'vout': 0,
'address': 'n3QDC7DzsMmN4mcyp3k7XGPX7zFXXHG387',
'scriptPubKey': '76a914f00c4a92ee2314ab08ac0283dc8d07d9bf2be32388ac',
'amount': 0.12345600,
'confirmations': 43537
}, {
'txid': '87a158d32833cb555aea27b6a21af569ccaeb8f9b19691e05f1e6c2b3440bdb3',
'vout': 1,
'address': 'mxdrp9s4mVxS9X4RBYiLe99v59V81XA5C3',
'scriptPubKey': '76a914bbc87986da6b17c7876db4efacf59a95e14f6cf588ac',
'amount': 0.05749800,
'confirmations': 43536
}
];
// Private keys in WIF format (see TransactionBuilder.js for other options)
var keys = [
'cQA75LXhV5JkMT8wkkqjR87SnHK4doh3c21p7PAd5tp8tc1tRBAY',
'cRz85dz9AiDieRpEwoucfXXQa1jdHHghcv6YnnVVGZ3MQyR1X4u2',
'cSq7yo4fvsbMyWVN945VUGUWMaSazZPWqBVJZyoGsHmNq6W4HVBV',
'cPa87VgwZfowGZYaEenoQeJgRfKW6PhZ1R65EHTkN1K19cSvc92G',
'cPQ9DSbBRLva9av5nqeF5AGrh3dsdW8p2E5jS4P8bDWZAoQTeeKB'
];
var peerman = new PeerManager({
network: 'testnet'
}); });
var createTx = function() {
var TXIN = 'd05f35e0bbc495f6dcab03e599c8f5e32a07cdb4bc76964de201d06a2a7d8265';
var TXIN_N = 0;
var ADDR = 'muHct3YZ9Nd5Pq7uLYYhXRAxeW4EnpcaLz';
var VAL = '0.001';
var txobj = {
version: 1,
lock_time: 0,
ins: [],
outs: []
};
var txin = {
s: coinUtil.EMPTY_BUFFER, // Add signature
q: 0xffffffff
};
var hash = new Buffer(TXIN.split('').reverse(), 'hex');
var vout = parseInt(TXIN_N);
var voutBuf = new Buffer(4);
voutBuf.writeUInt32LE(vout, 0);
txin.o = Buffer.concat([hash, voutBuf]);
txobj.ins.push(txin);
var addr = new Address(ADDR);
var script = Script.createPubKeyHashOut(addr.payload());
var valueNum = coinUtil.parseValue(VAL);
var value = coinUtil.bigIntToValue(valueNum);
var txout = {
v: value,
s: script.getBuffer(),
};
txobj.outs.push(txout);
return new Transaction(txobj);
};
var peerman = new PeerManager();
peerman.addPeer(new Peer('127.0.0.1', 18333)); peerman.addPeer(new Peer('127.0.0.1', 18333));
peerman.on('connect', function() { peerman.on('connect', function() {
var conn = peerman.getActiveConnection(); var conn = peerman.getActiveConnection();
if (conn) { if (conn) {
conn.sendTx(createTx()); // define transaction output
var outs = [{
address: 'mhNCT9TwZAGF1tLPpZdqfkTmtBkY282YDW',
amount: 0.1337
}];
// set change address
var opts = {
remainderOut: {
address: 'n4g2TFaQo8UgedwpkYdcQFF6xE2Ei9Czvy'
}
};
var tx = new TransactionBuilder(opts)
.setUnspent(unspent)
.setOutputs(outs)
.sign(keys)
.build();
/* Create and signing can be done in multiple steps:
*
* var builder = new bitcore.TransactionBuilder(opts)
* .setUnspent(utxos)
* .setOutputs(outs);
*
* // Sign with the first key
* builder.sign(key1);
* var tx = builder.build(); // Partially signed transaction
*
* // Sign with the second key
* builder.sign(key2);
* if (builder.isFullySigned()){
* var tx = builder.build();
* }
*
* var selectedUnspent = build.getSelectedUnspent(); // Retrieve selected unspent outputs from the transaction
*/
var txid = tx.getHash().toString('hex');
console.log('Created transaction with txid '+txid);
var raw_tx = tx.serialize().toString('hex');
console.log('Transaction raw hex dump:');
console.log('-------------------------------------');
console.log(raw_tx);
console.log('-------------------------------------');
// finally, send transaction to the bitcoin network
conn.sendTx(tx);
// for now, the network won't respond in any case
// (transaction accepted, transaction rejected)
// in the future, we may listen to 'reject' message
// see https://gist.github.com/gavinandresen/7079034
} }
conn.on('reject', function() {
console.log('Transaction Rejected');
});
}); });
peerman.start(); peerman.start();
}; };
module.exports.run = run; module.exports.run = run;

View File

@ -1,6 +1,6 @@
/** /**
* This is a simple script that will display network messages. * This is a simple script that will display network messages.
* It users the Peer / Connection classes * directly instead of * It users the Peer / Connection classes directly instead of
* relying on PeerManager. * relying on PeerManager.
*/ */

View File

@ -1,19 +1,18 @@
var imports = require('soop').imports(); var imports = require('soop').imports();
var config = imports.config || require('../config');
var log = imports.log || require('../util/log'); var log = imports.log || require('../util/log');
var network = imports.network || require('../networks')[config.network];
var MAX_RECEIVE_BUFFER = 10000000; var MAX_RECEIVE_BUFFER = 10000000;
var PROTOCOL_VERSION = 70000; var PROTOCOL_VERSION = 70000;
var Binary = imports.Binary || require('binary');
var Put = imports.Put || require('bufferput'); var Put = imports.Put || require('bufferput');
var Buffers = imports.Buffers || require('buffers'); var Buffers = imports.Buffers || require('buffers');
require('../patches/Buffers.monkey').patch(Buffers); require('../patches/Buffers.monkey').patch(Buffers);
var Block = require('./Block'); var bitcoreDefaults = imports.config || require('../config');
var Transaction = require('./Transaction'); var networks = imports.networks || require('../networks');
var Block = imports.Block || require('./Block');
var Transaction = imports.Transaction || require('./Transaction');
var util = imports.util || require('../util'); var util = imports.util || require('../util');
var Parser = imports.Parser || require('../util/BinaryParser'); var Parser = imports.Parser || require('../util/BinaryParser');
var buffertools = imports.buffertools || require('buffertools'); var buffertools = imports.buffertools || require('buffertools');
@ -22,11 +21,21 @@ var nonce = util.generateNonce();
var BIP0031_VERSION = 60000; var BIP0031_VERSION = 60000;
function Connection(socket, peer) { function Connection(socket, peer, opts) {
Connection.super(this, arguments); Connection.super(this, arguments);
this.config = opts || bitcoreDefaults;
this.network = networks[this.config.network] || networks.livenet;
this.socket = socket; this.socket = socket;
this.peer = peer; this.peer = peer;
// check for socks5 proxy options and construct a proxied socket
if (this.config.proxy) {
var Socks5Client = imports.Socks5Client || require('socks5-client');
this.socket = new Socks5Client(this.config.proxy.host, this.config.proxy.port);
}
// A connection is considered "active" once we have received verack // A connection is considered "active" once we have received verack
this.active = false; this.active = false;
// The version incoming packages are interpreted as // The version incoming packages are interpreted as
@ -36,7 +45,7 @@ function Connection(socket, peer) {
// The (claimed) height of the remote peer's block chain // The (claimed) height of the remote peer's block chain
this.bestHeight = 0; this.bestHeight = 0;
// Is this an inbound connection? // Is this an inbound connection?
this.inbound = !!socket.server; this.inbound = !!this.socket.server;
// Have we sent a getaddr on this connection? // Have we sent a getaddr on this connection?
this.getaddr = false; this.getaddr = false;
@ -54,6 +63,12 @@ function Connection(socket, peer) {
} }
Connection.parent = imports.parent || require('events').EventEmitter; Connection.parent = imports.parent || require('events').EventEmitter;
Connection.prototype.open = function(callback) {
if (typeof callback === 'function') this.once('connect', callback);
this.socket.connect(this.peer.port, this.peer.host);
return this;
};
Connection.prototype.setupHandlers = function () { Connection.prototype.setupHandlers = function () {
this.socket.addListener('connect', this.handleConnect.bind(this)); this.socket.addListener('connect', this.handleConnect.bind(this));
this.socket.addListener('error', this.handleError.bind(this)); this.socket.addListener('error', this.handleError.bind(this));
@ -131,7 +146,7 @@ Connection.prototype.handleMessage = function(message) {
this.recvVer = Math.min(message.version, PROTOCOL_VERSION); this.recvVer = Math.min(message.version, PROTOCOL_VERSION);
} else { } else {
// We won't start expecting a checksum until after we've received // We won't start expecting a checksum until after we've received
// the "verack" message. // the 'verack' message.
this.once('verack', (function () { this.once('verack', (function () {
this.recvVer = message.version; this.recvVer = message.version;
}).bind(this)); }).bind(this));
@ -145,7 +160,7 @@ Connection.prototype.handleMessage = function(message) {
break; break;
case 'ping': case 'ping':
if ("object" === typeof message.nonce) { if ('object' === typeof message.nonce) {
this.sendPong(message.nonce); this.sendPong(message.nonce);
} }
break; break;
@ -285,7 +300,7 @@ Connection.prototype.sendBlock = function (block, txs) {
Connection.prototype.sendMessage = function (command, payload) { Connection.prototype.sendMessage = function (command, payload) {
try { try {
var magic = network.magic; var magic = this.network.magic;
var commandBuf = new Buffer(command, 'ascii'); var commandBuf = new Buffer(command, 'ascii');
if (commandBuf.length > 12) throw 'Command name too long'; if (commandBuf.length > 12) throw 'Command name too long';
@ -308,13 +323,13 @@ Connection.prototype.sendMessage = function (command, payload) {
var buffer = message.buffer(); var buffer = message.buffer();
log.debug('['+this.peer+'] '+ log.debug('['+this.peer+'] '+
"Sending message "+command+" ("+payload.length+" bytes)"); 'Sending message '+command+' ('+payload.length+' bytes)');
this.socket.write(buffer); this.socket.write(buffer);
} catch (err) { } catch (err) {
// TODO: We should catch this error one level higher in order to better // TODO: We should catch this error one level higher in order to better
// determine how to react to it. For now though, ignoring it will do. // determine how to react to it. For now though, ignoring it will do.
log.err("Error while sending message to peer "+this.peer+": "+ log.err('Error while sending message to peer '+this.peer+': '+
(err.stack ? err.stack : err.toString())); (err.stack ? err.stack : err.toString()));
} }
}; };
@ -323,7 +338,7 @@ Connection.prototype.handleData = function (data) {
this.buffers.push(data); this.buffers.push(data);
if (this.buffers.length > MAX_RECEIVE_BUFFER) { if (this.buffers.length > MAX_RECEIVE_BUFFER) {
log.err("Peer "+this.peer+" exceeded maxreceivebuffer, disconnecting."+ log.err('Peer '+this.peer+' exceeded maxreceivebuffer, disconnecting.'+
(err.stack ? err.stack : err.toString())); (err.stack ? err.stack : err.toString()));
this.socket.destroy(); this.socket.destroy();
return; return;
@ -336,7 +351,7 @@ Connection.prototype.processData = function () {
// If there are less than 20 bytes there can't be a message yet. // If there are less than 20 bytes there can't be a message yet.
if (this.buffers.length < 20) return; if (this.buffers.length < 20) return;
var magic = network.magic; var magic = this.network.magic;
var i = 0; var i = 0;
for (;;) { for (;;) {
if (this.buffers.get(i ) === magic[0] && if (this.buffers.get(i ) === magic[0] &&
@ -371,13 +386,13 @@ Connection.prototype.processData = function () {
if (this.buffers.length < endPos) return; if (this.buffers.length < endPos) return;
var command = this.buffers.slice(4, 16).toString('ascii').replace(/\0+$/,""); var command = this.buffers.slice(4, 16).toString('ascii').replace(/\0+$/,'');
var payload = this.buffers.slice(startPos, endPos); var payload = this.buffers.slice(startPos, endPos);
var checksum = (this.recvVer >= 209) ? this.buffers.slice(20, 24) : null; var checksum = (this.recvVer >= 209) ? this.buffers.slice(20, 24) : null;
log.debug('['+this.peer+'] ' + log.debug('['+this.peer+'] ' +
"Received message " + command + 'Received message ' + command +
" (" + payloadLen + " bytes)"); ' (' + payloadLen + ' bytes)');
if (checksum !== null) { if (checksum !== null) {
var checksumConfirm = doubleSha256(payload).slice(0, 4); var checksumConfirm = doubleSha256(payload).slice(0, 4);

View File

@ -1,12 +1,9 @@
var imports = require('soop').imports(); var imports = require('soop').imports();
var config = imports.config || require('../config');
var log = imports.log || require('../util/log'); var log = imports.log || require('../util/log');
var network = imports.network || require('../networks')[config.network]; var bitcoreDefaults = imports.config || require('../config');
var Connection = imports.Connection || require ('./Connection');
var Connection = imports.Connection ||
require('soop').load('./Connection', {config: config, network: network}) ||
require ('./Connection');
var Peer = imports.Peer || require('./Peer'); var Peer = imports.Peer || require('./Peer');
@ -15,7 +12,8 @@ GetAdjustedTime = imports.GetAdjustedTime || function () {
return Math.floor(new Date().getTime() / 1000); return Math.floor(new Date().getTime() / 1000);
}; };
function PeerManager() { function PeerManager(config) {
this.config = config || bitcoreDefaults;
this.active = false; this.active = false;
this.timer = null; this.timer = null;
@ -28,7 +26,7 @@ function PeerManager() {
this.interval = 5000; this.interval = 5000;
this.minConnections = 8; this.minConnections = 8;
this.minKnownPeers = 10; this.minKnownPeers = 10;
}; }
PeerManager.parent = imports.parent || require('events').EventEmitter; PeerManager.parent = imports.parent || require('events').EventEmitter;
PeerManager.Connection = Connection; PeerManager.Connection = Connection;
@ -96,7 +94,7 @@ PeerManager.prototype.connectTo = function(peer) {
}; };
PeerManager.prototype.addConnection = function(socketConn, peer) { PeerManager.prototype.addConnection = function(socketConn, peer) {
var conn = new Connection(socketConn, peer); var conn = new Connection(socketConn, peer, this.config);
this.connections.push(conn); this.connections.push(conn);
this.emit('connection', conn); this.emit('connection', conn);

View File

@ -26,6 +26,10 @@
{ {
"name": "Ryan X. Charles", "name": "Ryan X. Charles",
"email": "ryan@bitpay.com" "email": "ryan@bitpay.com"
},
{
"name": "Gordon Hall",
"email": "gordon@bitpay.com"
} }
], ],
"keywords": [ "keywords": [
@ -63,6 +67,7 @@
"commander": "=2.1.0", "commander": "=2.1.0",
"browserify-bignum": "git://github.com/maraoz/browserify-bignum.git", "browserify-bignum": "git://github.com/maraoz/browserify-bignum.git",
"browserify-buffertools": "git://github.com/maraoz/browserify-buffertools.git", "browserify-buffertools": "git://github.com/maraoz/browserify-buffertools.git",
"socks5-client": "~0.3.6",
"brfs": "=1.0.0", "brfs": "=1.0.0",
"chai": "=1.9.1", "chai": "=1.9.1",
"uglifyify": "=1.2.3" "uglifyify": "=1.2.3"

View File

@ -23,6 +23,16 @@ describe('Connection', function() {
var c = new Connection(mSocket, mPeer); var c = new Connection(mSocket, mPeer);
should.exist(c); should.exist(c);
}); });
if (typeof process !== 'undefined' && process.versions) { //node-only tests
it('should create a proxied socket if instructed', function() {
var mPeer;
var c = new Connection(null, mPeer, {
proxy: { host: 'localhost', port: 9050 }
});
should.exist(c.socket);
});
};
}); });

View File

@ -16,21 +16,6 @@ describe('Key', function() {
var k = new Key(); var k = new Key();
should.exist(k); should.exist(k);
}); });
it('should not fail when called as Key() without "new"', function() {
var key = Key();
should.exist(key);
});
it('should not fail when called as Key() without "new" with some args', function() {
var key = Key(1, 2, 3, 4, 5);
should.exist(key);
});
it('should have correct properties when called with Key() without "new"', function() {
var key = Key();
key.compressed.should.equal(true);
should.not.exist(key.public);
should.not.exist(key.private);
should.exist(key);
});
it('should be able to generateSync instance', function() { it('should be able to generateSync instance', function() {
var k = Key.generateSync(); var k = Key.generateSync();
should.exist(k); should.exist(k);
@ -180,6 +165,25 @@ describe('Key', function() {
}); });
}); });
describe('node only Key functionality', function() {
it('should not fail when called as Key() without "new"', function() {
var key = Key();
should.exist(key);
});
it('should not fail when called as Key() without "new" with some args', function() {
var key = Key(1, 2, 3, 4, 5);
should.exist(key);
});
it('should have correct properties when called with Key() without "new"', function() {
var key = Key();
key.compressed.should.equal(true);
should.not.exist(key.public);
should.not.exist(key.private);
should.exist(key);
});
});
} }
}); });