2016-12-17 15:24:00 +01:00
|
|
|
var pushdata = require('pushdata-bitcoin')
|
2016-10-06 12:53:48 +02:00
|
|
|
var varuint = require('varuint-bitcoin')
|
2014-05-31 05:18:57 +02:00
|
|
|
|
2016-10-06 12:53:48 +02:00
|
|
|
// https://github.com/feross/buffer/blob/master/index.js#L1127
|
|
|
|
function verifuint (value, max) {
|
|
|
|
if (typeof value !== 'number') throw new Error('cannot write a non-number as a number')
|
|
|
|
if (value < 0) throw new Error('specified a negative value for writing an unsigned value')
|
|
|
|
if (value > max) throw new Error('RangeError: value out of range')
|
|
|
|
if (Math.floor(value) !== value) throw new Error('value has a fractional component')
|
|
|
|
}
|
|
|
|
|
2015-02-23 00:36:57 +01:00
|
|
|
function readUInt64LE (buffer, offset) {
|
2014-05-01 11:38:18 +02:00
|
|
|
var a = buffer.readUInt32LE(offset)
|
|
|
|
var b = buffer.readUInt32LE(offset + 4)
|
|
|
|
b *= 0x100000000
|
|
|
|
|
2014-05-31 05:18:57 +02:00
|
|
|
verifuint(b + a, 0x001fffffffffffff)
|
2014-05-01 11:38:18 +02:00
|
|
|
|
|
|
|
return b + a
|
|
|
|
}
|
|
|
|
|
2015-02-23 00:36:57 +01:00
|
|
|
function writeUInt64LE (buffer, value, offset) {
|
2014-05-31 05:18:57 +02:00
|
|
|
verifuint(value, 0x001fffffffffffff)
|
2014-05-01 11:38:18 +02:00
|
|
|
|
|
|
|
buffer.writeInt32LE(value & -1, offset)
|
|
|
|
buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4)
|
2016-10-09 13:53:41 +02:00
|
|
|
return offset + 8
|
2014-05-01 11:38:18 +02:00
|
|
|
}
|
|
|
|
|
2016-10-06 12:53:48 +02:00
|
|
|
// TODO: remove in 4.0.0?
|
|
|
|
function readVarInt (buffer, offset) {
|
|
|
|
var result = varuint.decode(buffer, offset)
|
2014-05-01 11:38:18 +02:00
|
|
|
|
2016-10-06 12:53:48 +02:00
|
|
|
return {
|
|
|
|
number: result,
|
|
|
|
size: varuint.decode.bytes
|
2014-05-01 11:38:18 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-06 12:53:48 +02:00
|
|
|
// TODO: remove in 4.0.0?
|
|
|
|
function writeVarInt (buffer, number, offset) {
|
|
|
|
varuint.encode(number, buffer, offset)
|
|
|
|
return varuint.encode.bytes
|
2014-10-17 04:07:14 +02:00
|
|
|
}
|
|
|
|
|
2014-05-01 11:38:18 +02:00
|
|
|
module.exports = {
|
2016-12-17 15:24:00 +01:00
|
|
|
pushDataSize: pushdata.encodingLength,
|
|
|
|
readPushDataInt: pushdata.decode,
|
2014-05-01 11:38:18 +02:00
|
|
|
readUInt64LE: readUInt64LE,
|
|
|
|
readVarInt: readVarInt,
|
2016-10-06 12:53:48 +02:00
|
|
|
varIntBuffer: varuint.encode,
|
|
|
|
varIntSize: varuint.encodingLength,
|
2016-12-17 15:24:00 +01:00
|
|
|
writePushDataInt: pushdata.encode,
|
2014-05-01 11:38:18 +02:00
|
|
|
writeUInt64LE: writeUInt64LE,
|
2016-10-06 12:53:48 +02:00
|
|
|
writeVarInt: writeVarInt
|
2014-05-01 11:38:18 +02:00
|
|
|
}
|