Merge pull request #79 from maraoz/feature/change-buffertools-usage

change buffertools usage and add tests
This commit is contained in:
Ryan X. Charles 2014-02-18 16:02:24 -05:00
commit 9bb331955f
13 changed files with 173 additions and 46 deletions

View File

@ -7,6 +7,7 @@ function spec(b) {
var Bignum = b.Bignum || require('bignum');
var Binary = b.Binary || require('binary');
var Step = b.Step || require('step');
var buffertools = b.buffertools || require('buffertools');
var Transaction = b.Transaction || require('./Transaction').class();
var TransactionIn = Transaction.In;
var TransactionOut = Transaction.Out;
@ -34,7 +35,7 @@ function spec(b) {
this.active = data.active || false;
this.chainWork = data.chainWork || util.EMPTY_BUFFER;
this.txs = data.txs || [];
};
}
Block.prototype.getHeader = function getHeader() {
var buf = new Buffer(80);
@ -79,7 +80,7 @@ function spec(b) {
Block.prototype.checkHash = function checkHash() {
if (!this.hash || !this.hash.length) return false;
return this.calcHash().compare(this.hash) == 0;
return buffertools.compare(this.calcHash(), this.hash) == 0;
};
Block.prototype.getHash = function getHash() {
@ -93,14 +94,14 @@ function spec(b) {
// TODO: Create a compare method in node-buffertools that uses the correct
// endian so we don't have to reverse both buffers before comparing.
this.hash.reverse();
buffertools.reverse(this.hash);
if (this.hash.compare(target) > 0) {
if (buffertools.compare(this.hash, target) > 0) {
throw new VerificationError('Difficulty target not met');
}
// Return the hash to its normal order
this.hash.reverse();
buffertools.reverse(this.hash);
return true;
};
@ -181,7 +182,7 @@ function spec(b) {
var i2 = Math.min(i + 1, size - 1);
var a = tree[j + i];
var b = tree[j + i2];
tree.push(util.twoSha256(a.concat(b)));
tree.push(util.twoSha256(Buffer.concat([a,b])));
}
j += size;
}
@ -199,7 +200,7 @@ function spec(b) {
throw new VerificationError('No merkle root');
}
if (this.calcMerkleRoot().compare(this.merkle_root) == 0) {
if (buffertools.compare(this.calcMerkleRoot(), this.merkle_root) == 0) {
throw new VerificationError('Merkle root incorrect');
}

View File

@ -17,6 +17,7 @@ function spec(b) {
var Transaction = require('./Transaction').class();
var util = b.util || require('./util/util');
var Parser = b.Parser || require('./util/BinaryParser').class();
var buffertools = b.buffertools || require('buffertools');
var doubleSha256 = b.doubleSha256 || util.twoSha256;
var nonce = util.generateNonce();
@ -51,7 +52,7 @@ function spec(b) {
}
this.setupHandlers();
};
}
Connection.superclass = b.superclass || require('events').EventEmitter;
Connection.prototype.setupHandlers = function () {
@ -62,8 +63,8 @@ function spec(b) {
var dumpLen = 35;
log.debug('['+this.peer+'] '+
'Recieved '+data.length+' bytes of data:');
log.debug('... '+ data.slice(0, dumpLen > data.length ?
data.length : dumpLen).toHex() +
log.debug('... '+ buffertools.toHex(data.slice(0, dumpLen > data.length ?
data.length : dumpLen)) +
(data.length > dumpLen ? '...' : ''));
}).bind(this));
this.socket.addListener('data', this.handleData.bind(this));
@ -114,7 +115,7 @@ function spec(b) {
switch (message.command) {
case 'version':
// Did we connect to ourself?
if (nonce.compare(message.nonce) === 0) {
if (buffertools.compare(nonce, message.nonce) === 0) {
this.socket.end();
return;
}
@ -376,7 +377,7 @@ function spec(b) {
if (checksum !== null) {
var checksumConfirm = doubleSha256(payload).slice(0, 4);
if (checksumConfirm.compare(checksum) !== 0) {
if (buffertools.compare(checksumConfirm, checksum) !== 0) {
log.err('['+this.peer+'] '+
'Checksum failed',
{ cmd: command,

View File

@ -3,6 +3,7 @@ require('classtool');
function spec(b) {
var Net = b.Net || require('net');
var Binary = b.Binary || require('binary');
var buffertools = b.buffertools || require('buffertools');
function Peer(host, port, services) {
if ("string" === typeof host) {
@ -17,7 +18,7 @@ function spec(b) {
this.host = host.host;
this.port = host.port;
} else if (Buffer.isBuffer(host)) {
if (host.slice(0, 12).compare(Peer.IPV6_IPV4_PADDING) != 0) {
if (buffertools.compare(Peer.IPV6_IPV4_PADDING, host.slice(0, 12)) != 0) {
throw new Error('IPV6 not supported yet! Cannot instantiate host.');
}
this.host = Array.prototype.slice.apply(host.slice(12)).join('.');

View File

@ -4,7 +4,8 @@ function spec(b) {
var config = b.config || require('./config');
var log = b.log || require('./util/log');
var Opcode = require('./Opcode').class();
var Opcode = b.Opcode || require('./Opcode').class();
var buffertools = b.buffertools || require('buffertools');
// Make opcodes available as pseudo-constants
for (var i in Opcode.map) {
@ -396,7 +397,7 @@ function spec(b) {
if (Buffer.isBuffer(chunk)) {
for (var i = 0, l = this.chunks.length; i < l; i++) {
if (Buffer.isBuffer(this.chunks[i]) &&
this.chunks[i].compare(chunk) == 0) {
buffertools.compare(this.chunks[i], chunk) === 0) {
this.chunks.splice(i, 1);
dirty = true;
}

View File

@ -5,7 +5,8 @@ function spec(b) {
var config = b.config || require('./config');
var log = b.log || require('./util/log');
var Opcode = require('./Opcode').class();
var Opcode = b.Opcode || require('./Opcode').class();
var buffertools = b.buffertools || require('buffertools');
// Make opcodes available as pseudo-constants
for (var i in Opcode.map) {
@ -302,7 +303,7 @@ function spec(b) {
var v2 = this.stackTop(1);
this.stackPop();
this.stackPop();
this.stack.push(v1.concat(v2));
this.stack.push(Buffer.concat([v1, v2]));
break;
case OP_SUBSTR:
@ -385,7 +386,7 @@ function spec(b) {
// (x1 x2 - bool)
var v1 = this.stackTop(2);
var v2 = this.stackTop(1);
var value = v1.compare(v2) == 0;
var value = buffertools.compare(v1, v2) === 0;
// OP_NOTEQUAL is disabled because it would be too easy to say
// something like n != 1 and have some wiseguy pass in 1 with extra
@ -797,13 +798,13 @@ function spec(b) {
ScriptInterpreter.prototype.getPrimitiveStack = function getPrimitiveStack() {
return this.stack.map(function (entry) {
if (entry.length > 2) {
return entry.slice(0).toHex();
return buffertools.toHex(entry.slice(0));
}
var num = castBigint(entry);
if (num.cmp(-128) >= 0 && num.cmp(127) <= 0) {
return num.toNumber();
} else {
return entry.slice(0).toHex();
return buffertools.toHex(entry.slice(0));
}
});
};
@ -835,7 +836,7 @@ function spec(b) {
var w = new Buffer(v.length);
v.copy(w);
w.reverse();
w = buffertools.reverse(w);
if (w[0] & 0x80) {
w[0] &= 0x7f;
return bignum.fromBuffer(w).neg();
@ -858,9 +859,9 @@ function spec(b) {
c = new Buffer(b.length + 1);
b.copy(c, 1);
c[0] = 0;
return c.reverse();
return buffertools.reverse(c);
} else {
return b.reverse();
return buffertools.reverse(b);
}
} else if (cmp == 0) {
return new Buffer([]);
@ -870,10 +871,10 @@ function spec(b) {
c = new Buffer(b.length + 1);
b.copy(c, 1);
c[0] = 0x80;
return c.reverse();
return buffertools.reverse(c);
} else {
b[0] |= 0x80;
return b.reverse();
return buffertools.reverse(b);
}
}
};

View File

@ -11,12 +11,13 @@ function spec(b) {
var Put = b.Put || require('bufferput');
var Parser = b.Parser || require('./util/BinaryParser').class();
var Step = b.Step || require('step');
var buffertools = b.buffertools || require('buffertools');
var error = b.error || require('./util/error');
var VerificationError = error.VerificationError;
var MissingSourceError = error.MissingSourceError;
var COINBASE_OP = util.NULL_HASH.concat(new Buffer("FFFFFFFF", 'hex'));
var COINBASE_OP = Buffer.concat([util.NULL_HASH, new Buffer('FFFFFFFF', 'hex')]);
function TransactionIn(data) {
if ("object" !== typeof data) {
@ -28,14 +29,14 @@ function spec(b) {
this.s = Buffer.isBuffer(data.s) ? data.s :
Buffer.isBuffer(data.script) ? data.script : util.EMPTY_BUFFER;
this.q = data.q ? data.q : data.sequence;
};
}
TransactionIn.prototype.getScript = function getScript() {
return new Script(this.s);
};
TransactionIn.prototype.isCoinBase = function isCoinBase() {
return this.o.compare(COINBASE_OP) === 0;
return buffertools.compare(this.o, COINBASE_OP) === 0;
};
TransactionIn.prototype.serialize = function serialize() {
@ -156,7 +157,8 @@ function spec(b) {
buf.writeUInt32LE(this.lock_time, 0);
bufs.push(buf);
return this._buffer = Buffer.concat(bufs);
this._buffer = Buffer.concat(bufs);
return this._buffer;
};
Transaction.prototype.getBuffer = function getBuffer() {
@ -173,7 +175,7 @@ function spec(b) {
Transaction.prototype.checkHash = function checkHash() {
if (!this.hash || !this.hash.length) return false;
return this.calcHash().compare(this.hash) == 0;
return buffertools.compare(this.calcHash(), this.hash) === 0;
};
Transaction.prototype.getHash = function getHash() {
@ -314,7 +316,7 @@ function spec(b) {
// Spent output detected, retrieve transaction that spends it
blockChain.getConflictingTransactions(outpoints, function (err, results) {
if (results.length) {
if (results[0].getHash().compare(self.getHash()) == 0) {
if (buffertools.compare(results[0].getHash(), self.getHash()) === 0) {
log.warn("Detected tx re-add (recoverable db corruption): "
+ util.formatHashAlt(results[0].getHash()));
// TODO: Needs to return an error for the memory pool case?
@ -535,7 +537,7 @@ function spec(b) {
var buffer = bytes.buffer();
// Append hashType
buffer = buffer.concat(new Buffer([parseInt(hashType), 0, 0, 0]));
buffer = Buffer.concat([buffer, new Buffer([parseInt(hashType), 0, 0, 0])]);
return util.twoSha256(buffer);
};
@ -555,7 +557,7 @@ function spec(b) {
var ins = this.ins.map(function (txin) {
var txinObj = {
prev_out: {
hash: new Buffer(txin.getOutpointHash()).reverse().toString('hex'),
hash: buffertools.reverse(new Buffer(txin.getOutpointHash())).toString('hex'),
n: txin.getOutpointIndex()
}
};
@ -605,7 +607,7 @@ function spec(b) {
txin.q = 0xffffffff;
var hash = new Buffer(inputobj.txid, 'hex');
hash.reverse();
hash = buffertools.reverse(hash);
var vout = parseInt(inputobj.vout);
var voutBuf = new Buffer(4);
voutBuf.writeUInt32LE(vout, 0);

View File

@ -15,6 +15,11 @@ module.exports.util = require('./util/util');
module.exports.Script = require('./Script');
module.exports.SINKey = require('./SINKey');
module.exports.Transaction = require('./Transaction');
module.exports.Peer = require('./Peer');
module.exports.Block = require('./Block');
module.exports.Connection = require('./Connection');
module.exports.ScriptInterpreter = require('./ScriptInterpreter');
module.exports.networks = require('./networks');
if (typeof process.versions === 'undefined') {

View File

@ -1,4 +1,5 @@
var Put = require('bufferput');
var buffertools = require('buffertools');
var hex = function(hex) {return new Buffer(hex, 'hex');};
exports.livenet = {
@ -10,7 +11,7 @@ exports.livenet = {
nonce: 2083236893,
version: 1,
hash: hex('6FE28C0AB6F1B372C1A6A246AE63F74F931E8365E15A089C68D6190000000000'),
prev_hash: new Buffer(32).fill(0),
prev_hash: buffertools.fill(new Buffer(32), 0),
timestamp: 1231006505,
merkle_root: hex('3BA3EDFD7A7B12B27AC72C3E67768F617FC81BC3888A51323A9FB8AA4B1E5E4A'),
bits: 486604799
@ -53,7 +54,7 @@ exports.testnet = {
nonce: 414098458,
version: 1,
hash: hex('43497FD7F826957108F4A30FD9CEC3AEBA79972084E90EAD01EA330900000000'),
prev_hash: new Buffer(32).fill(0),
prev_hash: buffertools.fill(new Buffer(32), 0),
timestamp: 1296688602,
merkle_root: hex('3BA3EDFD7A7B12B27AC72C3E67768F617FC81BC3888A51323A9FB8AA4B1E5E4A'),
bits: 486604799,

28
test/test.Block.js Normal file
View File

@ -0,0 +1,28 @@
'use strict';
var chai = require('chai');
var bitcore = require('../bitcore');
var should = chai.should();
var BlockModule = bitcore.Block;
var Block;
describe('Block', function() {
it('should initialze the main object', function() {
should.exist(BlockModule);
});
it('should be able to create class', function() {
Block = BlockModule.class();
should.exist(Block);
});
it('should be able to create instance', function() {
var p = new Block();
should.exist(p);
});
});

31
test/test.Connection.js Normal file
View File

@ -0,0 +1,31 @@
'use strict';
var chai = require('chai');
var bitcore = require('../bitcore');
var should = chai.should();
var ConnectionModule = bitcore.Connection;
var Connection;
var nop = function() {};
describe('Connection', function() {
it('should initialze the main object', function() {
should.exist(ConnectionModule);
});
it('should be able to create class', function() {
Connection = ConnectionModule.class();
should.exist(Connection);
});
it('should be able to create instance', function() {
var mSocket = {server: null, addListener: nop},
mPeer;
var c = new Connection(mSocket, mPeer);
should.exist(c);
});
});

28
test/test.Peer.js Normal file
View File

@ -0,0 +1,28 @@
'use strict';
var chai = require('chai');
var bitcore = require('../bitcore');
var should = chai.should();
var PeerModule = bitcore.Peer;
var Peer;
describe('Peer', function() {
it('should initialze the main object', function() {
should.exist(PeerModule);
});
it('should be able to create class', function() {
Peer = PeerModule.class();
should.exist(Peer);
});
it('should be able to create instance', function() {
var p = new Peer('localhost', 8333);
should.exist(p);
});
});

View File

@ -0,0 +1,28 @@
'use strict';
var chai = require('chai');
var bitcore = require('../bitcore');
var should = chai.should();
var ScriptInterpreterModule = bitcore.ScriptInterpreter;
var ScriptInterpreter;
describe('ScriptInterpreter', function() {
it('should initialze the main object', function() {
should.exist(ScriptInterpreterModule);
});
it('should be able to create class', function() {
ScriptInterpreter = ScriptInterpreterModule.class();
should.exist(ScriptInterpreter);
});
it('should be able to create instance', function() {
var si = new ScriptInterpreter();
should.exist(si);
});
});

View File

@ -3,7 +3,7 @@ var crypto = require('crypto');
var bignum = require('bignum');
var Binary = require('binary');
var Put = require('bufferput');
require('buffertools').extend();
var buffertools = require('buffertools');
var sha256 = exports.sha256 = function (data) {
return new Buffer(crypto.createHash('sha256').update(data).digest('binary'), 'binary');
@ -29,20 +29,18 @@ var sha256ripe160 = exports.sha256ripe160 = function (data) {
* Format a block hash like the official client does.
*/
var formatHash = exports.formatHash = function (hash) {
// Make a copy, because reverse() and toHex() are destructive.
var hashEnd = new Buffer(10);
hash.copy(hashEnd, 0, 22, 32);
return hashEnd.reverse().toString('hex');
return buffertools.reverse(hashEnd).toString('hex');
};
/**
* Display the whole hash, as hex, in correct endian order.
*/
var formatHashFull = exports.formatHashFull = function (hash) {
// Make a copy, because reverse() and toHex() are destructive.
var copy = new Buffer(hash.length);
hash.copy(copy);
var hex = copy.reverse().toHex();
var hex = buffertools.toHex(buffertools.reverse(copy));
return hex;
};
@ -71,7 +69,7 @@ var formatBuffer = exports.formatBuffer = function (buffer, maxLen) {
buffer.copy(temp, 0, 0, maxLen);
// Format as string
var output = temp.toHex();
var output = buffertools.toHex(temp);
if (temp.length < buffer.length) {
output += "...";
}
@ -225,7 +223,8 @@ var decodeDiffBits = exports.decodeDiffBits = function (diffBits, asBigInt) {
// Convert to buffer
var diffBuf = target.toBuffer();
var targetBuf = new Buffer(32).fill(0);
var targetBuf = new Buffer(32);
buffertools.fill(targetBuf, 0);
diffBuf.copy(targetBuf, 32-diffBuf.length);
return targetBuf;
};
@ -321,13 +320,13 @@ var varIntBuf = exports.varIntBuf = function varIntBuf(n) {
};
var varStrBuf = exports.varStrBuf = function varStrBuf(s) {
return Buffer.concat(varIntBuf(s.length), s);
return Buffer.concat([varIntBuf(s.length), s]);
};
// Initializations
exports.NULL_HASH = new Buffer(32).fill(0);
exports.NULL_HASH = buffertools.fill(new Buffer(32), 0);
exports.EMPTY_BUFFER = new Buffer(0);
exports.ZERO_VALUE = new Buffer(8).fill(0);
exports.ZERO_VALUE = buffertools.fill(new Buffer(8), 0);
var INT64_MAX = new Buffer('ffffffffffffffff', 'hex');
exports.INT64_MAX = INT64_MAX;