2018-12-29 13:39:19 +01:00
|
|
|
|
2017-05-23 07:14:08 +02:00
|
|
|
|
2018-12-28 04:59:43 +01:00
|
|
|
export function decode (buffer: Buffer, maxLength?: number, minimal?: boolean): number {
|
2016-01-04 15:59:14 +01:00
|
|
|
maxLength = maxLength || 4
|
|
|
|
minimal = minimal === undefined ? true : minimal
|
|
|
|
|
2018-06-25 08:37:45 +02:00
|
|
|
const length = buffer.length
|
2016-01-04 15:59:14 +01:00
|
|
|
if (length === 0) return 0
|
|
|
|
if (length > maxLength) throw new TypeError('Script number overflow')
|
|
|
|
if (minimal) {
|
|
|
|
if ((buffer[length - 1] & 0x7f) === 0) {
|
|
|
|
if (length <= 1 || (buffer[length - 2] & 0x80) === 0) throw new Error('Non-minimally encoded script number')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-04 16:18:50 +01:00
|
|
|
// 40-bit
|
|
|
|
if (length === 5) {
|
2018-06-25 08:37:45 +02:00
|
|
|
const a = buffer.readUInt32LE(0)
|
|
|
|
const b = buffer.readUInt8(4)
|
2016-01-04 15:59:14 +01:00
|
|
|
|
2017-04-19 09:24:58 +02:00
|
|
|
if (b & 0x80) return -(((b & ~0x80) * 0x100000000) + a)
|
|
|
|
return (b * 0x100000000) + a
|
2016-01-04 16:38:04 +01:00
|
|
|
}
|
2016-01-04 15:59:14 +01:00
|
|
|
|
2016-01-04 16:38:04 +01:00
|
|
|
// 32-bit / 24-bit / 16-bit / 8-bit
|
2018-06-25 08:37:45 +02:00
|
|
|
let result = 0
|
2016-01-04 16:38:04 +01:00
|
|
|
for (var i = 0; i < length; ++i) {
|
|
|
|
result |= buffer[i] << (8 * i)
|
2016-01-04 15:59:14 +01:00
|
|
|
}
|
|
|
|
|
2016-01-04 16:18:50 +01:00
|
|
|
if (buffer[length - 1] & 0x80) return -(result & ~(0x80 << (8 * (length - 1))))
|
|
|
|
return result
|
2016-01-04 15:59:14 +01:00
|
|
|
}
|
|
|
|
|
2018-12-28 16:53:54 +01:00
|
|
|
function scriptNumSize (i: number): number {
|
2016-01-04 15:59:14 +01:00
|
|
|
return i > 0x7fffffff ? 5
|
2018-05-29 03:37:03 +02:00
|
|
|
: i > 0x7fffff ? 4
|
|
|
|
: i > 0x7fff ? 3
|
|
|
|
: i > 0x7f ? 2
|
|
|
|
: i > 0x00 ? 1
|
|
|
|
: 0
|
2016-01-04 15:59:14 +01:00
|
|
|
}
|
|
|
|
|
2018-12-28 04:59:43 +01:00
|
|
|
export function encode (number: number): Buffer {
|
2018-06-25 08:37:45 +02:00
|
|
|
let value = Math.abs(number)
|
|
|
|
const size = scriptNumSize(value)
|
|
|
|
const buffer = Buffer.allocUnsafe(size)
|
|
|
|
const negative = number < 0
|
2016-01-04 15:59:14 +01:00
|
|
|
|
|
|
|
for (var i = 0; i < size; ++i) {
|
|
|
|
buffer.writeUInt8(value & 0xff, i)
|
|
|
|
value >>= 8
|
|
|
|
}
|
|
|
|
|
|
|
|
if (buffer[size - 1] & 0x80) {
|
|
|
|
buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1)
|
|
|
|
} else if (negative) {
|
|
|
|
buffer[size - 1] |= 0x80
|
|
|
|
}
|
|
|
|
|
|
|
|
return buffer
|
|
|
|
}
|