Merge pull request #117 from mbelshe/master

* Fix size bug in bitcore's getVarIntSize.
This commit is contained in:
Ryan X. Charles 2014-03-07 08:17:08 -06:00
commit 1a9c062760
3 changed files with 61 additions and 9 deletions

View File

@ -145,15 +145,16 @@ Bitcoin.Util = {
if (i < 0xfd) {
// unsigned char
return [i];
} else if (i <= 1<<16) {
} else if (i < 0x10000) {
// unsigned short (LE)
return [0xfd, i >>> 8, i & 255];
} else if (i <= 1<<32) {
return [0xfd, i & 255 , i >>> 8];
} else if (i < 0x100000000) {
// unsigned int (LE)
return [0xfe].concat(Crypto.util.wordsToBytes([i]));
return [0xfe].concat(Crypto.util.wordsToBytes([i]).reverse());
} else {
throw 'quadword not implemented'
// unsigned long long (LE)
return [0xff].concat(Crypto.util.wordsToBytes([i >>> 32, i]));
//return [0xff].concat(Crypto.util.wordsToBytes([i >>> 32, i]));
}
},

View File

@ -65,4 +65,52 @@ describe('util', function() {
});
});
});
describe('#varIntBuf', function() {
var data = [
[0, '00' ],
[1, '01'],
[253, 'fdfd00'],
[254, 'fdfe00'],
[255, 'fdff00'],
[0x100, 'fd0001'],
[0x1000, 'fd0010'],
[0x1001, 'fd0110'],
[0x10000, 'fe00000100'],
[0x12345, 'fe45230100'],
[0x12345678, 'fe78563412'],
[0x123456789a, 'ff9a78563412000000'],
[0x123456789abcde, 'ffdebc9a7856341200'],
];
data.forEach(function(datum) {
var integer = datum[0];
var result = datum[1];
it('should work for ' + integer, function() {
buffertools.toHex(coinUtil.varIntBuf(integer)).should.equal(result);
});
});
});
describe('#getVarIntSize', function() {
var data = [
[0, 1 ],
[1, 1],
[252, 1],
[253, 3],
[254, 3],
[0x100, 3],
[0x1000, 3],
[0x1001, 3],
[0x10000, 5],
[0x10001, 5],
[0xffffffff, 5],
[0x100000000, 9],
[0x100000001, 9],
];
data.forEach(function(datum) {
var integer = datum[0];
var result = datum[1];
it('should work for ' + integer, function() {
coinUtil.getVarIntSize(integer).should.equal(result);
});
});
});
});

View File

@ -321,13 +321,13 @@ var reverseBytes32 = exports.reverseBytes32 = function (data) {
var getVarIntSize = exports.getVarIntSize = function getVarIntSize(i) {
if (i < 0xFD) {
if (i < 253) {
// unsigned char
return 1;
} else if (i <= 1<<16) {
} else if (i < 0x10000) {
// unsigned short (LE)
return 3;
} else if (i <= 1<<32) {
} else if (i < 0x100000000) {
// unsigned int (LE)
return 5;
} else {
@ -350,7 +350,10 @@ var varIntBuf = exports.varIntBuf = function varIntBuf(n) {
buf.writeUInt8(254, 0);
buf.writeUInt32LE(n, 1);
} else {
throw new Error("quadword not supported");
buf = new Buffer(1 + 8);
buf.writeUInt8(255, 0);
buf.writeInt32LE(n & -1, 1);
buf.writeUInt32LE(Math.floor(n / 0x100000000), 5);
}
return buf;