diff --git a/src/bufferutils.js b/src/bufferutils.js index 05364e1..858a934 100644 --- a/src/bufferutils.js +++ b/src/bufferutils.js @@ -159,11 +159,18 @@ function writeVarInt(buffer, number, offset) { return size } +function reverse(buffer) { + var buffer2 = new Buffer(buffer) + Array.prototype.reverse.call(buffer2) + return buffer2 +} + module.exports = { pushDataSize: pushDataSize, readPushDataInt: readPushDataInt, readUInt64LE: readUInt64LE, readVarInt: readVarInt, + reverse: reverse, varIntSize: varIntSize, writePushDataInt: writePushDataInt, writeUInt64LE: writeUInt64LE, diff --git a/src/transaction.js b/src/transaction.js index a9a0899..91be756 100644 --- a/src/transaction.js +++ b/src/transaction.js @@ -37,10 +37,8 @@ Transaction.prototype.addInput = function(tx, index, sequence) { var hash if (typeof tx === 'string') { - hash = new Buffer(tx, 'hex') - // TxId hex is big-endian, we need little-endian - Array.prototype.reverse.call(hash) + hash = bufferutils.reverse(new Buffer(tx, 'hex')) } else if (tx instanceof Transaction) { hash = tx.getHash() @@ -211,12 +209,8 @@ Transaction.prototype.getHash = function () { } Transaction.prototype.getId = function () { - var buffer = this.getHash() - - // Big-endian is used for TxHash - Array.prototype.reverse.call(buffer) - - return buffer.toString('hex') + // TxHash is little-endian, we need big-endian + return bufferutils.reverse(this.getHash()).toString('hex') } Transaction.prototype.clone = function () { diff --git a/src/wallet.js b/src/wallet.js index 26f8bfd..f3f0adf 100644 --- a/src/wallet.js +++ b/src/wallet.js @@ -1,4 +1,5 @@ var assert = require('assert') +var bufferutils = require('./bufferutils') var crypto = require('crypto') var networks = require('./networks') @@ -123,10 +124,7 @@ Wallet.prototype.__processTx = function(tx, isPending) { tx.ins.forEach(function(txIn, i) { // copy and convert to big-endian hex - var txinId = new Buffer(txIn.hash) - Array.prototype.reverse.call(txinId) - txinId = txinId.toString('hex') - + var txinId = bufferutils.reverse(txIn.hash).toString('hex') var output = txinId + ':' + txIn.index if (!(output in this.outputs)) return diff --git a/test/bufferutils.js b/test/bufferutils.js index d7dbfa3..447d516 100644 --- a/test/bufferutils.js +++ b/test/bufferutils.js @@ -75,6 +75,19 @@ describe('bufferutils', function() { }) }) + describe('reverse', function() { + fixtures.valid.forEach(function(f) { + it('reverses ' + f.hex64 + ' correctly', function() { + var buffer = new Buffer(f.hex64, 'hex') + var buffer2 = bufferutils.reverse(buffer) + + Array.prototype.reverse.call(buffer) + + assert.deepEqual(buffer, buffer2) + }) + }) + }) + describe('varIntSize', function() { fixtures.valid.forEach(function(f) { it('determines the varIntSize of ' + f.dec + ' correctly', function() {