From 5bd3786f94a5cad455c2d0e7ba94f56e86e8a9b4 Mon Sep 17 00:00:00 2001 From: kinoshitajona Date: Thu, 14 Nov 2019 15:07:15 +0900 Subject: [PATCH 1/2] Fix ScriptNum --- js/coin.js | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/js/coin.js b/js/coin.js index b25c197..443a261 100644 --- a/js/coin.js +++ b/js/coin.js @@ -156,7 +156,7 @@ } var s = coinjs.script(); - s.writeBytes(coinjs.numToByteArray(checklocktimeverify)); + s.writeBytes(coinjs.numToScriptNumBytes(checklocktimeverify)); s.writeOp(177);//OP_CHECKLOCKTIMEVERIFY s.writeOp(117);//OP_DROP s.writeBytes(Crypto.util.hexToBytes(pubkey)); @@ -1924,12 +1924,34 @@ } } - coinjs.numToByteArray = function(num) { - if (num <= 256) { - return [num]; - } else { - return [num % 256].concat(coinjs.numToByteArray(Math.floor(num / 256))); + function scriptNumSize(i) { + return i > 0x7fffffff ? 5 + : i > 0x7fffff ? 4 + : i > 0x7fff ? 3 + : i > 0x7f ? 2 + : i > 0x00 ? 1 + : 0; + } + + coinjs.numToScriptNumBytes = function(_number) { + if (_number <= 16 && _number >= 1 && _number === Math.floor(_number)) { + return [0x50 + _number] // OP_1 to OP_16 for minimal encoding } + var value = Math.abs(_number); + var size = scriptNumSize(value); + var result = []; + for (var i = 0; i < size; ++i) { + result.push(0); + } + var negative = _number < 0; + for (i = 0; i < size; ++i) { + result[i] = value & 0xff; + value = Math.floor(value / 256); + } + if (negative) { + result[size - 1] |= 0x80; + } + return result; } coinjs.numToVarInt = function(num) { From d4f47fce28db6fd8959a3648671a2d49771320e3 Mon Sep 17 00:00:00 2001 From: kinoshitajona Date: Thu, 14 Nov 2019 15:13:51 +0900 Subject: [PATCH 2/2] Must do OPs with script method --- js/coin.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/js/coin.js b/js/coin.js index 443a261..9f46bcb 100644 --- a/js/coin.js +++ b/js/coin.js @@ -156,7 +156,11 @@ } var s = coinjs.script(); - s.writeBytes(coinjs.numToScriptNumBytes(checklocktimeverify)); + if (checklocktimeverify <= 16 && checklocktimeverify >= 1) { + s.writeOp(0x50 + checklocktimeverify);//OP_1 to OP_16 for minimal encoding + } else { + s.writeBytes(coinjs.numToScriptNumBytes(checklocktimeverify)); + } s.writeOp(177);//OP_CHECKLOCKTIMEVERIFY s.writeOp(117);//OP_DROP s.writeBytes(Crypto.util.hexToBytes(pubkey)); @@ -1934,9 +1938,6 @@ } coinjs.numToScriptNumBytes = function(_number) { - if (_number <= 16 && _number >= 1 && _number === Math.floor(_number)) { - return [0x50 + _number] // OP_1 to OP_16 for minimal encoding - } var value = Math.abs(_number); var size = scriptNumSize(value); var result = [];