scrypt-ts
Advanced tools
Comparing version 0.1.5-beta.6 to 0.1.5-test.1
@@ -134,14 +134,2 @@ import { SigHashType } from "scryptlib"; | ||
/** | ||
* @category bitwise | ||
*/ | ||
/** | ||
* @category bitwise | ||
*/ | ||
/** | ||
* @category bitwise | ||
*/ | ||
/** | ||
* @category bitwise | ||
*/ | ||
/** | ||
* @category bitshift | ||
@@ -148,0 +136,0 @@ */ |
@@ -5,4 +5,4 @@ "use strict"; | ||
exports.Constants = exports.Tx = exports.VarIntWriter = exports.VarIntReader = exports.SigHash = exports.Utils = exports.OpCode = exports.asm = exports.rshift = exports.lshift = exports.pow2 = exports.assert = exports.flattenSha256 = exports.hash256 = exports.hash160 = exports.sha256 = exports.sha1 = exports.ripemd160 = exports.within = exports.max = exports.min = exports.abs = exports.exit = exports.checkMultiSig = exports.reverseBytes = exports.len = exports.int2str = exports.unpack = exports.pack = exports.getSortedItem = exports.invert = exports.or = exports.xor = exports.and = void 0; | ||
const scryptlib_1 = require("scryptlib"); | ||
const types_1 = require("./types"); | ||
var scryptlib_1 = require("scryptlib"); | ||
var types_1 = require("./types"); | ||
var builtins_1 = require("scryptlib/dist/builtins"); | ||
@@ -20,3 +20,3 @@ Object.defineProperty(exports, "and", { enumerable: true, get: function () { return builtins_1.and; } }); | ||
function pack(n) { | ||
const num = new scryptlib_1.bsv.crypto.BN(n); | ||
var num = new scryptlib_1.bsv.crypto.BN(n); | ||
return num.toSM({ endian: 'little' }).toString('hex'); | ||
@@ -61,5 +61,5 @@ } | ||
function reverseBytes(b, size) { | ||
let l = len(b); | ||
var l = len(b); | ||
if (l != size) { | ||
throw new Error(`reverseBytes error, expected c = ${l}`); | ||
throw new Error("reverseBytes error, expected c = ".concat(l)); | ||
} | ||
@@ -202,3 +202,3 @@ return b.match(/[a-fA-F0-9]{2}/g).reverse().join(''); | ||
if (!condition) { | ||
const message = 'Execution failed' + (msg ? `, ${msg}` : ''); | ||
var message = 'Execution failed' + (msg ? ", ".concat(msg) : ''); | ||
throw new Error(message); | ||
@@ -220,2 +220,9 @@ } | ||
*/ | ||
function simplePow(x, y) { | ||
var calced = (0, scryptlib_1.Int)(1); | ||
for (var i = 0, e = y; i < e; i++) { | ||
calced *= x; | ||
} | ||
return calced; | ||
} | ||
/** | ||
@@ -225,3 +232,3 @@ * @category bitshift | ||
function pow2(n) { | ||
return 2n ** n; | ||
return simplePow((0, scryptlib_1.Int)(2), n); | ||
} | ||
@@ -243,4 +250,4 @@ exports.pow2 = pow2; | ||
assert(n >= 0); | ||
let ret = x / pow2(n); | ||
return n == 0n ? x : (x % 2n == -1n ? (ret - 1n) : (x < 0n && ret == 0n) ? -1n : ret); | ||
var ret = x / pow2(n); | ||
return n == (0, scryptlib_1.Int)(0) ? x : (x % (0, scryptlib_1.Int)(2) == (0, scryptlib_1.Int)(-1) ? (ret - (0, scryptlib_1.Int)(1)) : (x < (0, scryptlib_1.Int)(0) && ret == (0, scryptlib_1.Int)(0)) ? (0, scryptlib_1.Int)(-1) : ret); | ||
} | ||
@@ -259,146 +266,151 @@ exports.rshift = rshift; | ||
*/ | ||
class OpCode { | ||
} | ||
var OpCode = /** @class */ (function () { | ||
function OpCode() { | ||
} | ||
// push value | ||
OpCode.OP_0 = (0, types_1.OpCodeType)('00'); | ||
OpCode.OP_FALSE = (0, types_1.OpCodeType)('00'); | ||
OpCode.OP_PUSHDATA1 = (0, types_1.OpCodeType)('4c'); | ||
OpCode.OP_PUSHDATA2 = (0, types_1.OpCodeType)('4d'); | ||
OpCode.OP_PUSHDATA4 = (0, types_1.OpCodeType)('4e'); | ||
OpCode.OP_1NEGATE = (0, types_1.OpCodeType)('4f'); | ||
OpCode.OP_RESERVED = (0, types_1.OpCodeType)('50'); | ||
OpCode.OP_1 = (0, types_1.OpCodeType)('51'); | ||
OpCode.OP_TRUE = (0, types_1.OpCodeType)('51'); | ||
OpCode.OP_2 = (0, types_1.OpCodeType)('52'); | ||
OpCode.OP_3 = (0, types_1.OpCodeType)('53'); | ||
OpCode.OP_4 = (0, types_1.OpCodeType)('54'); | ||
OpCode.OP_5 = (0, types_1.OpCodeType)('55'); | ||
OpCode.OP_6 = (0, types_1.OpCodeType)('56'); | ||
OpCode.OP_7 = (0, types_1.OpCodeType)('57'); | ||
OpCode.OP_8 = (0, types_1.OpCodeType)('58'); | ||
OpCode.OP_9 = (0, types_1.OpCodeType)('59'); | ||
OpCode.OP_10 = (0, types_1.OpCodeType)('5a'); | ||
OpCode.OP_11 = (0, types_1.OpCodeType)('5b'); | ||
OpCode.OP_12 = (0, types_1.OpCodeType)('5c'); | ||
OpCode.OP_13 = (0, types_1.OpCodeType)('5d'); | ||
OpCode.OP_14 = (0, types_1.OpCodeType)('5e'); | ||
OpCode.OP_15 = (0, types_1.OpCodeType)('5f'); | ||
OpCode.OP_16 = (0, types_1.OpCodeType)('60'); | ||
// control | ||
OpCode.OP_NOP = (0, types_1.OpCodeType)('61'); | ||
OpCode.OP_VER = (0, types_1.OpCodeType)('62'); | ||
OpCode.OP_IF = (0, types_1.OpCodeType)('63'); | ||
OpCode.OP_NOTIF = (0, types_1.OpCodeType)('64'); | ||
OpCode.OP_VERIF = (0, types_1.OpCodeType)('65'); | ||
OpCode.OP_VERNOTIF = (0, types_1.OpCodeType)('66'); | ||
OpCode.OP_ELSE = (0, types_1.OpCodeType)('67'); | ||
OpCode.OP_ENDIF = (0, types_1.OpCodeType)('68'); | ||
OpCode.OP_VERIFY = (0, types_1.OpCodeType)('69'); | ||
OpCode.OP_RETURN = (0, types_1.OpCodeType)('6a'); | ||
// stack ops | ||
OpCode.OP_TOALTSTACK = (0, types_1.OpCodeType)('6b'); | ||
OpCode.OP_FROMALTSTACK = (0, types_1.OpCodeType)('6c'); | ||
OpCode.OP_2DROP = (0, types_1.OpCodeType)('6d'); | ||
OpCode.OP_2DUP = (0, types_1.OpCodeType)('6e'); | ||
OpCode.OP_3DUP = (0, types_1.OpCodeType)('6f'); | ||
OpCode.OP_2OVER = (0, types_1.OpCodeType)('70'); | ||
OpCode.OP_2ROT = (0, types_1.OpCodeType)('71'); | ||
OpCode.OP_2SWAP = (0, types_1.OpCodeType)('72'); | ||
OpCode.OP_IFDUP = (0, types_1.OpCodeType)('73'); | ||
OpCode.OP_DEPTH = (0, types_1.OpCodeType)('74'); | ||
OpCode.OP_DROP = (0, types_1.OpCodeType)('75'); | ||
OpCode.OP_DUP = (0, types_1.OpCodeType)('76'); | ||
OpCode.OP_NIP = (0, types_1.OpCodeType)('77'); | ||
OpCode.OP_OVER = (0, types_1.OpCodeType)('78'); | ||
OpCode.OP_PICK = (0, types_1.OpCodeType)('79'); | ||
OpCode.OP_ROLL = (0, types_1.OpCodeType)('7a'); | ||
OpCode.OP_ROT = (0, types_1.OpCodeType)('7b'); | ||
OpCode.OP_SWAP = (0, types_1.OpCodeType)('7c'); | ||
OpCode.OP_TUCK = (0, types_1.OpCodeType)('7d'); | ||
// splice ops | ||
OpCode.OP_CAT = (0, types_1.OpCodeType)('7e'); | ||
OpCode.OP_SPLIT = (0, types_1.OpCodeType)('7f'); // after monolith upgrade (May 2018) | ||
OpCode.OP_NUM2BIN = (0, types_1.OpCodeType)('80'); // after monolith upgrade (May 2018) | ||
OpCode.OP_BIN2NUM = (0, types_1.OpCodeType)('81'); // after monolith upgrade (May 2018) | ||
OpCode.OP_SIZE = (0, types_1.OpCodeType)('82'); | ||
// bit logic | ||
OpCode.OP_INVERT = (0, types_1.OpCodeType)('83'); | ||
OpCode.OP_AND = (0, types_1.OpCodeType)('84'); | ||
OpCode.OP_OR = (0, types_1.OpCodeType)('85'); | ||
OpCode.OP_XOR = (0, types_1.OpCodeType)('86'); | ||
OpCode.OP_EQUAL = (0, types_1.OpCodeType)('87'); | ||
OpCode.OP_EQUALVERIFY = (0, types_1.OpCodeType)('88'); | ||
OpCode.OP_RESERVED1 = (0, types_1.OpCodeType)('89'); | ||
OpCode.OP_RESERVED2 = (0, types_1.OpCodeType)('8a'); | ||
// numeric | ||
OpCode.OP_1ADD = (0, types_1.OpCodeType)('8b'); | ||
OpCode.OP_1SUB = (0, types_1.OpCodeType)('8c'); | ||
OpCode.OP_2MUL = (0, types_1.OpCodeType)('8d'); | ||
OpCode.OP_2DIV = (0, types_1.OpCodeType)('8e'); | ||
OpCode.OP_NEGATE = (0, types_1.OpCodeType)('8f'); | ||
OpCode.OP_ABS = (0, types_1.OpCodeType)('90'); | ||
OpCode.OP_NOT = (0, types_1.OpCodeType)('91'); | ||
OpCode.OP_0NOTEQUAL = (0, types_1.OpCodeType)('92'); | ||
OpCode.OP_ADD = (0, types_1.OpCodeType)('93'); | ||
OpCode.OP_SUB = (0, types_1.OpCodeType)('94'); | ||
OpCode.OP_MUL = (0, types_1.OpCodeType)('95'); | ||
OpCode.OP_DIV = (0, types_1.OpCodeType)('96'); | ||
OpCode.OP_MOD = (0, types_1.OpCodeType)('97'); | ||
OpCode.OP_LSHIFT = (0, types_1.OpCodeType)('98'); | ||
OpCode.OP_RSHIFT = (0, types_1.OpCodeType)('99'); | ||
OpCode.OP_BOOLAND = (0, types_1.OpCodeType)('9a'); | ||
OpCode.OP_BOOLOR = (0, types_1.OpCodeType)('9b'); | ||
OpCode.OP_NUMEQUAL = (0, types_1.OpCodeType)('9c'); | ||
OpCode.OP_NUMEQUALVERIFY = (0, types_1.OpCodeType)('9d'); | ||
OpCode.OP_NUMNOTEQUAL = (0, types_1.OpCodeType)('9e'); | ||
OpCode.OP_LESSTHAN = (0, types_1.OpCodeType)('9f'); | ||
OpCode.OP_GREATERTHAN = (0, types_1.OpCodeType)('a0'); | ||
OpCode.OP_LESSTHANOREQUAL = (0, types_1.OpCodeType)('a1'); | ||
OpCode.OP_GREATERTHANOREQUAL = (0, types_1.OpCodeType)('a2'); | ||
OpCode.OP_MIN = (0, types_1.OpCodeType)('a3'); | ||
OpCode.OP_MAX = (0, types_1.OpCodeType)('a4'); | ||
OpCode.OP_WITHIN = (0, types_1.OpCodeType)('a5'); | ||
// crypto | ||
OpCode.OP_RIPEMD160 = (0, types_1.OpCodeType)('a6'); | ||
OpCode.OP_SHA1 = (0, types_1.OpCodeType)('a7'); | ||
OpCode.OP_SHA256 = (0, types_1.OpCodeType)('a8'); | ||
OpCode.OP_HASH160 = (0, types_1.OpCodeType)('a9'); | ||
OpCode.OP_HASH256 = (0, types_1.OpCodeType)('aa'); | ||
OpCode.OP_CODESEPARATOR = (0, types_1.OpCodeType)('ab'); | ||
OpCode.OP_CHECKSIG = (0, types_1.OpCodeType)('ac'); | ||
OpCode.OP_CHECKSIGVERIFY = (0, types_1.OpCodeType)('ad'); | ||
OpCode.OP_CHECKMULTISIG = (0, types_1.OpCodeType)('ae'); | ||
OpCode.OP_CHECKMULTISIGVERIFY = (0, types_1.OpCodeType)('af'); | ||
// expansion | ||
OpCode.OP_NOP1 = (0, types_1.OpCodeType)('b0'); | ||
OpCode.OP_NOP2 = (0, types_1.OpCodeType)('b1'); // previously OP_CHECKLOCKTIMEVERIFY | ||
OpCode.OP_NOP3 = (0, types_1.OpCodeType)('b2'); // OpCode.OP_CHECKSEQUENCEVERIFY; | ||
OpCode.OP_NOP4 = (0, types_1.OpCodeType)('b3'); | ||
OpCode.OP_NOP5 = (0, types_1.OpCodeType)('b4'); | ||
OpCode.OP_NOP6 = (0, types_1.OpCodeType)('b5'); | ||
OpCode.OP_NOP7 = (0, types_1.OpCodeType)('b6'); | ||
OpCode.OP_NOP8 = (0, types_1.OpCodeType)('b7'); | ||
OpCode.OP_NOP9 = (0, types_1.OpCodeType)('b8'); | ||
OpCode.OP_NOP10 = (0, types_1.OpCodeType)('b9'); | ||
// The first static const OpCodeType OP_code value after all defined opcodes | ||
//FIRST_UNDEFINED_OP_VALUE | ||
// template matching params | ||
OpCode.OP_PUBKEYHASH = (0, types_1.OpCodeType)('fd'); | ||
OpCode.OP_PUBKEY = (0, types_1.OpCodeType)('fe'); | ||
OpCode.OP_INVALIDOPCODE = (0, types_1.OpCodeType)('ff'); | ||
return OpCode; | ||
}()); | ||
exports.OpCode = OpCode; | ||
// push value | ||
OpCode.OP_0 = (0, types_1.OpCodeType)('00'); | ||
OpCode.OP_FALSE = (0, types_1.OpCodeType)('00'); | ||
OpCode.OP_PUSHDATA1 = (0, types_1.OpCodeType)('4c'); | ||
OpCode.OP_PUSHDATA2 = (0, types_1.OpCodeType)('4d'); | ||
OpCode.OP_PUSHDATA4 = (0, types_1.OpCodeType)('4e'); | ||
OpCode.OP_1NEGATE = (0, types_1.OpCodeType)('4f'); | ||
OpCode.OP_RESERVED = (0, types_1.OpCodeType)('50'); | ||
OpCode.OP_1 = (0, types_1.OpCodeType)('51'); | ||
OpCode.OP_TRUE = (0, types_1.OpCodeType)('51'); | ||
OpCode.OP_2 = (0, types_1.OpCodeType)('52'); | ||
OpCode.OP_3 = (0, types_1.OpCodeType)('53'); | ||
OpCode.OP_4 = (0, types_1.OpCodeType)('54'); | ||
OpCode.OP_5 = (0, types_1.OpCodeType)('55'); | ||
OpCode.OP_6 = (0, types_1.OpCodeType)('56'); | ||
OpCode.OP_7 = (0, types_1.OpCodeType)('57'); | ||
OpCode.OP_8 = (0, types_1.OpCodeType)('58'); | ||
OpCode.OP_9 = (0, types_1.OpCodeType)('59'); | ||
OpCode.OP_10 = (0, types_1.OpCodeType)('5a'); | ||
OpCode.OP_11 = (0, types_1.OpCodeType)('5b'); | ||
OpCode.OP_12 = (0, types_1.OpCodeType)('5c'); | ||
OpCode.OP_13 = (0, types_1.OpCodeType)('5d'); | ||
OpCode.OP_14 = (0, types_1.OpCodeType)('5e'); | ||
OpCode.OP_15 = (0, types_1.OpCodeType)('5f'); | ||
OpCode.OP_16 = (0, types_1.OpCodeType)('60'); | ||
// control | ||
OpCode.OP_NOP = (0, types_1.OpCodeType)('61'); | ||
OpCode.OP_VER = (0, types_1.OpCodeType)('62'); | ||
OpCode.OP_IF = (0, types_1.OpCodeType)('63'); | ||
OpCode.OP_NOTIF = (0, types_1.OpCodeType)('64'); | ||
OpCode.OP_VERIF = (0, types_1.OpCodeType)('65'); | ||
OpCode.OP_VERNOTIF = (0, types_1.OpCodeType)('66'); | ||
OpCode.OP_ELSE = (0, types_1.OpCodeType)('67'); | ||
OpCode.OP_ENDIF = (0, types_1.OpCodeType)('68'); | ||
OpCode.OP_VERIFY = (0, types_1.OpCodeType)('69'); | ||
OpCode.OP_RETURN = (0, types_1.OpCodeType)('6a'); | ||
// stack ops | ||
OpCode.OP_TOALTSTACK = (0, types_1.OpCodeType)('6b'); | ||
OpCode.OP_FROMALTSTACK = (0, types_1.OpCodeType)('6c'); | ||
OpCode.OP_2DROP = (0, types_1.OpCodeType)('6d'); | ||
OpCode.OP_2DUP = (0, types_1.OpCodeType)('6e'); | ||
OpCode.OP_3DUP = (0, types_1.OpCodeType)('6f'); | ||
OpCode.OP_2OVER = (0, types_1.OpCodeType)('70'); | ||
OpCode.OP_2ROT = (0, types_1.OpCodeType)('71'); | ||
OpCode.OP_2SWAP = (0, types_1.OpCodeType)('72'); | ||
OpCode.OP_IFDUP = (0, types_1.OpCodeType)('73'); | ||
OpCode.OP_DEPTH = (0, types_1.OpCodeType)('74'); | ||
OpCode.OP_DROP = (0, types_1.OpCodeType)('75'); | ||
OpCode.OP_DUP = (0, types_1.OpCodeType)('76'); | ||
OpCode.OP_NIP = (0, types_1.OpCodeType)('77'); | ||
OpCode.OP_OVER = (0, types_1.OpCodeType)('78'); | ||
OpCode.OP_PICK = (0, types_1.OpCodeType)('79'); | ||
OpCode.OP_ROLL = (0, types_1.OpCodeType)('7a'); | ||
OpCode.OP_ROT = (0, types_1.OpCodeType)('7b'); | ||
OpCode.OP_SWAP = (0, types_1.OpCodeType)('7c'); | ||
OpCode.OP_TUCK = (0, types_1.OpCodeType)('7d'); | ||
// splice ops | ||
OpCode.OP_CAT = (0, types_1.OpCodeType)('7e'); | ||
OpCode.OP_SPLIT = (0, types_1.OpCodeType)('7f'); // after monolith upgrade (May 2018) | ||
OpCode.OP_NUM2BIN = (0, types_1.OpCodeType)('80'); // after monolith upgrade (May 2018) | ||
OpCode.OP_BIN2NUM = (0, types_1.OpCodeType)('81'); // after monolith upgrade (May 2018) | ||
OpCode.OP_SIZE = (0, types_1.OpCodeType)('82'); | ||
// bit logic | ||
OpCode.OP_INVERT = (0, types_1.OpCodeType)('83'); | ||
OpCode.OP_AND = (0, types_1.OpCodeType)('84'); | ||
OpCode.OP_OR = (0, types_1.OpCodeType)('85'); | ||
OpCode.OP_XOR = (0, types_1.OpCodeType)('86'); | ||
OpCode.OP_EQUAL = (0, types_1.OpCodeType)('87'); | ||
OpCode.OP_EQUALVERIFY = (0, types_1.OpCodeType)('88'); | ||
OpCode.OP_RESERVED1 = (0, types_1.OpCodeType)('89'); | ||
OpCode.OP_RESERVED2 = (0, types_1.OpCodeType)('8a'); | ||
// numeric | ||
OpCode.OP_1ADD = (0, types_1.OpCodeType)('8b'); | ||
OpCode.OP_1SUB = (0, types_1.OpCodeType)('8c'); | ||
OpCode.OP_2MUL = (0, types_1.OpCodeType)('8d'); | ||
OpCode.OP_2DIV = (0, types_1.OpCodeType)('8e'); | ||
OpCode.OP_NEGATE = (0, types_1.OpCodeType)('8f'); | ||
OpCode.OP_ABS = (0, types_1.OpCodeType)('90'); | ||
OpCode.OP_NOT = (0, types_1.OpCodeType)('91'); | ||
OpCode.OP_0NOTEQUAL = (0, types_1.OpCodeType)('92'); | ||
OpCode.OP_ADD = (0, types_1.OpCodeType)('93'); | ||
OpCode.OP_SUB = (0, types_1.OpCodeType)('94'); | ||
OpCode.OP_MUL = (0, types_1.OpCodeType)('95'); | ||
OpCode.OP_DIV = (0, types_1.OpCodeType)('96'); | ||
OpCode.OP_MOD = (0, types_1.OpCodeType)('97'); | ||
OpCode.OP_LSHIFT = (0, types_1.OpCodeType)('98'); | ||
OpCode.OP_RSHIFT = (0, types_1.OpCodeType)('99'); | ||
OpCode.OP_BOOLAND = (0, types_1.OpCodeType)('9a'); | ||
OpCode.OP_BOOLOR = (0, types_1.OpCodeType)('9b'); | ||
OpCode.OP_NUMEQUAL = (0, types_1.OpCodeType)('9c'); | ||
OpCode.OP_NUMEQUALVERIFY = (0, types_1.OpCodeType)('9d'); | ||
OpCode.OP_NUMNOTEQUAL = (0, types_1.OpCodeType)('9e'); | ||
OpCode.OP_LESSTHAN = (0, types_1.OpCodeType)('9f'); | ||
OpCode.OP_GREATERTHAN = (0, types_1.OpCodeType)('a0'); | ||
OpCode.OP_LESSTHANOREQUAL = (0, types_1.OpCodeType)('a1'); | ||
OpCode.OP_GREATERTHANOREQUAL = (0, types_1.OpCodeType)('a2'); | ||
OpCode.OP_MIN = (0, types_1.OpCodeType)('a3'); | ||
OpCode.OP_MAX = (0, types_1.OpCodeType)('a4'); | ||
OpCode.OP_WITHIN = (0, types_1.OpCodeType)('a5'); | ||
// crypto | ||
OpCode.OP_RIPEMD160 = (0, types_1.OpCodeType)('a6'); | ||
OpCode.OP_SHA1 = (0, types_1.OpCodeType)('a7'); | ||
OpCode.OP_SHA256 = (0, types_1.OpCodeType)('a8'); | ||
OpCode.OP_HASH160 = (0, types_1.OpCodeType)('a9'); | ||
OpCode.OP_HASH256 = (0, types_1.OpCodeType)('aa'); | ||
OpCode.OP_CODESEPARATOR = (0, types_1.OpCodeType)('ab'); | ||
OpCode.OP_CHECKSIG = (0, types_1.OpCodeType)('ac'); | ||
OpCode.OP_CHECKSIGVERIFY = (0, types_1.OpCodeType)('ad'); | ||
OpCode.OP_CHECKMULTISIG = (0, types_1.OpCodeType)('ae'); | ||
OpCode.OP_CHECKMULTISIGVERIFY = (0, types_1.OpCodeType)('af'); | ||
// expansion | ||
OpCode.OP_NOP1 = (0, types_1.OpCodeType)('b0'); | ||
OpCode.OP_NOP2 = (0, types_1.OpCodeType)('b1'); // previously OP_CHECKLOCKTIMEVERIFY | ||
OpCode.OP_NOP3 = (0, types_1.OpCodeType)('b2'); // OpCode.OP_CHECKSEQUENCEVERIFY; | ||
OpCode.OP_NOP4 = (0, types_1.OpCodeType)('b3'); | ||
OpCode.OP_NOP5 = (0, types_1.OpCodeType)('b4'); | ||
OpCode.OP_NOP6 = (0, types_1.OpCodeType)('b5'); | ||
OpCode.OP_NOP7 = (0, types_1.OpCodeType)('b6'); | ||
OpCode.OP_NOP8 = (0, types_1.OpCodeType)('b7'); | ||
OpCode.OP_NOP9 = (0, types_1.OpCodeType)('b8'); | ||
OpCode.OP_NOP10 = (0, types_1.OpCodeType)('b9'); | ||
// The first static const OpCodeType OP_code value after all defined opcodes | ||
//FIRST_UNDEFINED_OP_VALUE | ||
// template matching params | ||
OpCode.OP_PUBKEYHASH = (0, types_1.OpCodeType)('fd'); | ||
OpCode.OP_PUBKEY = (0, types_1.OpCodeType)('fe'); | ||
OpCode.OP_INVALIDOPCODE = (0, types_1.OpCodeType)('ff'); | ||
/** | ||
* @category Standard Contracts | ||
*/ | ||
class Utils { | ||
var Utils = /** @class */ (function () { | ||
function Utils() { | ||
} | ||
// convert signed integer `n` to unsigned integer of `l` string, in little endian | ||
static toLEUnsigned(n, l) { | ||
let m = int2str(n, l + 1n); | ||
Utils.toLEUnsigned = function (n, l) { | ||
var m = int2str(n, l + (0, scryptlib_1.Int)(1)); | ||
// remove sign byte | ||
return m.slice(0, len(m) * 2 - 2); | ||
} | ||
}; | ||
// convert string to unsigned integer, in sign-magnitude little endian | ||
static fromLEUnsigned(bytes) { | ||
Utils.fromLEUnsigned = function (bytes) { | ||
return unpack(bytes + (0, types_1.toByteString)('00')); | ||
} | ||
}; | ||
/* | ||
@@ -409,65 +421,68 @@ * VarInt (variable integer) is used to encode fields of variable length in a bitcoin transaction | ||
// read a VarInt field from the beginning of 'b' | ||
static readVarint(buf) { | ||
let l = 0n; | ||
let ret = (0, types_1.toByteString)(''); | ||
let header = buf.slice(0, 2); | ||
Utils.readVarint = function (buf) { | ||
var l = (0, scryptlib_1.Int)(0); | ||
var ret = (0, types_1.toByteString)(''); | ||
var header = buf.slice(0, 2); | ||
if (header == (0, types_1.toByteString)('fd')) { | ||
l = Utils.fromLEUnsigned(buf.slice(2, 6)); | ||
ret = buf.slice(6, 6 + Number(l * 2n)); | ||
ret = buf.slice(6, 6 + Number(l * (0, scryptlib_1.Int)(2))); | ||
} | ||
else if (header == (0, types_1.toByteString)('fe')) { | ||
l = Utils.fromLEUnsigned(buf.slice(2, 10)); | ||
ret = buf.slice(10, 10 + Number(l * 2n)); | ||
ret = buf.slice(10, 10 + Number(l * (0, scryptlib_1.Int)(2))); | ||
} | ||
else if (header == (0, types_1.toByteString)('ff')) { | ||
l = Utils.fromLEUnsigned(buf.slice(2, 18)); | ||
ret = buf.slice(18, 18 + Number(l * 2n)); | ||
ret = buf.slice(18, 18 + Number(l * (0, scryptlib_1.Int)(2))); | ||
} | ||
else { | ||
l = Utils.fromLEUnsigned(buf.slice(0, 2)); | ||
ret = buf.slice(2, 2 + Number(l * 2n)); | ||
ret = buf.slice(2, 2 + Number(l * (0, scryptlib_1.Int)(2))); | ||
} | ||
return ret; | ||
} | ||
}; | ||
// convert 'b' to a VarInt field, including the preceding length | ||
static writeVarint(buf) { | ||
let n = len(buf); | ||
let header = (0, types_1.toByteString)(''); | ||
Utils.writeVarint = function (buf) { | ||
var n = len(buf); | ||
var header = (0, types_1.toByteString)(''); | ||
if (n < 0xfd) { | ||
header = Utils.toLEUnsigned(BigInt(n), 1n); | ||
header = Utils.toLEUnsigned((0, scryptlib_1.Int)(n), (0, scryptlib_1.Int)(1)); | ||
} | ||
else if (n < 0x10000) { | ||
header = (0, types_1.toByteString)('fd') + Utils.toLEUnsigned(BigInt(n), 2n); | ||
header = (0, types_1.toByteString)('fd') + Utils.toLEUnsigned((0, scryptlib_1.Int)(n), (0, scryptlib_1.Int)(2)); | ||
} | ||
else if (n < 0x100000000) { | ||
header = (0, types_1.toByteString)('fe') + Utils.toLEUnsigned(BigInt(n), 4n); | ||
header = (0, types_1.toByteString)('fe') + Utils.toLEUnsigned((0, scryptlib_1.Int)(n), (0, scryptlib_1.Int)(4)); | ||
} | ||
else if (n < 0x10000000000000000) { | ||
header = (0, types_1.toByteString)('ff') + Utils.toLEUnsigned(BigInt(n), 8n); | ||
header = (0, types_1.toByteString)('ff') + Utils.toLEUnsigned((0, scryptlib_1.Int)(n), (0, scryptlib_1.Int)(8)); | ||
} | ||
return header + buf; | ||
} | ||
}; | ||
// build a tx output from its script and satoshi amount | ||
static buildOutput(outputScript, outputSatoshis) { | ||
Utils.buildOutput = function (outputScript, outputSatoshis) { | ||
return int2str(outputSatoshis, Constants.OutputValueLen) + Utils.writeVarint(outputScript); | ||
} | ||
}; | ||
// build P2PKH script from PubKeyHash | ||
static buildPublicKeyHashScript(pubKeyHash) { | ||
Utils.buildPublicKeyHashScript = function (pubKeyHash) { | ||
return (0, types_1.toByteString)(OpCode.OP_DUP) + (0, types_1.toByteString)(OpCode.OP_HASH160) + pack(Constants.PubKeyHashLen /* "OP_PUSHDATA0" */) | ||
+ pubKeyHash + (0, types_1.toByteString)(OpCode.OP_EQUALVERIFY) + (0, types_1.toByteString)(OpCode.OP_CHECKSIG); | ||
} | ||
}; | ||
// build false OPRETURN script from data payload | ||
static buildOpreturnScript(data) { | ||
Utils.buildOpreturnScript = function (data) { | ||
return (0, types_1.toByteString)(OpCode.OP_FALSE) + (0, types_1.toByteString)(OpCode.OP_RETURN) + Utils.writeVarint(data); | ||
} | ||
} | ||
}; | ||
// number of string to denote output value | ||
Utils.OutputValueLen = (0, scryptlib_1.Int)(8); | ||
// number of string to denote a public key hash | ||
Utils.PubKeyHashLen = (0, scryptlib_1.Int)(20); | ||
return Utils; | ||
}()); | ||
exports.Utils = Utils; | ||
// number of string to denote output value | ||
Utils.OutputValueLen = 8n; | ||
// number of string to denote a public key hash | ||
Utils.PubKeyHashLen = 20n; | ||
/** | ||
* @category Standard Contracts | ||
*/ | ||
class SigHash { | ||
var SigHash = /** @class */ (function () { | ||
function SigHash() { | ||
} | ||
/* | ||
@@ -478,93 +493,94 @@ * util functions to parse every field of a sighash preimage | ||
*/ | ||
static nVersion(preimage) { | ||
SigHash.nVersion = function (preimage) { | ||
return (0, types_1.toByteString)(preimage).slice(0, 8); | ||
} | ||
static hashPrevouts(preimage) { | ||
}; | ||
SigHash.hashPrevouts = function (preimage) { | ||
return (0, types_1.toByteString)(preimage).slice(8, 72); | ||
} | ||
static hashSequence(preimage) { | ||
}; | ||
SigHash.hashSequence = function (preimage) { | ||
return (0, types_1.toByteString)(preimage).slice(36 * 2, 68 * 2); | ||
} | ||
static outpoint(preimage) { | ||
}; | ||
SigHash.outpoint = function (preimage) { | ||
return (0, types_1.toByteString)(preimage).slice(68 * 2, 104 * 2); | ||
} | ||
}; | ||
// scriptCode is just scriptPubKey if there is no CODESEPARATOR in the latter | ||
static scriptCode(preimage) { | ||
SigHash.scriptCode = function (preimage) { | ||
return Utils.readVarint((0, types_1.toByteString)(preimage).slice(104 * 2)); | ||
} | ||
static valueRaw(preimage) { | ||
let l = len((0, types_1.toByteString)(preimage)); | ||
}; | ||
SigHash.valueRaw = function (preimage) { | ||
var l = len((0, types_1.toByteString)(preimage)); | ||
return (0, types_1.toByteString)(preimage).slice(l * 2 - 104, l * 2 - 88); | ||
} | ||
static value(preimage) { | ||
}; | ||
SigHash.value = function (preimage) { | ||
return Utils.fromLEUnsigned(SigHash.valueRaw(preimage)); | ||
} | ||
static nSequenceRaw(preimage) { | ||
let l = len((0, types_1.toByteString)(preimage)); | ||
}; | ||
SigHash.nSequenceRaw = function (preimage) { | ||
var l = len((0, types_1.toByteString)(preimage)); | ||
return (0, types_1.toByteString)(preimage).slice(l * 2 - 88, l * 2 - 80); | ||
} | ||
static nSequence(preimage) { | ||
}; | ||
SigHash.nSequence = function (preimage) { | ||
return Utils.fromLEUnsigned(SigHash.nSequenceRaw(preimage)); | ||
} | ||
}; | ||
; | ||
static hashOutputs(preimage) { | ||
let l = len((0, types_1.toByteString)(preimage)); | ||
SigHash.hashOutputs = function (preimage) { | ||
var l = len((0, types_1.toByteString)(preimage)); | ||
return (0, types_1.toByteString)(preimage).slice(l * 2 - 80, l * 2 - 16); | ||
} | ||
static nLocktimeRaw(preimage) { | ||
let l = len((0, types_1.toByteString)(preimage)); | ||
}; | ||
SigHash.nLocktimeRaw = function (preimage) { | ||
var l = len((0, types_1.toByteString)(preimage)); | ||
return (0, types_1.toByteString)(preimage).slice(l * 2 - 16, l * 2 - 8); | ||
} | ||
static nLocktime(preimage) { | ||
}; | ||
SigHash.nLocktime = function (preimage) { | ||
return Utils.fromLEUnsigned(SigHash.nLocktimeRaw(preimage)); | ||
} | ||
}; | ||
; | ||
static sigHashType(preimage) { | ||
let l = len((0, types_1.toByteString)(preimage)); | ||
let sigHashType = Utils.fromLEUnsigned((0, types_1.toByteString)(preimage).slice(l * 2 - 8, l * 2 - 6)); | ||
SigHash.sigHashType = function (preimage) { | ||
var l = len((0, types_1.toByteString)(preimage)); | ||
var sigHashType = Utils.fromLEUnsigned((0, types_1.toByteString)(preimage).slice(l * 2 - 8, l * 2 - 6)); | ||
return (0, scryptlib_1.SigHashType)(Number(sigHashType)); | ||
} | ||
} | ||
}; | ||
SigHash.ALL = (0, scryptlib_1.SigHashType)(65); | ||
SigHash.NONE = (0, scryptlib_1.SigHashType)(66); | ||
SigHash.SINGLE = (0, scryptlib_1.SigHashType)(67); | ||
SigHash.ANYONECANPAY_ALL = (0, scryptlib_1.SigHashType)(193); | ||
SigHash.ANYONECANPAY_NONE = (0, scryptlib_1.SigHashType)(194); | ||
SigHash.ANYONECANPAY_SINGLE = (0, scryptlib_1.SigHashType)(195); | ||
return SigHash; | ||
}()); | ||
exports.SigHash = SigHash; | ||
SigHash.ALL = (0, scryptlib_1.SigHashType)(65); | ||
SigHash.NONE = (0, scryptlib_1.SigHashType)(66); | ||
SigHash.SINGLE = (0, scryptlib_1.SigHashType)(67); | ||
SigHash.ANYONECANPAY_ALL = (0, scryptlib_1.SigHashType)(193); | ||
SigHash.ANYONECANPAY_NONE = (0, scryptlib_1.SigHashType)(194); | ||
SigHash.ANYONECANPAY_SINGLE = (0, scryptlib_1.SigHashType)(195); | ||
/** | ||
* @category Standard Contracts | ||
*/ | ||
class VarIntReader { | ||
constructor(buf) { | ||
var VarIntReader = /** @class */ (function () { | ||
function VarIntReader(buf) { | ||
this.buf = buf; | ||
this.pos = 0n; | ||
this.pos = (0, scryptlib_1.Int)(0); | ||
} | ||
eof() { | ||
VarIntReader.prototype.eof = function () { | ||
return this.pos >= len(this.buf); | ||
} | ||
readBytes() { | ||
let l = 0n; | ||
let buf = this.buf; | ||
let ret = (0, types_1.toByteString)(''); | ||
let header = unpack(buf.slice(Number(this.pos * 2n), Number((this.pos + 1n) * 2n))); | ||
}; | ||
VarIntReader.prototype.readBytes = function () { | ||
var l = (0, scryptlib_1.Int)(0); | ||
var buf = this.buf; | ||
var ret = (0, types_1.toByteString)(''); | ||
var header = unpack(buf.slice(Number(this.pos * (0, scryptlib_1.Int)(2)), Number((this.pos + (0, scryptlib_1.Int)(1)) * (0, scryptlib_1.Int)(2)))); | ||
this.pos++; | ||
if (header < 0x4cn) { | ||
if (header < (0, scryptlib_1.Int)(0x4c)) { | ||
l = header; | ||
ret = buf.slice(Number(this.pos * 2n), Number((this.pos + l) * 2n)); | ||
ret = buf.slice(Number(this.pos * (0, scryptlib_1.Int)(2)), Number((this.pos + l) * (0, scryptlib_1.Int)(2))); | ||
} | ||
else if (header == 0x4cn) { | ||
l = Utils.fromLEUnsigned(buf.slice(Number(this.pos * 2n), Number((this.pos + 1n) * 2n))); | ||
this.pos += 1n; | ||
ret = buf.slice(Number(this.pos * 2n), Number((this.pos + l) * 2n)); | ||
else if (header == (0, scryptlib_1.Int)(0x4c)) { | ||
l = Utils.fromLEUnsigned(buf.slice(Number(this.pos * (0, scryptlib_1.Int)(2)), Number((this.pos + (0, scryptlib_1.Int)(1)) * (0, scryptlib_1.Int)(2)))); | ||
this.pos += (0, scryptlib_1.Int)(1); | ||
ret = buf.slice(Number(this.pos * (0, scryptlib_1.Int)(2)), Number((this.pos + l) * (0, scryptlib_1.Int)(2))); | ||
} | ||
else if (header == 0x4dn) { | ||
l = Utils.fromLEUnsigned(buf.slice(Number(this.pos * 2n), Number((this.pos + 2n) * 2n))); | ||
this.pos += 2n; | ||
ret = buf.slice(Number(this.pos * 2n), Number((this.pos + l) * 2n)); | ||
else if (header == (0, scryptlib_1.Int)(0x4d)) { | ||
l = Utils.fromLEUnsigned(buf.slice(Number(this.pos * (0, scryptlib_1.Int)(2)), Number((this.pos + (0, scryptlib_1.Int)(2)) * (0, scryptlib_1.Int)(2)))); | ||
this.pos += (0, scryptlib_1.Int)(2); | ||
ret = buf.slice(Number(this.pos * (0, scryptlib_1.Int)(2)), Number((this.pos + l) * (0, scryptlib_1.Int)(2))); | ||
} | ||
else if (header == 0x4en) { | ||
l = Utils.fromLEUnsigned(buf.slice(Number(this.pos * 2n), Number((this.pos + 4n) * 2n))); | ||
this.pos += 4n; | ||
ret = buf.slice(Number(this.pos * 2n), Number((this.pos + l) * 2n)); | ||
else if (header == (0, scryptlib_1.Int)(0x4e)) { | ||
l = Utils.fromLEUnsigned(buf.slice(Number(this.pos * (0, scryptlib_1.Int)(2)), Number((this.pos + (0, scryptlib_1.Int)(2)) * (0, scryptlib_1.Int)(2)))); | ||
this.pos += (0, scryptlib_1.Int)(2); | ||
ret = buf.slice(Number(this.pos * (0, scryptlib_1.Int)(2)), Number((this.pos + l) * (0, scryptlib_1.Int)(2))); | ||
} | ||
@@ -577,49 +593,52 @@ else { | ||
return ret; | ||
} | ||
readBool() { | ||
let buf = this.buf.slice(Number(this.pos * 2n), Number((this.pos + 1n) * 2n)); | ||
}; | ||
VarIntReader.prototype.readBool = function () { | ||
var buf = this.buf.slice(Number(this.pos * (0, scryptlib_1.Int)(2)), Number((this.pos + (0, scryptlib_1.Int)(1)) * (0, scryptlib_1.Int)(2))); | ||
this.pos++; | ||
return (0, types_1.toByteString)('00') != buf; | ||
} | ||
readInt() { | ||
}; | ||
VarIntReader.prototype.readInt = function () { | ||
return unpack(this.readBytes()); | ||
} | ||
static getStateStart(scriptCode) { | ||
}; | ||
VarIntReader.getStateStart = function (scriptCode) { | ||
// locking script: code + opreturn + data(state + state_len + version) | ||
let scriptLen = BigInt(len(scriptCode)); | ||
var scriptLen = BigInt(len(scriptCode)); | ||
// read state length | ||
let start = scriptLen - VarIntReader.StateLen - VarIntReader.VersionLen; | ||
let end = scriptLen - VarIntReader.VersionLen; | ||
let lb = scriptCode.slice(Number(start * 2n), Number(end * 2n)); | ||
let stateLen = unpack(lb); | ||
var start = scriptLen - VarIntReader.StateLen - VarIntReader.VersionLen; | ||
var end = scriptLen - VarIntReader.VersionLen; | ||
var lb = scriptCode.slice(Number(start * (0, scryptlib_1.Int)(2)), Number(end * (0, scryptlib_1.Int)(2))); | ||
var stateLen = unpack(lb); | ||
// TODO: check version is as expected | ||
return scriptLen - stateLen - VarIntReader.StateLen - VarIntReader.VersionLen; | ||
} | ||
} | ||
}; | ||
// fixed number of string to denote length of serialized state | ||
VarIntReader.StateLen = (0, scryptlib_1.Int)(4); | ||
// fixed number of string to denote version | ||
VarIntReader.VersionLen = (0, scryptlib_1.Int)(1); | ||
// version | ||
VarIntReader.Version = (0, scryptlib_1.Int)(0); | ||
return VarIntReader; | ||
}()); | ||
exports.VarIntReader = VarIntReader; | ||
// fixed number of string to denote length of serialized state | ||
VarIntReader.StateLen = 4n; | ||
// fixed number of string to denote version | ||
VarIntReader.VersionLen = 1n; | ||
// version | ||
VarIntReader.Version = 0n; | ||
/** | ||
* @category Standard Contracts | ||
*/ | ||
class VarIntWriter { | ||
var VarIntWriter = /** @class */ (function () { | ||
function VarIntWriter() { | ||
} | ||
// return VarInt encoding | ||
static writeBytes(buf) { | ||
let n = BigInt(len(buf)); | ||
let header = (0, types_1.toByteString)(''); | ||
VarIntWriter.writeBytes = function (buf) { | ||
var n = BigInt(len(buf)); | ||
var header = (0, types_1.toByteString)(''); | ||
if (n < 0x4c) { | ||
header = Utils.toLEUnsigned(n, 1n); | ||
header = Utils.toLEUnsigned(n, (0, scryptlib_1.Int)(1)); | ||
} | ||
else if (n < 0x100) { | ||
header = (0, types_1.toByteString)('4c') + Utils.toLEUnsigned(n, 1n); | ||
header = (0, types_1.toByteString)('4c') + Utils.toLEUnsigned(n, (0, scryptlib_1.Int)(1)); | ||
} | ||
else if (n < 0x10000) { | ||
header = (0, types_1.toByteString)('4d') + Utils.toLEUnsigned(n, 2n); | ||
header = (0, types_1.toByteString)('4d') + Utils.toLEUnsigned(n, (0, scryptlib_1.Int)(2)); | ||
} | ||
else if (n < 0x100000000) { | ||
header = (0, types_1.toByteString)('4e') + Utils.toLEUnsigned(n, 4n); | ||
header = (0, types_1.toByteString)('4e') + Utils.toLEUnsigned(n, (0, scryptlib_1.Int)(4)); | ||
} | ||
@@ -631,17 +650,18 @@ else { | ||
return header + buf; | ||
} | ||
}; | ||
// uses fixed 1 byte to represent a boolean, plus length | ||
static writeBool(x) { | ||
VarIntWriter.writeBool = function (x) { | ||
return x ? (0, types_1.toByteString)('01') : (0, types_1.toByteString)('00'); | ||
} | ||
}; | ||
// bigint is little endian | ||
static writeInt(x) { | ||
return VarIntWriter.writeBytes(x == 0n ? (0, types_1.toByteString)('00') : pack(x)); | ||
} | ||
static serializeState(stateBuf) { | ||
VarIntWriter.writeInt = function (x) { | ||
return VarIntWriter.writeBytes(x == (0, scryptlib_1.Int)(0) ? (0, types_1.toByteString)('00') : pack(x)); | ||
}; | ||
VarIntWriter.serializeState = function (stateBuf) { | ||
// locking script: code + opreturn + data(state + state_len + version) | ||
let lenBuf = int2str(BigInt(len(stateBuf)), VarIntReader.StateLen); | ||
var lenBuf = int2str(BigInt(len(stateBuf)), VarIntReader.StateLen); | ||
return stateBuf + lenBuf + int2str(VarIntReader.Version, VarIntReader.VersionLen); | ||
} | ||
} | ||
}; | ||
return VarIntWriter; | ||
}()); | ||
exports.VarIntWriter = VarIntWriter; | ||
@@ -652,15 +672,17 @@ /** | ||
*/ | ||
class Tx { | ||
static normalize(k, modulus) { | ||
let res = k % modulus; | ||
var Tx = /** @class */ (function () { | ||
function Tx() { | ||
} | ||
Tx.normalize = function (k, modulus) { | ||
var res = k % modulus; | ||
// ensure it's positive | ||
return (res < 0) ? res + modulus : res; | ||
} | ||
static sign(h, privKey, inverseK, r, rBigEndian, sigHashType) { | ||
}; | ||
Tx.sign = function (h, privKey, inverseK, r, rBigEndian, sigHashType) { | ||
// TODO: r * privKey can also be precomputed | ||
let s = inverseK * (h + r * privKey); | ||
let N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n; | ||
var s = inverseK * (h + r * privKey); | ||
var N = (0, scryptlib_1.Int)(0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141); | ||
s = Tx.normalize(s, N); | ||
// lower S | ||
if (s > N / 2n) { | ||
if (s > N / (0, scryptlib_1.Int)(2)) { | ||
s = N - s; | ||
@@ -673,65 +695,69 @@ } | ||
*/ | ||
let rlen = BigInt(len(rBigEndian)); | ||
let slen = len(pack(s)); | ||
var rlen = BigInt(len(rBigEndian)); | ||
var slen = len(pack(s)); | ||
// we convert s to 32 bytes, otherwise reverseBytes(, 32) fails when s is strictly less than 31 bytes (note: 31 bytes works) | ||
// slice it after reversing to remove extra leading zeros, otherwise strict DER rule fails it due to not minimally encoded | ||
let sBigEndian = reverseBytes(int2str(s, 32n), 32).slice(32 * 2 - slen * 2); | ||
let l = 4n + rlen + BigInt(slen); | ||
var sBigEndian = reverseBytes(int2str(s, (0, scryptlib_1.Int)(32)), 32).slice(32 * 2 - slen * 2); | ||
var l = (0, scryptlib_1.Int)(4) + rlen + BigInt(slen); | ||
// rBigEndian must be mininally encoded, to conform to strict DER rule | ||
let rb = (0, types_1.toByteString)('30') + pack(l) + (0, types_1.toByteString)('02') + pack(rlen) + rBigEndian + (0, types_1.toByteString)('02') + pack(BigInt(slen)) + sBigEndian + (0, types_1.toByteString)(sigHashType); | ||
var rb = (0, types_1.toByteString)('30') + pack(l) + (0, types_1.toByteString)('02') + pack(rlen) + rBigEndian + (0, types_1.toByteString)('02') + pack(BigInt(slen)) + sBigEndian + (0, types_1.toByteString)(sigHashType); | ||
return (0, types_1.Sig)(rb); | ||
} | ||
static fromBEUnsigned(bytes) { | ||
}; | ||
Tx.fromBEUnsigned = function (bytes) { | ||
// change endian first | ||
// append positive sign byte. This does not hurt even when sign bit is already positive | ||
return unpack(reverseBytes(bytes, 32) + (0, types_1.toByteString)('00')); | ||
} | ||
}; | ||
// optimal pushtx | ||
static checkPreimageOpt(txPreimage) { throw new Error('unimplemented'); } | ||
Tx.checkPreimageOpt = function (txPreimage) { throw new Error('unimplemented'); }; | ||
// customize sigHashType | ||
static checkPreimageOpt_(txPreimage) { throw new Error('unimplemented'); } | ||
static checkPreimageAdvancedOCS(txPreimage, privKey, pubKey, inverseK, r, rBigEndian, sigHashType) { throw new Error('unimplemented'); } | ||
static checkPreimageOCS(txPreimage) { throw new Error('unimplemented'); } | ||
static checkPreimageSigHashTypeOCS(txPreimage, sigHashType) { throw new Error('unimplemented'); } | ||
Tx.checkPreimageOpt_ = function (txPreimage) { throw new Error('unimplemented'); }; | ||
Tx.checkPreimageAdvancedOCS = function (txPreimage, privKey, pubKey, inverseK, r, rBigEndian, sigHashType) { throw new Error('unimplemented'); }; | ||
Tx.checkPreimageOCS = function (txPreimage) { throw new Error('unimplemented'); }; | ||
Tx.checkPreimageSigHashTypeOCS = function (txPreimage, sigHashType) { throw new Error('unimplemented'); }; | ||
// optimal pushtx | ||
static checkPreimageOptOCS(txPreimage) { throw new Error('unimplemented'); } | ||
Tx.checkPreimageOptOCS = function (txPreimage) { throw new Error('unimplemented'); }; | ||
// customize sigHashType | ||
static checkPreimageOptOCS_(txPreimage) { throw new Error('unimplemented'); } | ||
Tx.checkPreimageOptOCS_ = function (txPreimage) { throw new Error('unimplemented'); }; | ||
// return whether is the first call of series public function calls in stateful contract | ||
static isFirstCall(txPreimage) { | ||
let scriptCode = SigHash.scriptCode(txPreimage); | ||
let stateStart = VarIntReader.getStateStart(scriptCode); | ||
let reader = new VarIntReader(scriptCode.slice(Number(stateStart) * 2)); | ||
Tx.isFirstCall = function (txPreimage) { | ||
var scriptCode = SigHash.scriptCode(txPreimage); | ||
var stateStart = VarIntReader.getStateStart(scriptCode); | ||
var reader = new VarIntReader(scriptCode.slice(Number(stateStart) * 2)); | ||
return reader.readBool(); | ||
} | ||
} | ||
}; | ||
// The following arguments can be generated using sample code at | ||
// https://gist.github.com/scrypt-sv/f6882be580780a88984cee75dd1564c4.js | ||
Tx.privKey = (0, types_1.PrivKey)((0, scryptlib_1.Int)(0x26f00fe2340a84335ebdf30f57e9bb58487117b29355718f5e46bf5168d7df97)); | ||
Tx.pubKey = (0, types_1.PubKey)((0, types_1.toByteString)('02ba79df5f8ae7604a9830f03c7933028186aede0675a16f025dc4f8be8eec0382')); | ||
// invK is the modular inverse of k, the ephemeral key | ||
Tx.invK = (0, scryptlib_1.Int)(0xc8ffdbaa05d93aa4ede79ec58f06a72562048b775a3507c2bf44bde4f007c40a); | ||
// r is x coordinate of R, which is kG | ||
Tx.r = (0, scryptlib_1.Int)(0x1008ce7480da41702918d1ec8e6849ba32b4d65b1e40dc669c31a1e6306b266c); | ||
// rBigEndian is the signed magnitude representation of r, in big endian | ||
Tx.rBigEndian = (0, types_1.toByteString)('1008ce7480da41702918d1ec8e6849ba32b4d65b1e40dc669c31a1e6306b266c'); | ||
return Tx; | ||
}()); | ||
exports.Tx = Tx; | ||
// The following arguments can be generated using sample code at | ||
// https://gist.github.com/scrypt-sv/f6882be580780a88984cee75dd1564c4.js | ||
Tx.privKey = (0, types_1.PrivKey)(0x26f00fe2340a84335ebdf30f57e9bb58487117b29355718f5e46bf5168d7df97n); | ||
Tx.pubKey = (0, types_1.PubKey)((0, types_1.toByteString)('02ba79df5f8ae7604a9830f03c7933028186aede0675a16f025dc4f8be8eec0382')); | ||
// invK is the modular inverse of k, the ephemeral key | ||
Tx.invK = 0xc8ffdbaa05d93aa4ede79ec58f06a72562048b775a3507c2bf44bde4f007c40an; | ||
// r is x coordinate of R, which is kG | ||
Tx.r = 0x1008ce7480da41702918d1ec8e6849ba32b4d65b1e40dc669c31a1e6306b266cn; | ||
// rBigEndian is the signed magnitude representation of r, in big endian | ||
Tx.rBigEndian = (0, types_1.toByteString)('1008ce7480da41702918d1ec8e6849ba32b4d65b1e40dc669c31a1e6306b266c'); | ||
/** | ||
* @category Standard Contracts | ||
*/ | ||
class Constants { | ||
} | ||
var Constants = /** @class */ (function () { | ||
function Constants() { | ||
} | ||
// number of string to denote input sequence | ||
Constants.InputSeqLen = (0, scryptlib_1.Int)(4); | ||
// number of string to denote output value | ||
Constants.OutputValueLen = (0, scryptlib_1.Int)(8); | ||
// number of string to denote a public key (compressed) | ||
Constants.PubKeyLen = (0, scryptlib_1.Int)(33); | ||
// number of string to denote a public key hash | ||
Constants.PubKeyHashLen = (0, scryptlib_1.Int)(20); | ||
// number of string to denote a tx id | ||
Constants.TxIdLen = (0, scryptlib_1.Int)(32); | ||
// number of string to denote a outpoint | ||
Constants.OutpointLen = (0, scryptlib_1.Int)(36); | ||
return Constants; | ||
}()); | ||
exports.Constants = Constants; | ||
// number of string to denote input sequence | ||
Constants.InputSeqLen = 4n; | ||
// number of string to denote output value | ||
Constants.OutputValueLen = 8n; | ||
// number of string to denote a public key (compressed) | ||
Constants.PubKeyLen = 33n; | ||
// number of string to denote a public key hash | ||
Constants.PubKeyHashLen = 20n; | ||
// number of string to denote a tx id | ||
Constants.TxIdLen = 32n; | ||
// number of string to denote a outpoint | ||
Constants.OutpointLen = 36n; | ||
//# sourceMappingURL=functions.js.map |
@@ -1,2 +0,2 @@ | ||
import { Bytes, SigHashPreimage, AbstractContract } from "scryptlib"; | ||
import { Bytes, SigHashPreimage, AbstractContract, Int } from "scryptlib"; | ||
import { SubBytes, SupportedParamType } from "scryptlib/dist/scryptTypes"; | ||
@@ -56,4 +56,4 @@ export { PubKey, Sig, SigHashPreimage, PrivKey, Ripemd160, PubKeyHash, Sha256, Sha1, OpCodeType, SigHashType } from "scryptlib"; | ||
export declare class HashedMap<K extends SupportedParamType, V extends SupportedParamType> { | ||
static readonly H_SIZE = 32n; | ||
static readonly ITEM_SIZE = 64n; | ||
static readonly H_SIZE: Int; | ||
static readonly ITEM_SIZE: Int; | ||
private innerMap; | ||
@@ -83,3 +83,3 @@ private _keyType?; | ||
innerSet: Set<E>; | ||
static readonly H_SIZE = 32n; | ||
static readonly H_SIZE: Int; | ||
private _elemType?; | ||
@@ -86,0 +86,0 @@ private _type?; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.HashedSet = exports.HashedMap = exports.equals = exports.utf8ToByteString = exports.toByteString = exports.SigHashType = exports.OpCodeType = exports.Sha1 = exports.Sha256 = exports.PubKeyHash = exports.Ripemd160 = exports.PrivKey = exports.SigHashPreimage = exports.Sig = exports.PubKey = void 0; | ||
const scryptlib_1 = require("scryptlib"); | ||
const functions_1 = require("./functions"); | ||
var scryptlib_1 = require("scryptlib"); | ||
var functions_1 = require("./functions"); | ||
var scryptlib_2 = require("scryptlib"); | ||
@@ -37,7 +37,7 @@ Object.defineProperty(exports, "PubKey", { enumerable: true, get: function () { return scryptlib_2.PubKey; } }); | ||
if (Array.isArray(a[0])) { | ||
let results = []; | ||
for (let i = 0; i < a.length; i++) { | ||
var results = []; | ||
for (var i = 0; i < a.length; i++) { | ||
results.push(equals(a[i], b[i])); | ||
} | ||
for (let i = 0; i < results.length; i++) { | ||
for (var i = 0; i < results.length; i++) { | ||
if (!results[i]) { | ||
@@ -52,3 +52,3 @@ return false; | ||
} | ||
for (let i = 0; i < a.length; i++) { | ||
for (var i = 0; i < a.length; i++) { | ||
if (!equals(a[i], b[i])) { | ||
@@ -61,12 +61,12 @@ return false; | ||
function equalsStruct(a, b) { | ||
let akeys = Object.keys(a); | ||
let bkeys = Object.keys(b); | ||
var akeys = Object.keys(a); | ||
var bkeys = Object.keys(b); | ||
if (akeys.length !== bkeys.length) { | ||
return false; | ||
} | ||
let results = []; | ||
for (let i = 0; i < akeys.length; i++) { | ||
var results = []; | ||
for (var i = 0; i < akeys.length; i++) { | ||
results.push(equals(a[akeys[i]], b[bkeys[i]])); | ||
} | ||
for (let i = 0; i < results.length; i++) { | ||
for (var i = 0; i < results.length; i++) { | ||
if (!results[i]) { | ||
@@ -89,8 +89,8 @@ return false; | ||
; | ||
class HashedMap { | ||
constructor(map) { | ||
var HashedMap = /** @class */ (function () { | ||
function HashedMap(map) { | ||
this.innerMap = map; | ||
} | ||
init(type, clazz) { | ||
const [name, genericTypes] = (0, scryptlib_1.parseGenericType)(type); | ||
HashedMap.prototype.init = function (type, clazz) { | ||
var _a = (0, scryptlib_1.parseGenericType)(type), name = _a[0], genericTypes = _a[1]; | ||
this._keyType = genericTypes[0]; | ||
@@ -100,25 +100,26 @@ this._valueType = genericTypes[1]; | ||
this._type = type; | ||
} | ||
}; | ||
// compare two bytes' order | ||
_checkInOrder(low, high) { | ||
HashedMap.prototype._checkInOrder = function (low, high) { | ||
// Note: low & high are both 256 bits, so they can not be converted to the same number unless they are the same. | ||
// Not working if their size are not equal due to non-minimal number format, ex. unpack('7180') == unpack('710080') | ||
return (0, functions_1.unpack)(low) < (0, functions_1.unpack)(high); | ||
} | ||
}; | ||
// insert / update (`key`, `val`) at `idx`, return false if `idx` is invalid or hash256ed' `key` is not in ascending order | ||
_set(key, val) { | ||
let r = false; | ||
let size = this.size(); | ||
let newKeyHash = this.DelegateClazz?.flattenSha256(key.item, this._keyType); | ||
let newElem = newKeyHash + this.DelegateClazz?.flattenSha256(val, this._valueType); | ||
if (key.idx >= 0n && key.idx <= size) { | ||
let isFirst = key.idx == 0n; | ||
let isLast = key.idx >= size - 1n; // idx == size if appending | ||
let before = isFirst ? toByteString("") : this.data().slice(0, Number(key.idx * HashedMap.ITEM_SIZE) * 2); | ||
let curElem = key.idx == size ? toByteString("") : this.data().slice(Number(key.idx * HashedMap.ITEM_SIZE) * 2, Number(key.idx * HashedMap.ITEM_SIZE + HashedMap.ITEM_SIZE) * 2); | ||
let curKeyHash = curElem == toByteString("") ? toByteString("") : curElem.slice(0, Number(HashedMap.H_SIZE) * 2); | ||
let after = isLast ? toByteString("") : this.data().slice(Number((key.idx + 1n) * HashedMap.ITEM_SIZE) * 2); | ||
HashedMap.prototype._set = function (key, val) { | ||
var _a, _b; | ||
var r = false; | ||
var size = this.size(); | ||
var newKeyHash = (_a = this.DelegateClazz) === null || _a === void 0 ? void 0 : _a.flattenSha256(key.item, this._keyType); | ||
var newElem = newKeyHash + ((_b = this.DelegateClazz) === null || _b === void 0 ? void 0 : _b.flattenSha256(val, this._valueType)); | ||
if (key.idx >= (0, scryptlib_1.Int)(0) && key.idx <= size) { | ||
var isFirst = key.idx == (0, scryptlib_1.Int)(0); | ||
var isLast = key.idx >= size - (0, scryptlib_1.Int)(1); // idx == size if appending | ||
var before_1 = isFirst ? toByteString("") : this.data().slice(0, Number(key.idx * HashedMap.ITEM_SIZE) * 2); | ||
var curElem = key.idx == size ? toByteString("") : this.data().slice(Number(key.idx * HashedMap.ITEM_SIZE) * 2, Number(key.idx * HashedMap.ITEM_SIZE + HashedMap.ITEM_SIZE) * 2); | ||
var curKeyHash = curElem == toByteString("") ? toByteString("") : curElem.slice(0, Number(HashedMap.H_SIZE) * 2); | ||
var after_1 = isLast ? toByteString("") : this.data().slice(Number((key.idx + (0, scryptlib_1.Int)(1)) * HashedMap.ITEM_SIZE) * 2); | ||
// check prevKeyHash < newKeyHash && newKeyHash < afterKeyHash | ||
if ((isFirst || this._checkInOrder(before.slice(Number((key.idx - 1n) * HashedMap.ITEM_SIZE) * 2, Number((key.idx - 1n) * HashedMap.ITEM_SIZE + HashedMap.H_SIZE) * 2), newKeyHash)) && | ||
(isLast || this._checkInOrder(newKeyHash, after.slice(0, Number(HashedMap.H_SIZE) * 2)))) { | ||
if ((isFirst || this._checkInOrder(before_1.slice(Number((key.idx - (0, scryptlib_1.Int)(1)) * HashedMap.ITEM_SIZE) * 2, Number((key.idx - (0, scryptlib_1.Int)(1)) * HashedMap.ITEM_SIZE + HashedMap.H_SIZE) * 2), newKeyHash)) && | ||
(isLast || this._checkInOrder(newKeyHash, after_1.slice(0, Number(HashedMap.H_SIZE) * 2)))) { | ||
if (curKeyHash == newKeyHash) { | ||
@@ -135,21 +136,23 @@ // update current element if key hashes matches | ||
return r; | ||
} | ||
}; | ||
// check whether if (`key`,`val`) exists at `idx` | ||
_canGet(key, val) { | ||
let r = false; | ||
if (key.idx >= 0n && key.idx < this.size()) { | ||
let startPos = key.idx * HashedMap.ITEM_SIZE; | ||
let k = this.data().slice(Number(startPos) * 2, Number(startPos + HashedMap.H_SIZE) * 2); | ||
let v = this.data().slice(Number(startPos + HashedMap.H_SIZE) * 2, Number(startPos + HashedMap.ITEM_SIZE) * 2); | ||
r = this.DelegateClazz?.flattenSha256(key.item, this._keyType) == k && this.DelegateClazz.flattenSha256(val, this._valueType) == v; | ||
HashedMap.prototype._canGet = function (key, val) { | ||
var _a; | ||
var r = false; | ||
if (key.idx >= (0, scryptlib_1.Int)(0) && key.idx < this.size()) { | ||
var startPos = key.idx * HashedMap.ITEM_SIZE; | ||
var k = this.data().slice(Number(startPos) * 2, Number(startPos + HashedMap.H_SIZE) * 2); | ||
var v = this.data().slice(Number(startPos + HashedMap.H_SIZE) * 2, Number(startPos + HashedMap.ITEM_SIZE) * 2); | ||
r = ((_a = this.DelegateClazz) === null || _a === void 0 ? void 0 : _a.flattenSha256(key.item, this._keyType)) == k && this.DelegateClazz.flattenSha256(val, this._valueType) == v; | ||
} | ||
return r; | ||
} | ||
}; | ||
// delete `key` which at `idx` from map | ||
_delete(key) { | ||
let r = false; | ||
HashedMap.prototype._delete = function (key) { | ||
var _a; | ||
var r = false; | ||
if (key.idx >= 0 && key.idx < this.size()) { | ||
let startPos = key.idx * HashedMap.ITEM_SIZE; | ||
let k = this.data().slice(Number(startPos) * 2, Number(startPos + HashedMap.H_SIZE) * 2); | ||
if (this.DelegateClazz?.flattenSha256(key.item, this._keyType) == k) { | ||
var startPos = key.idx * HashedMap.ITEM_SIZE; | ||
var k = this.data().slice(Number(startPos) * 2, Number(startPos + HashedMap.H_SIZE) * 2); | ||
if (((_a = this.DelegateClazz) === null || _a === void 0 ? void 0 : _a.flattenSha256(key.item, this._keyType)) == k) { | ||
r = true; | ||
@@ -159,27 +162,29 @@ } | ||
return r; | ||
} | ||
}; | ||
// check whether has `key` at `idx` | ||
_has(key) { | ||
let r = false; | ||
HashedMap.prototype._has = function (key) { | ||
var _a; | ||
var r = false; | ||
if (key.idx >= 0 && key.idx < this.size()) { | ||
let startPos = key.idx * HashedMap.ITEM_SIZE; | ||
let k = this.data().slice(Number(startPos) * 2, Number(startPos + HashedMap.H_SIZE) * 2); | ||
r = this.DelegateClazz?.flattenSha256(key.item, this._keyType) == k; | ||
var startPos = key.idx * HashedMap.ITEM_SIZE; | ||
var k = this.data().slice(Number(startPos) * 2, Number(startPos + HashedMap.H_SIZE) * 2); | ||
r = ((_a = this.DelegateClazz) === null || _a === void 0 ? void 0 : _a.flattenSha256(key.item, this._keyType)) == k; | ||
} | ||
return r; | ||
} | ||
}; | ||
// delete all | ||
clear() { | ||
HashedMap.prototype.clear = function () { | ||
this.innerMap = new Map(); | ||
return true; | ||
} | ||
}; | ||
// return map size | ||
size() { | ||
HashedMap.prototype.size = function () { | ||
return BigInt((0, functions_1.len)(this.data())) / HashedMap.ITEM_SIZE; | ||
} | ||
}; | ||
// return the underlaying data storage | ||
data() { | ||
return this.DelegateClazz?.toData(this.innerMap, this._type); | ||
} | ||
set(key, value) { | ||
HashedMap.prototype.data = function () { | ||
var _a; | ||
return (_a = this.DelegateClazz) === null || _a === void 0 ? void 0 : _a.toData(this.innerMap, this._type); | ||
}; | ||
HashedMap.prototype.set = function (key, value) { | ||
if (this.DelegateClazz && this._keyType && this._valueType) { | ||
@@ -194,4 +199,4 @@ if (this._set(key, value)) { | ||
return true; | ||
} | ||
has(key) { | ||
}; | ||
HashedMap.prototype.has = function (key) { | ||
if (this.DelegateClazz && this._keyType && this._valueType) { | ||
@@ -201,4 +206,4 @@ return this._has(key); | ||
return this.innerMap.has(key.item); | ||
} | ||
delete(key) { | ||
}; | ||
HashedMap.prototype.delete = function (key) { | ||
if (this.DelegateClazz && this._keyType && this._valueType) { | ||
@@ -213,4 +218,4 @@ if (this._delete(key)) { | ||
return this.innerMap.delete(key.item); | ||
} | ||
canGet(key, val) { | ||
}; | ||
HashedMap.prototype.canGet = function (key, val) { | ||
if (this.DelegateClazz && this._keyType && this._valueType) { | ||
@@ -220,43 +225,45 @@ return this._canGet(key, val); | ||
return (this.innerMap.get(key.item) === val); | ||
} | ||
toMap() { | ||
}; | ||
HashedMap.prototype.toMap = function () { | ||
return this.innerMap; | ||
} | ||
attach(map) { | ||
}; | ||
HashedMap.prototype.attach = function (map) { | ||
this.innerMap = new Map(map); | ||
} | ||
} | ||
}; | ||
HashedMap.H_SIZE = (0, scryptlib_1.Int)(32); // hash256'ed key/value size, 32 bytes | ||
HashedMap.ITEM_SIZE = (0, scryptlib_1.Int)(64); // 2 * H_SIZE | ||
return HashedMap; | ||
}()); | ||
exports.HashedMap = HashedMap; | ||
HashedMap.H_SIZE = 32n; // hash256'ed key/value size, 32 bytes | ||
HashedMap.ITEM_SIZE = 64n; // 2 * H_SIZE | ||
class HashedSet { | ||
constructor(set) { | ||
var HashedSet = /** @class */ (function () { | ||
function HashedSet(set) { | ||
this.innerSet = set; | ||
} | ||
init(type, clazz) { | ||
const [name, genericTypes] = (0, scryptlib_1.parseGenericType)(type); | ||
HashedSet.prototype.init = function (type, clazz) { | ||
var _a = (0, scryptlib_1.parseGenericType)(type), name = _a[0], genericTypes = _a[1]; | ||
this._type = type; | ||
this._elemType = genericTypes[0]; | ||
this.DelegateClazz = clazz; | ||
} | ||
}; | ||
// compare two bytes' order | ||
_checkInOrder(low, high) { | ||
HashedSet.prototype._checkInOrder = function (low, high) { | ||
// Note: low & high are both 256 bits, so they can not be converted to the same number unless they are the same. | ||
// Not working if their size are not equal due to non-minimal number format, ex. unpack('7180') == unpack('710080') | ||
return (0, functions_1.unpack)(low) < (0, functions_1.unpack)(high); | ||
} | ||
}; | ||
// add / update element `elem` at `idx`, return false if `idx` is invalid or hash256ed' `elem` is not in ascending order | ||
_add(elem) { | ||
let r = false; | ||
let size = this.size(); | ||
let newHash = this.DelegateClazz?.flattenSha256(elem.item, this._elemType); | ||
HashedSet.prototype._add = function (elem) { | ||
var _a; | ||
var r = false; | ||
var size = this.size(); | ||
var newHash = (_a = this.DelegateClazz) === null || _a === void 0 ? void 0 : _a.flattenSha256(elem.item, this._elemType); | ||
if (elem.idx >= 0 && elem.idx <= size) { | ||
let isFirst = elem.idx == 0n; | ||
let isLast = elem.idx >= size - 1n; // idx == size if appending | ||
let before = isFirst ? toByteString("") : this.data().slice(0, Number(elem.idx * HashedSet.H_SIZE) * 2); | ||
let curHash = elem.idx == size ? toByteString("") : this.data().slice(Number(elem.idx * HashedSet.H_SIZE) * 2, Number(elem.idx * HashedSet.H_SIZE + HashedSet.H_SIZE) * 2); | ||
let after = isLast ? toByteString("") : this.data().slice(Number((elem.idx + 1n) * HashedSet.H_SIZE) * 2); | ||
var isFirst = elem.idx == (0, scryptlib_1.Int)(0); | ||
var isLast = elem.idx >= size - (0, scryptlib_1.Int)(1); // idx == size if appending | ||
var before_2 = isFirst ? toByteString("") : this.data().slice(0, Number(elem.idx * HashedSet.H_SIZE) * 2); | ||
var curHash = elem.idx == size ? toByteString("") : this.data().slice(Number(elem.idx * HashedSet.H_SIZE) * 2, Number(elem.idx * HashedSet.H_SIZE + HashedSet.H_SIZE) * 2); | ||
var after_2 = isLast ? toByteString("") : this.data().slice(Number((elem.idx + (0, scryptlib_1.Int)(1)) * HashedSet.H_SIZE) * 2); | ||
// check prevHash < newHash && newHash < afterHash | ||
if ((isFirst || this._checkInOrder(before.slice(Number((elem.idx - 1n) * HashedSet.H_SIZE) * 2, Number((elem.idx - 1n) * HashedSet.H_SIZE + HashedSet.H_SIZE) * 2), newHash)) && | ||
(isLast || this._checkInOrder(newHash, after.slice(0, Number(HashedSet.H_SIZE) * 2)))) { | ||
if ((isFirst || this._checkInOrder(before_2.slice(Number((elem.idx - (0, scryptlib_1.Int)(1)) * HashedSet.H_SIZE) * 2, Number((elem.idx - (0, scryptlib_1.Int)(1)) * HashedSet.H_SIZE + HashedSet.H_SIZE) * 2), newHash)) && | ||
(isLast || this._checkInOrder(newHash, after_2.slice(0, Number(HashedSet.H_SIZE) * 2)))) { | ||
if (curHash == newHash) { | ||
@@ -273,10 +280,11 @@ // duplicated adding | ||
return r; | ||
} | ||
}; | ||
// delete `elem` which at `idx` from set | ||
_delete(elem) { | ||
let r = false; | ||
HashedSet.prototype._delete = function (elem) { | ||
var _a; | ||
var r = false; | ||
if (elem.idx >= 0 && elem.idx < this.size()) { | ||
let startPos = elem.idx * HashedSet.H_SIZE; | ||
let v = this.data().slice(Number(startPos) * 2, Number(startPos + HashedSet.H_SIZE) * 2); | ||
if (this.DelegateClazz?.flattenSha256(elem.item, this._elemType) == v) { | ||
var startPos = elem.idx * HashedSet.H_SIZE; | ||
var v = this.data().slice(Number(startPos) * 2, Number(startPos + HashedSet.H_SIZE) * 2); | ||
if (((_a = this.DelegateClazz) === null || _a === void 0 ? void 0 : _a.flattenSha256(elem.item, this._elemType)) == v) { | ||
r = true; | ||
@@ -286,14 +294,15 @@ } | ||
return r; | ||
} | ||
}; | ||
// check whether has `elem` at `idx` | ||
_has(elem) { | ||
let r = false; | ||
HashedSet.prototype._has = function (elem) { | ||
var _a; | ||
var r = false; | ||
if (elem.idx >= 0 && elem.idx < this.size()) { | ||
let startPos = elem.idx * HashedSet.H_SIZE; | ||
let v = this.data().slice(Number(startPos) * 2, Number(startPos + HashedSet.H_SIZE) * 2); | ||
r = this.DelegateClazz?.flattenSha256(elem.item, this._elemType) == v; | ||
var startPos = elem.idx * HashedSet.H_SIZE; | ||
var v = this.data().slice(Number(startPos) * 2, Number(startPos + HashedSet.H_SIZE) * 2); | ||
r = ((_a = this.DelegateClazz) === null || _a === void 0 ? void 0 : _a.flattenSha256(elem.item, this._elemType)) == v; | ||
} | ||
return r; | ||
} | ||
add(key) { | ||
}; | ||
HashedSet.prototype.add = function (key) { | ||
if (this.DelegateClazz && this._elemType) { | ||
@@ -308,4 +317,4 @@ if (this._add(key)) { | ||
return true; | ||
} | ||
has(key) { | ||
}; | ||
HashedSet.prototype.has = function (key) { | ||
if (this.DelegateClazz && this._elemType) { | ||
@@ -315,4 +324,4 @@ return this._has(key); | ||
return this.innerSet.has(key.item); | ||
} | ||
delete(key) { | ||
}; | ||
HashedSet.prototype.delete = function (key) { | ||
if (this.DelegateClazz && this._elemType) { | ||
@@ -327,25 +336,27 @@ if (this._delete(key)) { | ||
return this.innerSet.delete(key.item); | ||
} | ||
}; | ||
// delete all | ||
clear() { | ||
HashedSet.prototype.clear = function () { | ||
this.innerSet = new Set(); | ||
return true; | ||
} | ||
}; | ||
// return set size | ||
size() { | ||
HashedSet.prototype.size = function () { | ||
return BigInt((0, functions_1.len)(this.data())) / HashedSet.H_SIZE; | ||
} | ||
}; | ||
// return the underlaying data storage | ||
data() { | ||
return this.DelegateClazz?.toData(this.innerSet, this._type); | ||
} | ||
toSet() { | ||
HashedSet.prototype.data = function () { | ||
var _a; | ||
return (_a = this.DelegateClazz) === null || _a === void 0 ? void 0 : _a.toData(this.innerSet, this._type); | ||
}; | ||
HashedSet.prototype.toSet = function () { | ||
return this.innerSet; | ||
} | ||
attach(set) { | ||
}; | ||
HashedSet.prototype.attach = function (set) { | ||
this.innerSet = new Set(set); | ||
} | ||
} | ||
}; | ||
HashedSet.H_SIZE = (0, scryptlib_1.Int)(32); // hash256'ed elem size, 32 bytes | ||
return HashedSet; | ||
}()); | ||
exports.HashedSet = HashedSet; | ||
HashedSet.H_SIZE = 32n; // hash256'ed elem size, 32 bytes | ||
//# sourceMappingURL=types.js.map |
@@ -90,2 +90,3 @@ import "reflect-metadata"; | ||
private delegateInstance; | ||
private static compileImpl; | ||
static compile(): Promise<TranspileError[] | undefined>; | ||
@@ -95,2 +96,5 @@ static loadArtifact(artifact: ContractArtifact): void; | ||
private static _getScryptFile; | ||
private static _getArtifactFile; | ||
private static _loadArtifact; | ||
getContractArtifact(): ContractArtifact | undefined; | ||
private static _getCtxMethods; | ||
@@ -97,0 +101,0 @@ getCtxMethods(): string[]; |
@@ -25,2 +25,47 @@ "use strict"; | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { | ||
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { | ||
if (ar || !(i in from)) { | ||
if (!ar) ar = Array.prototype.slice.call(from, 0, i); | ||
ar[i] = from[i]; | ||
} | ||
} | ||
return to.concat(ar || Array.prototype.slice.call(from)); | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
@@ -32,13 +77,13 @@ return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
require("reflect-metadata"); | ||
const fs = __importStar(require("fs")); | ||
const os_1 = require("os"); | ||
const path_1 = require("path"); | ||
const indexer_1 = require("./indexer"); | ||
const scryptlib_1 = require("scryptlib"); | ||
const types_1 = require("./builtins/types"); | ||
const functions_1 = require("./builtins/functions"); | ||
const lodash_clonedeep_1 = __importDefault(require("lodash.clonedeep")); | ||
const library_1 = require("./library"); | ||
const typeCheck_1 = require("scryptlib/dist/typeCheck"); | ||
const diffUtils_1 = require("./diffUtils"); | ||
var fs = __importStar(require("fs")); | ||
var os_1 = require("os"); | ||
var path_1 = require("path"); | ||
var indexer_1 = require("./indexer"); | ||
var scryptlib_1 = require("scryptlib"); | ||
var types_1 = require("./builtins/types"); | ||
var functions_1 = require("./builtins/functions"); | ||
var lodash_clonedeep_1 = __importDefault(require("lodash.clonedeep")); | ||
var library_1 = require("./library"); | ||
var typeCheck_1 = require("scryptlib/dist/typeCheck"); | ||
var diffUtils_1 = require("./diffUtils"); | ||
/** | ||
@@ -54,10 +99,14 @@ * The main contract class. To write a contract, extend this class as such: | ||
*/ | ||
class SmartContract { | ||
constructor(...args) { | ||
var SmartContract = /** @class */ (function () { | ||
function SmartContract() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
this.enableUpdateEMC = false; // a flag indicateing whether can update `this.entryMethodCall` | ||
const DelegateClazz = this.getDelegateClazz(); | ||
var DelegateClazz = this.getDelegateClazz(); | ||
if (!DelegateClazz) { | ||
throw new Error(`'${this.constructor.name}.compile' or '${this.constructor.name}.loadArtifact' should be called before initializing any instance!`); | ||
throw new Error("'".concat(this.constructor.name, ".compile' or '").concat(this.constructor.name, ".loadArtifact' should be called before initializing any instance!")); | ||
} | ||
const args_ = args.map((arg, index) => { | ||
var args_ = args.map(function (arg, index) { | ||
if (arg instanceof library_1.SmartContractLib) { | ||
@@ -67,4 +116,4 @@ return arg.getArgs(); | ||
else if (arg instanceof types_1.HashedMap) { | ||
const ctorAbi = DelegateClazz.abi.find(abi => abi.type === scryptlib_1.ABIEntityType.CONSTRUCTOR); | ||
const type = ctorAbi.params[index].type; | ||
var ctorAbi = DelegateClazz.abi.find(function (abi) { return abi.type === scryptlib_1.ABIEntityType.CONSTRUCTOR; }); | ||
var type = ctorAbi.params[index].type; | ||
arg.init(type, DelegateClazz); | ||
@@ -74,4 +123,4 @@ return arg.toMap(); | ||
else if (arg instanceof types_1.HashedSet) { | ||
const ctorAbi = DelegateClazz.abi.find(abi => abi.type === scryptlib_1.ABIEntityType.CONSTRUCTOR); | ||
const type = ctorAbi.params[index].type; | ||
var ctorAbi = DelegateClazz.abi.find(function (abi) { return abi.type === scryptlib_1.ABIEntityType.CONSTRUCTOR; }); | ||
var type = ctorAbi.params[index].type; | ||
arg.init(type, DelegateClazz); | ||
@@ -82,92 +131,144 @@ return arg.toSet(); | ||
}); | ||
this.delegateInstance = new DelegateClazz(...args_); | ||
this.delegateInstance = new (DelegateClazz.bind.apply(DelegateClazz, __spreadArray([void 0], args_, false)))(); | ||
this.delegateInstance.isGenesis = false; | ||
} | ||
static async compile() { | ||
const transform = this._getTransform(); | ||
if (!transform.success) { | ||
return transform.errors; | ||
} | ||
const tmpDir = fs.mkdtempSync((0, path_1.join)((0, os_1.tmpdir)(), "scrypt-ts-")); | ||
let filePath = this._getScryptFile(); | ||
const result = await (0, scryptlib_1.compileContractAsync)(filePath, { | ||
sourceMap: true, | ||
artifact: true, | ||
out: tmpDir | ||
SmartContract.compileImpl = function (filePath) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var tmpDir, result, artifactFileName_1, artifactFile; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
tmpDir = fs.mkdtempSync((0, path_1.join)((0, os_1.tmpdir)(), "scrypt-ts-")); | ||
return [4 /*yield*/, (0, scryptlib_1.compileContractAsync)(filePath, { | ||
sourceMap: true, | ||
artifact: true, | ||
out: tmpDir | ||
})]; | ||
case 1: | ||
result = _a.sent(); | ||
if (result.errors.length > 0) { | ||
throw new Error("Compiled failed for class `".concat(this.name, "`, check the output details at project building time!")); | ||
} | ||
else { | ||
artifactFileName_1 = (0, path_1.basename)(filePath).replace('.scrypt', '.json'); | ||
artifactFile = fs.readdirSync(tmpDir).filter(function (fn) { return fn == artifactFileName_1; })[0]; | ||
if (artifactFile) { | ||
fs.copyFileSync((0, path_1.join)(tmpDir, artifactFile), (0, path_1.join)((0, path_1.dirname)(filePath), artifactFile)); | ||
} | ||
} | ||
return [2 /*return*/, result]; | ||
} | ||
}); | ||
}); | ||
if (result.errors.length > 0) { | ||
throw new Error(`Compiled failed for class \`${this.name}\`, check the output details at project building time!`); | ||
} | ||
else { | ||
const artifactFileName = (0, path_1.basename)(filePath).replace('.scrypt', '.json'); | ||
const artifactFile = fs.readdirSync(tmpDir).filter(fn => fn == artifactFileName)[0]; | ||
if (artifactFile) { | ||
fs.copyFileSync((0, path_1.join)(tmpDir, artifactFile), (0, path_1.join)((0, path_1.dirname)(filePath), artifactFile)); | ||
} | ||
} | ||
this.DelegateClazz = (0, scryptlib_1.buildContractClass)(result); | ||
} | ||
static loadArtifact(artifact) { | ||
let filePath = this._getScryptFile(); | ||
const sourceContent = fs.readFileSync(filePath, 'utf8'); | ||
const md5Hash = (0, scryptlib_1.md5)(sourceContent); | ||
}; | ||
SmartContract.compile = function () { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var transform, artifact, filePath, result; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
transform = this._getTransform(); | ||
if (!transform.success) { | ||
return [2 /*return*/, transform.errors]; | ||
} | ||
artifact = this._loadArtifact(); | ||
if (!artifact) return [3 /*break*/, 1]; | ||
this.DelegateClazz = (0, scryptlib_1.buildContractClass)(artifact); | ||
return [3 /*break*/, 3]; | ||
case 1: | ||
filePath = this._getScryptFile(); | ||
return [4 /*yield*/, this.compileImpl(filePath)]; | ||
case 2: | ||
result = _a.sent(); | ||
this.DelegateClazz = (0, scryptlib_1.buildContractClass)(result); | ||
_a.label = 3; | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
}; | ||
SmartContract.loadArtifact = function (artifact) { | ||
var filePath = this._getScryptFile(); | ||
var sourceContent = fs.readFileSync(filePath, 'utf8'); | ||
var md5Hash = (0, scryptlib_1.md5)(sourceContent); | ||
if (this.name !== artifact.contract || artifact.md5 !== md5Hash) { | ||
throw new Error(`Contract artifact file cannot match contract \`${this.name}\`!`); | ||
throw new Error("Contract artifact file cannot match contract `".concat(this.name, "`!")); | ||
} | ||
this.DelegateClazz = (0, scryptlib_1.buildContractClass)(artifact); | ||
} | ||
static _getTransform() { | ||
let transformFile = Reflect.getMetadata("scrypt:transform", this); | ||
}; | ||
SmartContract._getTransform = function () { | ||
var transformFile = Reflect.getMetadata("scrypt:transform", this); | ||
if (!transformFile) { | ||
throw new Error('the ts-scrypt transformer plugin may not be activated for the project, check your `tsconfig` file!'); | ||
} | ||
let srcFile = Reflect.getMetadata("__filename", this); | ||
let indexFile = indexer_1.Indexer.queryIndexFile(srcFile, process.cwd()); | ||
var srcFile = Reflect.getMetadata("__filename", this); | ||
var indexFile = indexer_1.Indexer.queryIndexFile(srcFile, process.cwd()); | ||
if (!indexFile) { | ||
throw new Error(`can not find \`scrypt.index.json\` file for contract \`${this.name}\`, search path from ${srcFile} to ${process.cwd()}`); | ||
throw new Error("can not find `scrypt.index.json` file for contract `".concat(this.name, "`, search path from ").concat(srcFile, " to ").concat(process.cwd())); | ||
} | ||
let indexer = new indexer_1.Indexer(indexFile); | ||
let filePath = indexer.getFullPath(transformFile); | ||
var indexer = new indexer_1.Indexer(indexFile); | ||
var filePath = indexer.getFullPath(transformFile); | ||
return JSON.parse(fs.readFileSync(filePath).toString()); | ||
} | ||
static _getScryptFile() { | ||
let transform = this._getTransform(); | ||
let scryptFile = transform.scryptfile; | ||
}; | ||
SmartContract._getScryptFile = function () { | ||
var transform = this._getTransform(); | ||
var scryptFile = transform.scryptfile; | ||
if (!scryptFile) { | ||
throw new Error('the ts-scrypt transformer plugin may not be activated for the project, check your `tsconfig` file!'); | ||
} | ||
let srcFile = Reflect.getMetadata("__filename", this); | ||
let indexFile = indexer_1.Indexer.queryIndexFile(srcFile, process.cwd()); | ||
var srcFile = Reflect.getMetadata("__filename", this); | ||
var indexFile = indexer_1.Indexer.queryIndexFile(srcFile, process.cwd()); | ||
if (!indexFile) { | ||
throw new Error(`can not find \`scrypt.index.json\` file for contract \`${this.name}\`, search path from ${srcFile} to ${process.cwd()}`); | ||
throw new Error("can not find `scrypt.index.json` file for contract `".concat(this.name, "`, search path from ").concat(srcFile, " to ").concat(process.cwd())); | ||
} | ||
let indexer = new indexer_1.Indexer(indexFile); | ||
let filePath = indexer.getFullPath(scryptFile); | ||
var indexer = new indexer_1.Indexer(indexFile); | ||
var filePath = indexer.getFullPath(scryptFile); | ||
if (!fs.existsSync(filePath)) { | ||
throw new Error(`can not find the bundled scrypt file for \`${typeof this}\` at ${filePath}`); | ||
throw new Error("can not find the bundled scrypt file for `".concat(typeof this, "` at ").concat(filePath)); | ||
} | ||
return filePath; | ||
} | ||
static _getCtxMethods() { | ||
let transform = this._getTransform(); | ||
}; | ||
SmartContract._getArtifactFile = function () { | ||
var scryptFile = this._getScryptFile(); | ||
return (0, path_1.join)((0, path_1.dirname)(scryptFile), "".concat((0, path_1.basename)(scryptFile, ".scrypt"), ".json")); | ||
}; | ||
SmartContract._loadArtifact = function () { | ||
var artifactFile = this._getArtifactFile(); | ||
if (!fs.existsSync(artifactFile)) { | ||
return undefined; | ||
} | ||
var artifact = JSON.parse(fs.readFileSync(artifactFile, 'utf8').toString()); | ||
var scryptFile = this._getScryptFile(); | ||
var sourceContent = fs.readFileSync(scryptFile, 'utf8'); | ||
if (artifact.contract !== this.name || artifact.md5 === (0, scryptlib_1.md5)(sourceContent)) { | ||
return artifact; | ||
} | ||
; | ||
}; | ||
SmartContract.prototype.getContractArtifact = function () { | ||
return Object.getPrototypeOf(this).constructor._loadArtifact(); | ||
}; | ||
SmartContract._getCtxMethods = function () { | ||
var transform = this._getTransform(); | ||
return transform.ctxMethods; | ||
} | ||
getCtxMethods() { | ||
}; | ||
SmartContract.prototype.getCtxMethods = function () { | ||
return Object.getPrototypeOf(this).constructor._getCtxMethods(); | ||
} | ||
getDelegateClazz() { | ||
return Object.getOwnPropertyDescriptor(this.constructor, 'DelegateClazz')?.value; | ||
} | ||
verify(entryMethodInvoking) { | ||
let srcFile = Reflect.getMetadata("__filename", Object.getPrototypeOf(this).constructor); | ||
let scryptFile = Object.getPrototypeOf(this).constructor._getScryptFile(); | ||
const sourceMapFile = scryptFile.replace(/\.scrypt$/, '.scrypt.map'); | ||
}; | ||
SmartContract.prototype.getDelegateClazz = function () { | ||
var _a; | ||
return (_a = Object.getOwnPropertyDescriptor(this.constructor, 'DelegateClazz')) === null || _a === void 0 ? void 0 : _a.value; | ||
}; | ||
SmartContract.prototype.verify = function (entryMethodInvoking) { | ||
var srcFile = Reflect.getMetadata("__filename", Object.getPrototypeOf(this).constructor); | ||
var scryptFile = Object.getPrototypeOf(this).constructor._getScryptFile(); | ||
var sourceMapFile = scryptFile.replace(/\.scrypt$/, '.scrypt.map'); | ||
if (!fs.existsSync(sourceMapFile)) { | ||
throw new Error(`can not find the bundled sourcemap file for \`${typeof this}\` at ${sourceMapFile}`); | ||
throw new Error("can not find the bundled sourcemap file for `".concat(typeof this, "` at ").concat(sourceMapFile)); | ||
} | ||
let sourceMap = JSON.parse(fs.readFileSync(sourceMapFile).toString()); | ||
let txContext = {}; | ||
var sourceMap = JSON.parse(fs.readFileSync(sourceMapFile).toString()); | ||
var txContext = {}; | ||
if (this.unlockFrom) { | ||
txContext.tx = this.unlockFrom.tx; | ||
let inputIndex = this.unlockFrom.inputIndex; | ||
var inputIndex = this.unlockFrom.inputIndex; | ||
txContext.inputIndex = inputIndex; | ||
@@ -177,9 +278,9 @@ txContext.inputSatoshis = this.unlockFrom.tx.inputs[inputIndex].output.satoshis; | ||
try { | ||
const result = this.buildEntryMethodCall(entryMethodInvoking).verify(txContext); | ||
var result = this.buildEntryMethodCall(entryMethodInvoking).verify(txContext); | ||
if (!result.success && result.error) { | ||
const matches = /\[(.+?)\]\((.+?)#(\d+)\)/.exec(result.error); | ||
var matches = /\[(.+?)\]\((.+?)#(\d+)\)/.exec(result.error); | ||
result.error.substring(0, matches.index); | ||
const line = parseInt(matches[3]); | ||
const tsLine = sourceMap[line - 1][0][2] + 1; | ||
result.error = `[Go to Source](file://${srcFile}:${tsLine})`; | ||
var line = parseInt(matches[3]); | ||
var tsLine = sourceMap[line - 1][0][2] + 1; | ||
result.error = "[Go to Source](file://".concat(srcFile, ":").concat(tsLine, ")"); | ||
} | ||
@@ -191,4 +292,4 @@ return result; | ||
} | ||
} | ||
getUnlockingScript(callPub) { | ||
}; | ||
SmartContract.prototype.getUnlockingScript = function (callPub) { | ||
try { | ||
@@ -200,61 +301,71 @@ return this.clone().buildEntryMethodCall(callPub).unlockingScript; | ||
} | ||
} | ||
genLaunchConfig(a, tx, inputIndex) { | ||
}; | ||
SmartContract.prototype.genLaunchConfig = function (a, tx, inputIndex) { | ||
return this.delegateInstance.genLaunchConfig(a, tx, inputIndex); | ||
} | ||
}; | ||
// sync properties values to delegateInstance iff it's not the genesis. | ||
syncStateProps() { | ||
SmartContract.prototype.syncStateProps = function () { | ||
var _this = this; | ||
if (!this.delegateInstance.isGenesis) { | ||
const statePropKeys = Reflect.getMetadata("scrypt:stateProps", this) || []; | ||
statePropKeys.forEach(statePropKey => { | ||
if (this[statePropKey] instanceof library_1.SmartContractLib) { | ||
this.delegateInstance[statePropKey] = this[statePropKey].getState(); | ||
var statePropKeys = Reflect.getMetadata("scrypt:stateProps", this) || []; | ||
statePropKeys.forEach(function (statePropKey) { | ||
if (_this[statePropKey] instanceof library_1.SmartContractLib) { | ||
_this.delegateInstance[statePropKey] = _this[statePropKey].getState(); | ||
} | ||
else if (this[statePropKey] instanceof types_1.HashedMap) { | ||
this.delegateInstance[statePropKey] = this[statePropKey].toMap(); | ||
else if (_this[statePropKey] instanceof types_1.HashedMap) { | ||
_this.delegateInstance[statePropKey] = _this[statePropKey].toMap(); | ||
} | ||
else if (this[statePropKey] instanceof types_1.HashedSet) { | ||
this.delegateInstance[statePropKey] = this[statePropKey].toSet(); | ||
else if (_this[statePropKey] instanceof types_1.HashedSet) { | ||
_this.delegateInstance[statePropKey] = _this[statePropKey].toSet(); | ||
} | ||
else { | ||
this.delegateInstance[statePropKey] = this[statePropKey]; | ||
_this.delegateInstance[statePropKey] = _this[statePropKey]; | ||
} | ||
}); | ||
} | ||
} | ||
get lockingScript() { | ||
this.syncStateProps(); | ||
return this.delegateInstance.lockingScript; | ||
} | ||
get codePart() { | ||
return this.delegateInstance.codePart.toHex(); | ||
} | ||
clone() { | ||
let obj = (0, lodash_clonedeep_1.default)(this); | ||
}; | ||
Object.defineProperty(SmartContract.prototype, "lockingScript", { | ||
get: function () { | ||
this.syncStateProps(); | ||
return this.delegateInstance.lockingScript; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
Object.defineProperty(SmartContract.prototype, "codePart", { | ||
get: function () { | ||
return this.delegateInstance.codePart.toHex(); | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
SmartContract.prototype.clone = function () { | ||
var obj = (0, lodash_clonedeep_1.default)(this); | ||
return obj; | ||
} | ||
next() { | ||
const obj = (0, lodash_clonedeep_1.default)(this); | ||
}; | ||
SmartContract.prototype.next = function () { | ||
var obj = (0, lodash_clonedeep_1.default)(this); | ||
obj.delegateInstance.isGenesis = false; | ||
obj.syncStateProps(); | ||
return obj; | ||
} | ||
markAsGenesis() { | ||
}; | ||
SmartContract.prototype.markAsGenesis = function () { | ||
this.delegateInstance.isGenesis = true; | ||
return this; | ||
} | ||
updateStateSigHashType(txPreimage, amount, sigHashType) { | ||
}; | ||
SmartContract.prototype.updateStateSigHashType = function (txPreimage, amount, sigHashType) { | ||
(0, functions_1.assert)(this.checkPreimageSigHashType(txPreimage, sigHashType)); | ||
let output = this.buildStateOutput(amount); | ||
var output = this.buildStateOutput(amount); | ||
return (0, functions_1.hash256)(output) == functions_1.SigHash.hashOutputs(txPreimage); | ||
} | ||
buildStateOutput(amount) { | ||
let outputScript = this.getStateScript(); | ||
}; | ||
SmartContract.prototype.buildStateOutput = function (amount) { | ||
var outputScript = this.getStateScript(); | ||
return functions_1.Utils.buildOutput(outputScript, amount); | ||
} | ||
getStateScript() { | ||
let sBuf = functions_1.VarIntWriter.writeBool(false); | ||
}; | ||
SmartContract.prototype.getStateScript = function () { | ||
var _this = this; | ||
var sBuf = functions_1.VarIntWriter.writeBool(false); | ||
this.delegateInstance.stateProps | ||
.forEach(p => { | ||
let value = this[p.name]; | ||
.forEach(function (p) { | ||
var value = _this[p.name]; | ||
if (value instanceof types_1.HashedMap || value instanceof types_1.HashedSet) { | ||
@@ -267,6 +378,6 @@ value = { | ||
value: value | ||
}), this.delegateInstance.resolver, { | ||
}), _this.delegateInstance.resolver, { | ||
state: true, | ||
ignoreValue: false | ||
}).forEach(p => { | ||
}).forEach(function (p) { | ||
if (['bytes', 'PubKey', 'Ripemd160', 'Sig', 'Sha1', 'SigHashPreimage', 'Sha256', 'SigHashType', 'OpCodeType'].includes(p.type)) { | ||
@@ -284,3 +395,3 @@ sBuf += functions_1.VarIntWriter.writeBytes(p.value); | ||
return this.codePart + functions_1.VarIntWriter.serializeState(sBuf); | ||
} | ||
}; | ||
/** | ||
@@ -291,7 +402,7 @@ * verifies an ECDSA signature. It takes two inputs from the stack, a public key (on top of the stack) and an ECDSA signature in its DER_CANONISED format concatenated with sighash flags. It outputs true or false on the stack based on whether the signature check passes or fails. | ||
*/ | ||
checkSig(signature, publickey) { | ||
SmartContract.prototype.checkSig = function (signature, publickey) { | ||
if (!this.checkSignatureEncoding(signature) || !this.checkPubkeyEncoding(publickey)) { | ||
return false; | ||
} | ||
let fSuccess = false; | ||
var fSuccess = false; | ||
if (!this.unlockFrom) { | ||
@@ -301,7 +412,7 @@ throw new Error('unlockFrom should be set when checkSig executes'); | ||
try { | ||
const sig = scryptlib_1.bsv.crypto.Signature.fromTxFormat(Buffer.from((0, types_1.toByteString)(signature), 'hex')); | ||
const pubkey = scryptlib_1.bsv.PublicKey.fromBuffer(Buffer.from((0, types_1.toByteString)(publickey), 'hex'), false); | ||
const tx = this.unlockFrom.tx; | ||
const inputIndex = this.unlockFrom.inputIndex || 0; | ||
const inputSatoshis = this.unlockFrom.tx.inputs[inputIndex].output.satoshis; | ||
var sig = scryptlib_1.bsv.crypto.Signature.fromTxFormat(Buffer.from((0, types_1.toByteString)(signature), 'hex')); | ||
var pubkey = scryptlib_1.bsv.PublicKey.fromBuffer(Buffer.from((0, types_1.toByteString)(publickey), 'hex'), false); | ||
var tx = this.unlockFrom.tx; | ||
var inputIndex = this.unlockFrom.inputIndex || 0; | ||
var inputSatoshis = this.unlockFrom.tx.inputs[inputIndex].output.satoshis; | ||
fSuccess = tx.verifySignature(sig, pubkey, inputIndex, this.delegateInstance.lockingScript, scryptlib_1.bsv.crypto.BN.fromNumber(inputSatoshis), scryptlib_1.DEFAULT_FLAGS); | ||
@@ -314,17 +425,17 @@ } | ||
return fSuccess; | ||
} | ||
}; | ||
// rBigEndian must be mininally encoded, to conform to strict DER rule https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#der-encoding | ||
checkPreimageAdvanced(txPreimage, privKey, pubKey, inverseK, r, rBigEndian, sigHashType) { | ||
SmartContract.prototype.checkPreimageAdvanced = function (txPreimage, privKey, pubKey, inverseK, r, rBigEndian, sigHashType) { | ||
// hash is big endian | ||
let h = (0, functions_1.hash256)((0, types_1.toByteString)(txPreimage)); | ||
let sig = functions_1.Tx.sign(functions_1.Tx.fromBEUnsigned(h), privKey, inverseK, r, rBigEndian, sigHashType); | ||
var h = (0, functions_1.hash256)((0, types_1.toByteString)(txPreimage)); | ||
var sig = functions_1.Tx.sign(functions_1.Tx.fromBEUnsigned(h), privKey, inverseK, r, rBigEndian, sigHashType); | ||
return this.checkSig(sig, pubKey); | ||
} | ||
}; | ||
// wrapper for OP_PUSH_TX with customized sighash type | ||
checkPreimageSigHashType(txPreimage, sigHashType) { | ||
SmartContract.prototype.checkPreimageSigHashType = function (txPreimage, sigHashType) { | ||
return this.checkPreimageAdvanced(txPreimage, functions_1.Tx.privKey, functions_1.Tx.pubKey, functions_1.Tx.invK, functions_1.Tx.r, functions_1.Tx.rBigEndian, sigHashType); | ||
} | ||
checkPreimage(txPreimage) { | ||
}; | ||
SmartContract.prototype.checkPreimage = function (txPreimage) { | ||
return this.checkPreimageAdvanced(txPreimage, functions_1.Tx.privKey, functions_1.Tx.pubKey, functions_1.Tx.invK, functions_1.Tx.r, functions_1.Tx.rBigEndian, functions_1.SigHash.ALL); | ||
} | ||
}; | ||
/** | ||
@@ -335,10 +446,10 @@ * Compares the first signature against each public key until it finds an ECDSA match. Starting with the subsequent public key, it compares the second signature against each remaining public key until it finds an ECDSA match. The process is repeated until all signatures have been checked or not enough public keys remain to produce a successful result. All signatures need to match a public key. Because public keys are not checked again if they fail any signature comparison, signatures must be placed in the scriptSig using the same order as their corresponding public keys were placed in the scriptPubKey or redeemScript. If all signatures are valid, 1 is returned, 0 otherwise. Due to a bug, one extra unused value is removed from the stack. | ||
*/ | ||
checkMultiSig(signatures, publickeys) { | ||
SmartContract.prototype.checkMultiSig = function (signatures, publickeys) { | ||
//TODO: unimplemented | ||
return true; | ||
} | ||
updateState(preimage, amount) { | ||
}; | ||
SmartContract.prototype.updateState = function (preimage, amount) { | ||
return this.updateStateSigHashType(preimage, amount, functions_1.SigHash.ALL); | ||
} | ||
checkPubkeyEncoding(publickey) { | ||
}; | ||
SmartContract.prototype.checkPubkeyEncoding = function (publickey) { | ||
if ((scryptlib_1.DEFAULT_FLAGS & scryptlib_1.bsv.Script.Interpreter.SCRIPT_VERIFY_STRICTENC) !== 0 && !scryptlib_1.bsv.PublicKey.isValid((0, types_1.toByteString)(publickey))) { | ||
@@ -348,4 +459,4 @@ return false; | ||
return true; | ||
} | ||
checkSignatureEncoding(signature) { | ||
}; | ||
SmartContract.prototype.checkSignatureEncoding = function (signature) { | ||
var buf = Buffer.from((0, types_1.toByteString)(signature), 'hex'); | ||
@@ -382,5 +493,10 @@ var sig; | ||
return true; | ||
} | ||
callDelegatedMethod(methodName, ...args) { | ||
const abi = this.getDelegateClazz().abi.find(func => func.name === methodName); | ||
}; | ||
SmartContract.prototype.callDelegatedMethod = function (methodName) { | ||
var _a; | ||
var args = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
args[_i - 1] = arguments[_i]; | ||
} | ||
var abi = this.getDelegateClazz().abi.find(function (func) { return func.name === methodName; }); | ||
if (abi) { | ||
@@ -394,6 +510,6 @@ // only entry (public) method calls will be delegated to the target instance. | ||
} | ||
const txPreimage = (0, types_1.SigHashPreimage)(this.unlockFrom.tx.getPreimage(this._unlockFrom.inputIndex)); | ||
var txPreimage = (0, types_1.SigHashPreimage)(this.unlockFrom.tx.getPreimage(this._unlockFrom.inputIndex)); | ||
args.push(txPreimage); | ||
} | ||
return this.getDelegateClazz().prototype[methodName].call(this.delegateInstance, ...args); | ||
return (_a = this.getDelegateClazz().prototype[methodName]).call.apply(_a, __spreadArray([this.delegateInstance], args, false)); | ||
} | ||
@@ -403,13 +519,17 @@ else { | ||
} | ||
} | ||
setDataPartInASM(dataPart) { | ||
}; | ||
SmartContract.prototype.setDataPartInASM = function (dataPart) { | ||
this.delegateInstance.setDataPartInASM(dataPart); | ||
} | ||
setDataPartInHex(dataPart) { | ||
}; | ||
SmartContract.prototype.setDataPartInHex = function (dataPart) { | ||
this.delegateInstance.setDataPartInHex(dataPart); | ||
} | ||
get dataPart() { | ||
return this.delegateInstance.dataPart; | ||
} | ||
buildEntryMethodCall(callPub) { | ||
}; | ||
Object.defineProperty(SmartContract.prototype, "dataPart", { | ||
get: function () { | ||
return this.delegateInstance.dataPart; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
SmartContract.prototype.buildEntryMethodCall = function (callPub) { | ||
this.entryMethodCall = undefined; | ||
@@ -422,39 +542,47 @@ this.enableUpdateEMC = true; | ||
} | ||
const entryCall = this.entryMethodCall; | ||
var entryCall = this.entryMethodCall; | ||
this.entryMethodCall = undefined; | ||
this.enableUpdateEMC = false; | ||
return entryCall; | ||
} | ||
set unlockFrom(ref) { | ||
this._unlockFrom = ref; | ||
const txPreimage = (0, types_1.SigHashPreimage)(ref.tx.getPreimage(ref.inputIndex)); | ||
const outpoint = functions_1.SigHash.outpoint(txPreimage); | ||
this.ctx = { | ||
version: functions_1.SigHash.nVersion(txPreimage), | ||
utxo: { | ||
value: functions_1.SigHash.value(txPreimage), | ||
script: functions_1.SigHash.scriptCode(txPreimage), | ||
outpoint: { | ||
txid: outpoint.slice(0, 32 * 2), | ||
outputIndex: functions_1.Utils.fromLEUnsigned(outpoint.slice(32 * 2)) | ||
} | ||
}, | ||
hashPrevouts: functions_1.SigHash.hashPrevouts(txPreimage), | ||
hashSequence: functions_1.SigHash.hashSequence(txPreimage), | ||
sequence: functions_1.SigHash.nSequence(txPreimage), | ||
hashOutputs: functions_1.SigHash.hashOutputs(txPreimage), | ||
locktime: functions_1.SigHash.nLocktime(txPreimage), | ||
sigHashType: functions_1.SigHash.sigHashType(txPreimage), | ||
}; | ||
} | ||
get unlockFrom() { | ||
return this._unlockFrom; | ||
} | ||
get lockTo() { | ||
return this._lockTo; | ||
} | ||
set lockTo(ref) { | ||
this._lockTo = ref; | ||
} | ||
static findKeyIndex(collection, key, keyType) { | ||
}; | ||
Object.defineProperty(SmartContract.prototype, "unlockFrom", { | ||
get: function () { | ||
return this._unlockFrom; | ||
}, | ||
set: function (ref) { | ||
this._unlockFrom = ref; | ||
var txPreimage = (0, types_1.SigHashPreimage)(ref.tx.getPreimage(ref.inputIndex)); | ||
var outpoint = functions_1.SigHash.outpoint(txPreimage); | ||
this.ctx = { | ||
version: functions_1.SigHash.nVersion(txPreimage), | ||
utxo: { | ||
value: functions_1.SigHash.value(txPreimage), | ||
script: functions_1.SigHash.scriptCode(txPreimage), | ||
outpoint: { | ||
txid: outpoint.slice(0, 32 * 2), | ||
outputIndex: functions_1.Utils.fromLEUnsigned(outpoint.slice(32 * 2)) | ||
} | ||
}, | ||
hashPrevouts: functions_1.SigHash.hashPrevouts(txPreimage), | ||
hashSequence: functions_1.SigHash.hashSequence(txPreimage), | ||
sequence: functions_1.SigHash.nSequence(txPreimage), | ||
hashOutputs: functions_1.SigHash.hashOutputs(txPreimage), | ||
locktime: functions_1.SigHash.nLocktime(txPreimage), | ||
sigHashType: functions_1.SigHash.sigHashType(txPreimage), | ||
}; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
Object.defineProperty(SmartContract.prototype, "lockTo", { | ||
get: function () { | ||
return this._lockTo; | ||
}, | ||
set: function (ref) { | ||
this._lockTo = ref; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
SmartContract.findKeyIndex = function (collection, key, keyType) { | ||
if (!keyType) { | ||
@@ -476,4 +604,4 @@ switch (typeof key) { | ||
return this.DelegateClazz.findKeyIndex(collection, key, keyType); | ||
} | ||
diffOutputs(outputs) { | ||
}; | ||
SmartContract.prototype.diffOutputs = function (outputs) { | ||
if (!this.unlockFrom) { | ||
@@ -483,3 +611,3 @@ throw new Error('unlockFrom should be set'); | ||
try { | ||
const info = (0, diffUtils_1.diffOutputs)(this.delegateInstance, outputs, this.unlockFrom.tx); | ||
var info = (0, diffUtils_1.diffOutputs)(this.delegateInstance, outputs, this.unlockFrom.tx); | ||
console.info(info); | ||
@@ -491,13 +619,18 @@ } | ||
} | ||
} | ||
get debug() { | ||
const self = this; | ||
return { | ||
diffOutputs: (outputs) => { | ||
self.diffOutputs(outputs); | ||
} | ||
}; | ||
} | ||
} | ||
}; | ||
Object.defineProperty(SmartContract.prototype, "debug", { | ||
get: function () { | ||
var self = this; | ||
return { | ||
diffOutputs: function (outputs) { | ||
self.diffOutputs(outputs); | ||
} | ||
}; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
return SmartContract; | ||
}()); | ||
exports.SmartContract = SmartContract; | ||
//# sourceMappingURL=contract.js.map |
"use strict"; | ||
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { | ||
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { | ||
if (ar || !(i in from)) { | ||
if (!ar) ar = Array.prototype.slice.call(from, 0, i); | ||
ar[i] = from[i]; | ||
} | ||
} | ||
return to.concat(ar || Array.prototype.slice.call(from)); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.prop = exports.method = void 0; | ||
const dist_1 = require("scryptlib/dist"); | ||
const functions_1 = require("./builtins/functions"); | ||
var dist_1 = require("scryptlib/dist"); | ||
var functions_1 = require("./builtins/functions"); | ||
/** | ||
@@ -10,46 +19,52 @@ * Indicates whether the method is a contract method, and ordinary methods do not affect the execution of the contract | ||
*/ | ||
function method(sigHashType = functions_1.SigHash.ALL) { | ||
function method(sigHashType) { | ||
if (sigHashType === void 0) { sigHashType = functions_1.SigHash.ALL; } | ||
return function (target, methodName, descriptor) { | ||
const originalMethod = descriptor.value; | ||
const newDescriptor = { | ||
var originalMethod = descriptor.value; | ||
var newDescriptor = { | ||
configurable: true, | ||
enumerable: false, | ||
get() { | ||
const wrappedMethod = (...args) => { | ||
get: function () { | ||
var _this = this; | ||
var wrappedMethod = function () { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
// static method on subclasses of `SmartContract` | ||
const isSmartContractLibStatic = typeof target === "function" | ||
&& Object.getPrototypeOf(this).name === "SmartContractLib"; | ||
var isSmartContractLibStatic = typeof target === "function" | ||
&& Object.getPrototypeOf(_this).name === "SmartContractLib"; | ||
// instance method on subclasses of `SmartContractLib` | ||
const isSmartContractLibMethod = typeof target === "object" | ||
&& Object.getPrototypeOf(this.constructor).name === "SmartContractLib"; | ||
var isSmartContractLibMethod = typeof target === "object" | ||
&& Object.getPrototypeOf(_this.constructor).name === "SmartContractLib"; | ||
if (isSmartContractLibStatic || isSmartContractLibMethod) { | ||
return originalMethod.apply(this, args); | ||
return originalMethod.apply(_this, args); | ||
} | ||
// static method on subclasses of `SmartContract` | ||
const isSmartContractStatic = typeof target === "function" | ||
&& Object.getPrototypeOf(this).name === "SmartContract"; | ||
var isSmartContractStatic = typeof target === "function" | ||
&& Object.getPrototypeOf(_this).name === "SmartContract"; | ||
// instance method on subclasses of `SmartContract` | ||
const isSmartContractMethod = typeof target === "object" | ||
&& Object.getPrototypeOf(this.constructor).name === "SmartContract"; | ||
var isSmartContractMethod = typeof target === "object" | ||
&& Object.getPrototypeOf(_this.constructor).name === "SmartContract"; | ||
if (isSmartContractStatic || isSmartContractMethod) { | ||
// update `this.entryMethodCall` iff the update flag is true & its value is undefined. | ||
if (this.enableUpdateEMC && !this.entryMethodCall) { | ||
this.entryMethodCall = this.callDelegatedMethod(methodName, ...args); | ||
const ctxMethods = this.getCtxMethods(); | ||
if (_this.enableUpdateEMC && !_this.entryMethodCall) { | ||
_this.entryMethodCall = _this.callDelegatedMethod.apply(_this, __spreadArray([methodName], args, false)); | ||
var ctxMethods = _this.getCtxMethods(); | ||
// check preimage before run the method | ||
if (ctxMethods.includes(methodName)) { | ||
if (!this.unlockFrom) { | ||
if (!_this.unlockFrom) { | ||
throw new Error('unlockFrom should be set'); | ||
} | ||
const ref = this.unlockFrom; | ||
const txPreimage = (0, dist_1.SigHashPreimage)(ref.tx.getPreimage(ref.inputIndex)); | ||
(0, functions_1.assert)(this.checkPreimageSigHashType(txPreimage, sigHashType)); | ||
var ref = _this.unlockFrom; | ||
var txPreimage = (0, dist_1.SigHashPreimage)(ref.tx.getPreimage(ref.inputIndex)); | ||
(0, functions_1.assert)(_this.checkPreimageSigHashType(txPreimage, sigHashType)); | ||
} | ||
if (this.entryMethodCall) { | ||
args = this.entryMethodCall.args.map(a => a.value); | ||
if (_this.entryMethodCall) { | ||
args = _this.entryMethodCall.args.map(function (a) { return a.value; }); | ||
} | ||
} | ||
return originalMethod.apply(this, args); | ||
return originalMethod.apply(_this, args); | ||
} | ||
throw new Error(`@method decorator used on \`${this.name || this.constructor.name}#${methodName}\`, it should only be used in subclasses of \`SmartContract\``); | ||
throw new Error("@method decorator used on `".concat(_this.name || _this.constructor.name, "#").concat(methodName, "`, it should only be used in subclasses of `SmartContract`")); | ||
}; | ||
@@ -68,7 +83,8 @@ return wrappedMethod; | ||
*/ | ||
function prop(state = false) { | ||
function prop(state) { | ||
if (state === void 0) { state = false; } | ||
return function (target, propertyName) { | ||
if (state) { | ||
const statePropsMetaKey = "scrypt:stateProps"; | ||
let stateProps = (Reflect.getMetadata(statePropsMetaKey, target) || []).concat(propertyName); | ||
var statePropsMetaKey = "scrypt:stateProps"; | ||
var stateProps = (Reflect.getMetadata(statePropsMetaKey, target) || []).concat(propertyName); | ||
Reflect.defineMetadata(statePropsMetaKey, stateProps, target); | ||
@@ -75,0 +91,0 @@ } |
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
o[k2] = m[k]; | ||
})); | ||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { | ||
Object.defineProperty(o, "default", { enumerable: true, value: v }); | ||
}) : function(o, v) { | ||
o["default"] = v; | ||
}); | ||
var __importStar = (this && this.__importStar) || function (mod) { | ||
if (mod && mod.__esModule) return mod; | ||
var result = {}; | ||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); | ||
__setModuleDefault(result, mod); | ||
return result; | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.diffOutputs = void 0; | ||
const chalk = require("chalk"); | ||
const Diff = require("fast-diff"); | ||
const scryptlib_1 = require("scryptlib"); | ||
const scryptlib_2 = require("scryptlib"); | ||
const customChalk = new chalk.Instance({ level: 1 }); | ||
var chalk = __importStar(require("chalk")); | ||
var fast_diff_1 = __importDefault(require("fast-diff")); | ||
var scryptlib_1 = require("scryptlib"); | ||
var scryptlib_2 = require("scryptlib"); | ||
var customChalk = new chalk.Instance({ level: 1 }); | ||
//If the lengths differ by more than 50%, the two are considered as significantly different | ||
function isTooDifferent(str1, str2) { | ||
let maxLen = Math.max(str1.length, str2.length); | ||
let diffLen = Math.abs(str1.length - str2.length); | ||
let startswith = str2.startsWith(str1) || str1.startsWith(str2); | ||
var maxLen = Math.max(str1.length, str2.length); | ||
var diffLen = Math.abs(str1.length - str2.length); | ||
var startswith = str2.startsWith(str1) || str1.startsWith(str2); | ||
return diffLen / maxLen > 0.5 && maxLen > 3000 && !startswith; | ||
@@ -18,10 +55,10 @@ } | ||
function toASMAndCut(hex1, hex2) { | ||
let tooDifferent = isTooDifferent(hex1, hex2); | ||
let asm1 = scryptlib_1.bsv.Script.fromHex(hex1).toASM(); | ||
let asm2 = scryptlib_1.bsv.Script.fromHex(hex2).toASM(); | ||
var tooDifferent = isTooDifferent(hex1, hex2); | ||
var asm1 = scryptlib_1.bsv.Script.fromHex(hex1).toASM(); | ||
var asm2 = scryptlib_1.bsv.Script.fromHex(hex2).toASM(); | ||
if (tooDifferent) { | ||
let arr1 = asm1.split(' '); | ||
let arr2 = asm2.split(' '); | ||
let minLen = Math.min(arr1.length, arr2.length); | ||
let maxLen = Math.min(minLen, 1000); | ||
var arr1 = asm1.split(' '); | ||
var arr2 = asm2.split(' '); | ||
var minLen = Math.min(arr1.length, arr2.length); | ||
var maxLen = Math.min(minLen, 1000); | ||
asm1 = arr1.slice(0, maxLen).join(' '); | ||
@@ -39,3 +76,3 @@ if (arr1.length > maxLen) { | ||
function stringify(state) { | ||
return JSON.stringify(state, (key, value) => { | ||
return JSON.stringify(state, function (key, value) { | ||
if (typeof value === 'bigint') { | ||
@@ -47,31 +84,32 @@ return value.toString(); | ||
function getTxContextOutputs(tx) { | ||
return tx.outputs.map(output => ({ | ||
return tx.outputs.map(function (output) { return ({ | ||
script: output.script.toHex(), | ||
satoshis: output.satoshis | ||
})); | ||
}); }); | ||
} | ||
function getContractOutputs(realOutputsHex) { | ||
const reader = new scryptlib_1.bsv.encoding.BufferReader(Buffer.from(realOutputsHex, 'hex')); | ||
const outputs = []; | ||
var reader = new scryptlib_1.bsv.encoding.BufferReader(Buffer.from(realOutputsHex, 'hex')); | ||
var outputs = []; | ||
while (!reader.eof()) { | ||
const output = scryptlib_1.bsv.Transaction.Output.fromBufferReader(reader); | ||
var output = scryptlib_1.bsv.Transaction.Output.fromBufferReader(reader); | ||
outputs.push(output); | ||
} | ||
return outputs.map(output => ({ | ||
return outputs.map(function (output) { return ({ | ||
script: output.script.toHex(), | ||
satoshis: output.satoshis | ||
})); | ||
}); }); | ||
} | ||
function formatOutputs(contract, contractOutputs, ctxOutputs) { | ||
if (scryptlib_2.AbstractContract.isStateful(contract)) { | ||
const codePart = contract.codePart.toHex(); | ||
const indexs1 = ctxOutputs.map((o, index) => o.script.startsWith(codePart) ? index : -1).filter(i => i > -1); | ||
const indexs2 = contractOutputs.map((o, index) => o.script.startsWith(codePart) ? index : -1).filter(i => i > -1); | ||
const commonIndexs = indexs1.map((indexc, index) => indexc === indexs2[index] ? indexc : -1).filter(i => i > -1); | ||
let formater = (output, index) => { | ||
if (commonIndexs.includes(index)) { | ||
const CLS = contract.ContractClass; | ||
const statesProps = CLS.fromHex(output.script).statePropsArgs; | ||
let states = statesProps.reduce((a, v) => { | ||
return { ...a, [v.name]: v.value }; | ||
var codePart_1 = contract.codePart.toHex(); | ||
var indexs1 = ctxOutputs.map(function (o, index) { return o.script.startsWith(codePart_1) ? index : -1; }).filter(function (i) { return i > -1; }); | ||
var indexs2_1 = contractOutputs.map(function (o, index) { return o.script.startsWith(codePart_1) ? index : -1; }).filter(function (i) { return i > -1; }); | ||
var commonIndexs_1 = indexs1.map(function (indexc, index) { return indexc === indexs2_1[index] ? indexc : -1; }).filter(function (i) { return i > -1; }); | ||
var formater = function (output, index) { | ||
if (commonIndexs_1.includes(index)) { | ||
var CLS = contract.ContractClass; | ||
var statesProps = CLS.fromHex(output.script).statePropsArgs; | ||
var states = statesProps.reduce(function (a, v) { | ||
var _a; | ||
return __assign(__assign({}, a), (_a = {}, _a[v.name] = v.value, _a)); | ||
}, {}); | ||
@@ -96,6 +134,6 @@ return { | ||
function diffState(contractOutputs, txContextOutputs) { | ||
let state = ''; | ||
let index = 0; | ||
var state = ''; | ||
var index = 0; | ||
state += customChalk.grey("["); | ||
contractOutputs.forEach(output => { | ||
contractOutputs.forEach(function (output) { | ||
if (typeof output.states !== 'undefined') { | ||
@@ -109,7 +147,7 @@ if (index > 0) { | ||
else { | ||
Diff(stringify(txContextOutputs[index].states), stringify(output.states)).forEach((part) => { | ||
if (part[0] === Diff.INSERT) { | ||
(0, fast_diff_1.default)(stringify(txContextOutputs[index].states), stringify(output.states)).forEach(function (part) { | ||
if (part[0] === fast_diff_1.default.INSERT) { | ||
state += customChalk.red(part[1]); | ||
} | ||
else if (part[0] === Diff.DELETE) { | ||
else if (part[0] === fast_diff_1.default.DELETE) { | ||
state += customChalk.green(part[1]); | ||
@@ -126,3 +164,3 @@ } | ||
for (; index < txContextOutputs.length; index++) { | ||
const output = txContextOutputs[index]; | ||
var output = txContextOutputs[index]; | ||
if (typeof output.states !== 'undefined') { | ||
@@ -136,12 +174,10 @@ state += customChalk.green(stringify(output.states)); | ||
function diffOutputs(contract, realOutputsHex, tx) { | ||
const contractOutputs = getContractOutputs(realOutputsHex); | ||
const txContextOutputs = getTxContextOutputs(tx); | ||
let result = `1. Outputs from ${customChalk.green('Transaction')} is marked green | ||
2. Outputs from (${customChalk.red('Contract')}) is marked red | ||
3. Identical parts are marked in gray\n\n`; | ||
let [contractOutputs_, txContextOutputs_] = formatOutputs(contract, contractOutputs, txContextOutputs); | ||
let outputs = ''; | ||
let index = 0; | ||
var contractOutputs = getContractOutputs(realOutputsHex); | ||
var txContextOutputs = getTxContextOutputs(tx); | ||
var result = "1. Outputs from ".concat(customChalk.green('Transaction'), " is marked green\n2. Outputs from (").concat(customChalk.red('Contract'), ") is marked red\n3. Identical parts are marked in gray\n\n"); | ||
var _a = formatOutputs(contract, contractOutputs, txContextOutputs), contractOutputs_ = _a[0], txContextOutputs_ = _a[1]; | ||
var outputs = ''; | ||
var index = 0; | ||
outputs += customChalk.grey("["); | ||
contractOutputs_.forEach(output => { | ||
contractOutputs_.forEach(function (output) { | ||
if (index > 0) { | ||
@@ -175,8 +211,8 @@ outputs += customChalk.grey(", "); | ||
else { | ||
const [asm1, asm2] = toASMAndCut(txContextOutputs_[index].script, output.script); | ||
Diff(asm1, asm2).forEach((part) => { | ||
if (part[0] === Diff.INSERT) { | ||
var _a = toASMAndCut(txContextOutputs_[index].script, output.script), asm1 = _a[0], asm2 = _a[1]; | ||
(0, fast_diff_1.default)(asm1, asm2).forEach(function (part) { | ||
if (part[0] === fast_diff_1.default.INSERT) { | ||
outputs += customChalk.red(foldStr(part[1])); | ||
} | ||
else if (part[0] === Diff.DELETE) { | ||
else if (part[0] === fast_diff_1.default.DELETE) { | ||
outputs += customChalk.green(foldStr(part[1])); | ||
@@ -194,3 +230,3 @@ } | ||
for (; index < txContextOutputs_.length; index++) { | ||
const output = txContextOutputs_[index]; | ||
var output = txContextOutputs_[index]; | ||
outputs += customChalk.gray(","); | ||
@@ -206,5 +242,5 @@ outputs += customChalk.green("{\n"); | ||
outputs += customChalk.grey("]"); | ||
result = result + `Outputs: ${outputs}`; | ||
result = result + "Outputs: ".concat(outputs); | ||
if (scryptlib_2.AbstractContract.isStateful(contract)) { | ||
result = result + `\n\nState: ${diffState(contractOutputs_, txContextOutputs_)}`; | ||
result = result + "\n\nState: ".concat(diffState(contractOutputs_, txContextOutputs_)); | ||
} | ||
@@ -215,3 +251,3 @@ return result; | ||
function foldStr(str) { | ||
let arr = str.split(' '); | ||
var arr = str.split(' '); | ||
if (arr.length > 10) { | ||
@@ -218,0 +254,0 @@ return arr.slice(0, 5).concat(['...']).concat(arr.slice(arr.length - 5)).join(' '); |
@@ -18,8 +18,8 @@ "use strict"; | ||
exports.FunctionCall = exports.buildOpreturnScript = exports.buildPublicKeyHashScript = exports.toHex = exports.bsv = exports.SmartContractLib = exports.SmartContract = exports.method = exports.prop = void 0; | ||
const decorators_1 = require("./decorators"); | ||
var decorators_1 = require("./decorators"); | ||
Object.defineProperty(exports, "prop", { enumerable: true, get: function () { return decorators_1.prop; } }); | ||
Object.defineProperty(exports, "method", { enumerable: true, get: function () { return decorators_1.method; } }); | ||
const contract_1 = require("./contract"); | ||
var contract_1 = require("./contract"); | ||
Object.defineProperty(exports, "SmartContract", { enumerable: true, get: function () { return contract_1.SmartContract; } }); | ||
const library_1 = require("./library"); | ||
var library_1 = require("./library"); | ||
Object.defineProperty(exports, "SmartContractLib", { enumerable: true, get: function () { return library_1.SmartContractLib; } }); | ||
@@ -26,0 +26,0 @@ __exportStar(require("./builtins/types"), exports); |
@@ -27,7 +27,7 @@ "use strict"; | ||
exports.Indexer = void 0; | ||
const path = __importStar(require("path")); | ||
const fs = __importStar(require("fs")); | ||
const INDEX_FILE_NAME = 'scrypt.index.json'; | ||
class Indexer { | ||
constructor(pathParam) { | ||
var path = __importStar(require("path")); | ||
var fs = __importStar(require("fs")); | ||
var INDEX_FILE_NAME = 'scrypt.index.json'; | ||
var Indexer = /** @class */ (function () { | ||
function Indexer(pathParam) { | ||
this.symbolPaths = new Map(); | ||
@@ -53,58 +53,62 @@ if (typeof pathParam === "string") { | ||
} | ||
query(symbol, includeBase = false) { | ||
const sPath = this.symbolPaths.get(symbol); | ||
Indexer.prototype.query = function (symbol, includeBase) { | ||
if (includeBase === void 0) { includeBase = false; } | ||
var sPath = this.symbolPaths.get(symbol); | ||
return sPath && includeBase ? path.join(this.scryptBasePath, sPath) : sPath; | ||
} | ||
save() { | ||
let content = { | ||
}; | ||
Indexer.prototype.save = function () { | ||
var _this = this; | ||
var content = { | ||
'scryptBase': this.scryptBasePath, | ||
'bindings': Array.from(this.symbolPaths.keys()).map(symbol => { | ||
return { symbol, path: this.symbolPaths.get(symbol) }; | ||
'bindings': Array.from(this.symbolPaths.keys()).map(function (symbol) { | ||
return { symbol: symbol, path: _this.symbolPaths.get(symbol) }; | ||
}) | ||
}; | ||
fs.writeFileSync(this.filePath, JSON.stringify(content)); | ||
} | ||
load() { | ||
}; | ||
Indexer.prototype.load = function () { | ||
var _this = this; | ||
if (!fs.existsSync(this.filePath)) { | ||
throw new Error(`index file not exist: ${this.filePath}`); | ||
throw new Error("index file not exist: ".concat(this.filePath)); | ||
} | ||
let content = JSON.parse(fs.readFileSync(this.filePath).toString()); | ||
var content = JSON.parse(fs.readFileSync(this.filePath).toString()); | ||
if (!content.scryptBase) { | ||
throw new Error(`missing \`scryptBase\` in index file ${this.filePath}`); | ||
throw new Error("missing `scryptBase` in index file ".concat(this.filePath)); | ||
} | ||
this.scryptBasePath = content.scryptBase; | ||
if (!content.bindings) { | ||
throw new Error(`missing \`bindings\` in index file ${this.filePath}`); | ||
throw new Error("missing `bindings` in index file ".concat(this.filePath)); | ||
} | ||
content.bindings.forEach(binding => { | ||
content.bindings.forEach(function (binding) { | ||
if (binding.symbol && binding.path) { | ||
this.symbolPaths.set(binding.symbol, binding.path); | ||
_this.symbolPaths.set(binding.symbol, binding.path); | ||
} | ||
}); | ||
} | ||
bindSymbols2Path(symbolsWithRange, symbolPath) { | ||
symbolsWithRange.forEach(symbolWithRange => { | ||
if (this.symbolPaths.has(symbolWithRange.name)) { | ||
const srcFileName = symbolWithRange.srcRange.fileName; | ||
const startLine = symbolWithRange.srcRange.start.line + 1; | ||
const startCol = symbolWithRange.srcRange.start.character + 1; | ||
const endLine = symbolWithRange.srcRange.end.line + 1; | ||
const endCol = symbolWithRange.srcRange.end.character + 1; | ||
console.log(`scrypt-ts WARNING - ${srcFileName}:${startLine}:${startCol}:${endLine}:${endCol} - symbol \`${symbolWithRange.name}\` already has a path binding \`${this.symbolPaths.get(symbolWithRange.name)}\` in ${this.filePath}\n`); | ||
}; | ||
Indexer.prototype.bindSymbols2Path = function (symbolsWithRange, symbolPath) { | ||
var _this = this; | ||
symbolsWithRange.forEach(function (symbolWithRange) { | ||
if (_this.symbolPaths.has(symbolWithRange.name)) { | ||
var srcFileName = symbolWithRange.srcRange.fileName; | ||
var startLine = symbolWithRange.srcRange.start.line + 1; | ||
var startCol = symbolWithRange.srcRange.start.character + 1; | ||
var endLine = symbolWithRange.srcRange.end.line + 1; | ||
var endCol = symbolWithRange.srcRange.end.character + 1; | ||
console.log("scrypt-ts WARNING - ".concat(srcFileName, ":").concat(startLine, ":").concat(startCol, ":").concat(endLine, ":").concat(endCol, " - symbol `").concat(symbolWithRange.name, "` already has a path binding `").concat(_this.symbolPaths.get(symbolWithRange.name), "` in ").concat(_this.filePath, "\n")); | ||
} | ||
this.symbolPaths.set(symbolWithRange.name, symbolPath); | ||
_this.symbolPaths.set(symbolWithRange.name, symbolPath); | ||
}); | ||
this.save(); | ||
} | ||
getPath(symbol) { | ||
}; | ||
Indexer.prototype.getPath = function (symbol) { | ||
return this.symbolPaths.get(symbol); | ||
} | ||
getFullPath(scryptFile) { | ||
}; | ||
Indexer.prototype.getFullPath = function (scryptFile) { | ||
return path.join(path.dirname(this.filePath), this.scryptBasePath, scryptFile); | ||
} | ||
static queryIndexFile(fromPath, toPath) { | ||
let searchDir = fromPath; | ||
}; | ||
Indexer.queryIndexFile = function (fromPath, toPath) { | ||
var searchDir = fromPath; | ||
toPath = toPath === undefined ? process.cwd() : toPath; | ||
do { | ||
let indexFile = path.join(searchDir, INDEX_FILE_NAME); | ||
var indexFile = path.join(searchDir, INDEX_FILE_NAME); | ||
if (fs.existsSync(indexFile)) { | ||
@@ -116,5 +120,6 @@ return indexFile; | ||
return undefined; | ||
} | ||
} | ||
}; | ||
return Indexer; | ||
}()); | ||
exports.Indexer = Indexer; | ||
//# sourceMappingURL=indexer.js.map |
@@ -15,9 +15,13 @@ "use strict"; | ||
*/ | ||
class SmartContractLib { | ||
constructor(...args) { | ||
var SmartContractLib = /** @class */ (function () { | ||
function SmartContractLib() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
this.args = []; | ||
this.args = args; | ||
} | ||
getArgs() { | ||
return (this.args || []).map(arg => { | ||
SmartContractLib.prototype.getArgs = function () { | ||
return (this.args || []).map(function (arg) { | ||
if (arg instanceof SmartContractLib) { | ||
@@ -28,14 +32,16 @@ return arg.getArgs(); | ||
}); | ||
} | ||
getState() { | ||
return Object.keys(this).reduce((acc, key) => { | ||
if (typeof this[key] === 'bigint' || typeof this[key] === 'boolean' || typeof this[key] === 'string') { | ||
return Object.assign(acc, { | ||
[key]: this[key] | ||
}); | ||
}; | ||
SmartContractLib.prototype.getState = function () { | ||
var _this = this; | ||
return Object.keys(this).reduce(function (acc, key) { | ||
var _a, _b; | ||
if (typeof _this[key] === 'bigint' || typeof _this[key] === 'boolean' || typeof _this[key] === 'string') { | ||
return Object.assign(acc, (_a = {}, | ||
_a[key] = _this[key], | ||
_a)); | ||
} | ||
else if (this[key] instanceof SmartContractLib) { | ||
return Object.assign(acc, { | ||
[key]: this[key].getState() | ||
}); | ||
else if (_this[key] instanceof SmartContractLib) { | ||
return Object.assign(acc, (_b = {}, | ||
_b[key] = _this[key].getState(), | ||
_b)); | ||
} | ||
@@ -46,5 +52,6 @@ else { | ||
}, {}); | ||
} | ||
} | ||
}; | ||
return SmartContractLib; | ||
}()); | ||
exports.SmartContractLib = SmartContractLib; | ||
//# sourceMappingURL=library.js.map |
@@ -26,18 +26,20 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const path = __importStar(require("path")); | ||
const indexer_1 = require("./indexer"); | ||
const transpiler_1 = require("./transpiler"); | ||
const dist_1 = require("scryptlib/dist"); | ||
var path = __importStar(require("path")); | ||
var indexer_1 = require("./indexer"); | ||
var transpiler_1 = require("./transpiler"); | ||
var dist_1 = require("scryptlib/dist"); | ||
/*** | ||
* @ignore | ||
*/ | ||
function transformProgram(program, host, pluginOptions, { ts: tsInstance }) { | ||
const compilerOptions = program.getCompilerOptions(); | ||
const compilerHost = getPatchedHost(host, tsInstance, compilerOptions); | ||
const rootFileNames = program.getRootFileNames().map(path.normalize); | ||
let tsconfigDir = process.env['TS_NODE_PROJECT'] ? path.dirname(process.env['TS_NODE_PROJECT']) : '.'; | ||
function transformProgram(program, host, pluginOptions, _a) { | ||
var _b, _c; | ||
var tsInstance = _a.ts; | ||
var compilerOptions = program.getCompilerOptions(); | ||
var compilerHost = getPatchedHost(host, tsInstance, compilerOptions); | ||
var rootFileNames = program.getRootFileNames().map(path.normalize); | ||
var tsconfigDir = process.env['TS_NODE_PROJECT'] ? path.dirname(process.env['TS_NODE_PROJECT']) : '.'; | ||
tsconfigDir = path.isAbsolute(tsconfigDir) ? tsconfigDir : path.join(program.getCurrentDirectory(), tsconfigDir); | ||
let tsRootDir = program.getCompilerOptions().rootDir ?? tsconfigDir; | ||
let jsOutDir = program.getCompilerOptions().outDir ?? tsconfigDir; | ||
let scryptOutDir = pluginOptions.outDir | ||
var tsRootDir = (_b = program.getCompilerOptions().rootDir) !== null && _b !== void 0 ? _b : tsconfigDir; | ||
var jsOutDir = (_c = program.getCompilerOptions().outDir) !== null && _c !== void 0 ? _c : tsconfigDir; | ||
var scryptOutDir = pluginOptions.outDir | ||
? path.join(tsconfigDir, pluginOptions.outDir) | ||
@@ -49,7 +51,7 @@ : jsOutDir; | ||
console.log(Array(20).fill('*'), 'path context', Array(20).fill('*')); | ||
console.log(`tsRootDir: ${tsRootDir}\ntsconfigDir: ${tsconfigDir}\njsOutDir: ${jsOutDir}\nscryptOutDir: ${scryptOutDir}`); | ||
console.log("tsRootDir: ".concat(tsRootDir, "\ntsconfigDir: ").concat(tsconfigDir, "\njsOutDir: ").concat(jsOutDir, "\nscryptOutDir: ").concat(scryptOutDir)); | ||
console.log(Array(50).fill('*'), '\n'); | ||
} | ||
let indexer = new indexer_1.Indexer({ tsconfigDir, scryptOutDir }); | ||
let checker = program.getTypeChecker(); | ||
var indexer = new indexer_1.Indexer({ tsconfigDir: tsconfigDir, scryptOutDir: scryptOutDir }); | ||
var checker = program.getTypeChecker(); | ||
/* Apply the transformation */ | ||
@@ -64,4 +66,4 @@ tsInstance.transform(program.getSourceFiles(), [ | ||
function getPatchedHost(maybeHost, tsInstance, compilerOptions) { | ||
const fileCache = new Map(); | ||
const compilerHost = maybeHost ?? tsInstance.createCompilerHost(compilerOptions, true); | ||
var fileCache = new Map(); | ||
var compilerHost = maybeHost !== null && maybeHost !== void 0 ? maybeHost : tsInstance.createCompilerHost(compilerOptions, true); | ||
if (compilerHost.fileCache !== undefined) { | ||
@@ -71,10 +73,10 @@ // return the already patched host | ||
} | ||
const cacheableVersion = (originalFunc) => { | ||
var cacheableVersion = function (originalFunc) { | ||
return function (fileName) { | ||
if (fileCache.has(fileName)) { | ||
const file = fileCache.get(fileName); | ||
var file = fileCache.get(fileName); | ||
fileCache.delete(fileName); // patch for making `tsc --watch` to work | ||
return file; | ||
} | ||
const sourceFile = originalFunc.apply(void 0, Array.from(arguments)); | ||
var sourceFile = originalFunc.apply(void 0, Array.from(arguments)); | ||
fileCache.set(fileName, sourceFile); | ||
@@ -86,3 +88,3 @@ return sourceFile; | ||
getSourceFile: cacheableVersion(compilerHost.getSourceFile), | ||
fileCache | ||
fileCache: fileCache | ||
}, compilerHost.getSourceFileByPath ? | ||
@@ -93,10 +95,10 @@ { getSourceFileByPath: cacheableVersion(compilerHost.getSourceFileByPath) } | ||
function applyInjections(tsInstance, host, sourceFile, injections) { | ||
const { fileName, text: originText, languageVersion } = sourceFile; | ||
let updatedText = ""; | ||
let lastInjectedIdx = 0; | ||
injections.sort((a, b) => a.pos - b.pos).forEach(injection => { | ||
var fileName = sourceFile.fileName, originText = sourceFile.text, languageVersion = sourceFile.languageVersion; | ||
var updatedText = ""; | ||
var lastInjectedIdx = 0; | ||
injections.sort(function (a, b) { return a.pos - b.pos; }).forEach(function (injection) { | ||
if (injection.pos < 1 || injection.pos > originText.length + 1) { | ||
throw new Error(`invalid injection position: ${injection.pos} on ${originText.length}`); | ||
throw new Error("invalid injection position: ".concat(injection.pos, " on ").concat(originText.length)); | ||
} | ||
const idx = injection.pos - 1; | ||
var idx = injection.pos - 1; | ||
updatedText += originText.slice(lastInjectedIdx, idx) + injection.code; | ||
@@ -106,3 +108,3 @@ lastInjectedIdx = idx; | ||
updatedText += originText.slice(lastInjectedIdx); | ||
const newFile = tsInstance.createSourceFile(fileName, updatedText, languageVersion, true); | ||
var newFile = tsInstance.createSourceFile(fileName, updatedText, languageVersion, true); | ||
newFile.version = (0, dist_1.md5)(updatedText); // patch for making `tsc --watch` work | ||
@@ -112,4 +114,4 @@ return newFile; | ||
function transformFile(host, checker, tsRootDir, scryptOutDir, indexer, ctx) { | ||
const tsInstance = this; | ||
return (sourceFile) => { | ||
var tsInstance = this; | ||
return function (sourceFile) { | ||
// skip declaration files of *.d.ts | ||
@@ -120,7 +122,7 @@ if (sourceFile.fileName.endsWith('.d.ts')) { | ||
// ts source file to root dir relative path which will be keeped in scrypt output structure. | ||
const root2srcRelativePath = path.relative(tsRootDir, sourceFile.fileName); | ||
var root2srcRelativePath = path.relative(tsRootDir, sourceFile.fileName); | ||
// the relative path from the scrypt output root directory to the file | ||
const scryptFile = root2srcRelativePath.replace(/\.ts$/, '.scrypt').replaceAll('\\', '/'); | ||
const transformFile = root2srcRelativePath.replace(/\.ts$/, '.transformer.json').replaceAll('\\', '/'); | ||
let transpiler = new transpiler_1.Transpiler(sourceFile, checker, scryptOutDir, scryptFile, transformFile, indexer); | ||
var scryptFile = root2srcRelativePath.replace(/\.ts$/, '.scrypt').replaceAll('\\', '/'); | ||
var transformFile = root2srcRelativePath.replace(/\.ts$/, '.transformer.json').replaceAll('\\', '/'); | ||
var transpiler = new transpiler_1.Transpiler(sourceFile, checker, scryptOutDir, scryptFile, transformFile, indexer); | ||
if (!transpiler.isTransformable()) { | ||
@@ -130,11 +132,12 @@ return sourceFile; | ||
transpiler.transform(); | ||
let injections = []; | ||
var injections = []; | ||
function visitor(node) { | ||
var _a; | ||
if (transpiler.scComponents.includes(node)) { | ||
const classNode = node; | ||
const className = classNode.name?.escapedText.toString(); | ||
var classNode = node; | ||
var className = (_a = classNode.name) === null || _a === void 0 ? void 0 : _a.escapedText.toString(); | ||
if (className) { | ||
injections.push({ | ||
pos: classNode.end + 1, | ||
code: `Reflect.defineMetadata("scrypt:transform", "${transformFile}", ${className});Reflect.defineMetadata("__filename", __filename, ${className});` | ||
code: "Reflect.defineMetadata(\"scrypt:transform\", \"".concat(transformFile, "\", ").concat(className, ");Reflect.defineMetadata(\"__filename\", __filename, ").concat(className, ");") | ||
}); | ||
@@ -147,3 +150,3 @@ } | ||
tsInstance.visitEachChild(sourceFile, visitor, ctx); | ||
const updatedSourceFile = applyInjections(tsInstance, host, sourceFile, injections); | ||
var updatedSourceFile = applyInjections(tsInstance, host, sourceFile, injections); | ||
host.fileCache.set(sourceFile.fileName, updatedSourceFile); | ||
@@ -150,0 +153,0 @@ return updatedSourceFile; |
@@ -27,3 +27,3 @@ "use strict"; | ||
exports.isNumberLiteralExpr = exports.hasModifier = exports.number2hex = exports.getBuildInType = exports.getPreimage = exports.signTx = void 0; | ||
const ts = __importStar(require("typescript")); | ||
var ts = __importStar(require("typescript")); | ||
var scryptlib_1 = require("scryptlib"); | ||
@@ -60,3 +60,3 @@ Object.defineProperty(exports, "signTx", { enumerable: true, get: function () { return scryptlib_1.signTx; } }); | ||
function number2hex(val) { | ||
let hex = val.toString(16); | ||
var hex = val.toString(16); | ||
if (hex.length % 2 === 1) { | ||
@@ -68,11 +68,17 @@ hex = '0' + hex; | ||
exports.number2hex = number2hex; | ||
function hasModifier(node, ...kinds) { | ||
function hasModifier(node) { | ||
var kinds = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
kinds[_i - 1] = arguments[_i]; | ||
} | ||
if (ts.canHaveModifiers(node)) { | ||
let modifiers = ts.getModifiers(node); | ||
var modifiers = ts.getModifiers(node); | ||
if (typeof modifiers === 'undefined') { | ||
return false; | ||
} | ||
for (const modifier of modifiers) | ||
for (var _a = 0, modifiers_1 = modifiers; _a < modifiers_1.length; _a++) { | ||
var modifier = modifiers_1[_a]; | ||
if (kinds.includes(modifier.kind)) | ||
return true; | ||
} | ||
} | ||
@@ -79,0 +85,0 @@ return false; |
{ | ||
"name": "scrypt-ts", | ||
"version": "0.1.5-beta.6", | ||
"version": "0.1.5-test.1", | ||
"description": "A toolset for building sCrypt smart contract applications on Bitcoin SV network written in typescript.", | ||
@@ -11,7 +11,9 @@ "main": "dist/index.js", | ||
"gendocs": "typedoc --readme none --plugin typedoc-plugin-markdown --out scryptTS-docs src/index.ts", | ||
"clean-test-out": "rimraf test/scrypt.index.json && rimraf test/out && rimraf test/artifacts", | ||
"pretest": "npm run build && npm run clean-test-out && cross-env TS_NODE_PROJECT=test/tsconfig.json NODE_ENV=test tsc -p test", | ||
"clean-test-out": "rimraf test/scrypt.index.json && rimraf test/out", | ||
"pretest": "npm run build && cross-env TS_NODE_PROJECT=test/tsconfig.json NODE_ENV=test tsc -p test", | ||
"test": "cd test && mocha 'out/test/local/**/*.test.js' --timeout 1200000", | ||
"pretestnet": "cross-env TS_NODE_PROJECT=test/tsconfig.json tsc test/testnet/hashpuzzle.ts", | ||
"testnet": "cd test && node out/test/testnet/hashpuzzle.js", | ||
"publish:beta": "npm publish --tag beta", | ||
"publish:test": "npm publish --tag test", | ||
"single-test": "npm run build && npm run clean-test-out && cross-env TS_NODE_PROJECT=test/tsconfig.json NODE_ENV=test mocha -r ts-node/register" | ||
@@ -18,0 +20,0 @@ }, |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
252452
5198
27