scriptnum: improve encoding.

This commit is contained in:
Christopher Jeffrey 2017-08-17 09:59:17 -07:00
parent 668202b2f9
commit a47d68024a
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD

View File

@ -43,14 +43,14 @@ Object.setPrototypeOf(ScriptNum.prototype, I64.prototype);
* @returns {Number}
*/
ScriptNum.prototype.toInt = function toInt() {
if (this.lt(I64.UINT32_MIN))
ScriptNum.prototype.getInt = function getInt() {
if (this.lt(I64.INT32_MIN))
return I64.LONG_MIN;
if (this.gt(I64.UINT32_MAX))
if (this.gt(I64.INT32_MAX))
return I64.LONG_MAX;
return this.lo;
return this.toInt();
};
/**
@ -128,6 +128,7 @@ ScriptNum.prototype.toRaw = function toRaw() {
ScriptNum.prototype.fromRaw = function fromRaw(data) {
assert(Buffer.isBuffer(data));
assert(data.length <= 9);
// Empty arrays are always zero.
if (data.length === 0)
@ -240,6 +241,30 @@ ScriptNum.isMinimal = function isMinimal(data) {
return true;
};
/**
* Encode a script number.
* @param {Number|ScriptNum|BN} num
* @returns {Buffer}
*/
ScriptNum.encode = function encode(num) {
assert(num != null);
if (ScriptNum.isScriptNum(num))
return num.encode();
if (typeof num === 'number')
num = ScriptNum.fromNumber(num);
else if (I64.isN64(num))
num = ScriptNum.fromObject(num);
else if (Array.isArray(num.words))
num = ScriptNum.fromBN(num);
else
throw new Error('Object must be encodable.');
return num.encode();
};
/**
* Decode and verify script number.
* @param {Buffer} data
@ -252,6 +277,31 @@ ScriptNum.decode = function decode(data, minimal, limit) {
return new ScriptNum().decode(data, minimal, limit);
};
/**
* Test whether object is encodable.
* @param {Object} obj
* @returns {Boolean}
*/
ScriptNum.isEncodable = function isEncodable(obj) {
if (obj == null)
return false;
if (ScriptNum.isScriptNum(obj))
return true;
if (typeof obj === 'number')
return true;
if (I64.isN64(obj))
return true;
if (Array.isArray(obj.words))
return true;
return false;
};
/**
* Test whether object is a script number.
* @param {Object} obj