Skip to content

Commit

Permalink
scriptnum: improve encoding.
Browse files Browse the repository at this point in the history
  • Loading branch information
chjj committed Aug 17, 2017
1 parent 668202b commit a47d680
Showing 1 changed file with 54 additions and 4 deletions.
58 changes: 54 additions & 4 deletions lib/script/scriptnum.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
};

/**
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit a47d680

Please sign in to comment.