@harmoniclabs/plu-ts
Advanced tools
Comparing version 0.3.0-dev1 to 0.3.0-dev10
import { byte } from "./types.js"; | ||
export declare function deriveEd25519PublicKey(privateKey: byte[]): byte[]; | ||
export declare function signEd25519(message: byte[] | Uint8Array, privateKey: byte[] | Uint8Array): [pubKey: byte[], signature: byte[]]; | ||
export declare function getEd25519Signature(message: byte[] | Uint8Array, privateKey: byte[] | Uint8Array): byte[]; | ||
export declare function verifyEd25519Signature(signature: byte[] | Uint8Array, message: byte[] | Uint8Array, publicKey: byte[] | Uint8Array): boolean; | ||
type Uint8ArrayLike = Uint8Array | string | byte[]; | ||
/** | ||
* based on the [`globalThis.crypto`](https://developer.mozilla.org/en-US/docs/Web/API/crypto_property) property | ||
**/ | ||
export declare function genKeys(): { | ||
privateKey: Uint8Array; | ||
publicKey: Uint8Array; | ||
}; | ||
export declare function deriveEd25519PublicKey(privateKey: Uint8ArrayLike): Uint8Array; | ||
export declare function signEd25519(message: Uint8ArrayLike, privateKey: Uint8ArrayLike): [pubKey: Uint8Array, signature: Uint8Array]; | ||
export declare function getEd25519Signature(message: Uint8ArrayLike, privateKey: Uint8ArrayLike): Uint8Array; | ||
export declare function verifyEd25519Signature(signature: Uint8ArrayLike, message: Uint8ArrayLike, publicKey: Uint8ArrayLike): boolean; | ||
export {}; |
@@ -18,207 +18,488 @@ "use strict"; | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
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.verifyEd25519Signature = exports.getEd25519Signature = exports.signEd25519 = exports.deriveEd25519PublicKey = void 0; | ||
var BasePlutsError_1 = require("../errors/BasePlutsError.js"); | ||
exports.verifyEd25519Signature = exports.getEd25519Signature = exports.signEd25519 = exports.deriveEd25519PublicKey = exports.genKeys = void 0; | ||
var uint8array_utils_1 = require("@harmoniclabs/uint8array-utils"); | ||
var BigIntUtils_1 = __importDefault(require("../utils/BigIntUtils/index.js")); | ||
var JsRuntime_1 = __importDefault(require("../utils/JsRuntime/index.js")); | ||
var types_1 = require("./types.js"); | ||
var sha2_512_1 = require("./sha2_512.js"); | ||
var types_1 = require("./types.js"); | ||
var positiveMod_1 = require("./utils/positiveMod.js"); | ||
var Q = BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"); // ipowi(255) - 19 | ||
var Q38 = BigInt("7237005577332262213973186563042994240829374041602535252466099000494570602494"); // (Q + 3)/8 | ||
var CURVE_ORDER = BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"); // ipow2(252) + 27742317777372353535851937790883648493; | ||
var D = -BigInt("4513249062541557337682894930092624173785641285191125241628941591882900924598840740"); // -121665 * invert(121666); | ||
var I = BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"); // expMod(BigInt( 2 ), (Q - BigInt( 1 ))/4, Q); | ||
var BASE = Object.freeze([ | ||
BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"), | ||
BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960") // (4*invert(5)) % Q | ||
]); | ||
/** | ||
* | ||
* @param {bigint} b | ||
* @param {bigint} e | ||
* @param {bigint} m | ||
* @returns {bigint} | ||
*/ | ||
function expMod(b, e, m) { | ||
if (e == BigInt(0)) { | ||
return BigInt(1); | ||
/*! | ||
@noble/ed25519 implementation | ||
including the package itself was causing issue because es2020 | ||
reimplementing here (sorry) | ||
*/ | ||
var P = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"); // n2 ** 255n - 19n; // ed25519 is twisted edwards curve | ||
var N = BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"); // n2 ** 252n + 27742317777372353535851937790883648493n; // curve's (group) order | ||
var Gx = BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"); // base point x | ||
var Gy = BigInt("0x6666666666666666666666666666666666666666666666666666666666666658"); // base point y | ||
var n0 = BigInt(0); | ||
var n1 = BigInt(1); | ||
var n2 = BigInt(2); | ||
var N_div_2 = N / n2; | ||
var _n1 = BigInt(-1); | ||
// Curve's formula is −x² + y² = -a + dx²y² | ||
// where a=-1, d = -(121665/121666) == -(121665 * inv(121666)) mod P | ||
/* | ||
const CURVE = { | ||
a: -n1, | ||
d: 37095705934669439343138083508754565189542113879843219016388785533085940283555n, | ||
p: P, n: N, h: 8, Gx, Gy // field prime, curve (group) order, cofactor | ||
}; | ||
*/ | ||
var CURVE_H = 8; | ||
var CURVE_D = BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"); | ||
var err = function (m) { | ||
if (m === void 0) { m = ''; } | ||
throw new Error(m); | ||
}; // error helper, messes-up stack trace | ||
var str = function (s) { return typeof s === 'string'; }; // is string | ||
var au8 = function (stuff, l) { | ||
if (!(stuff instanceof Uint8Array) || | ||
(typeof l === 'number' && | ||
l > 0 && | ||
stuff.length !== l)) | ||
throw new Error('Uint8Array expected'); | ||
return stuff; | ||
}; | ||
/** creates Uint8Array */ | ||
var u8n = function (data) { return new Uint8Array(data); }; | ||
/** norm(hex/u8a) to u8a */ | ||
var toU8 = function (a, len) { return au8(str(a) ? (0, uint8array_utils_1.fromHex)(a) : u8n(a), len); }; | ||
/** mod division */ | ||
var mod = function (a, b) { | ||
if (b === void 0) { b = P; } | ||
var r = a % b; | ||
return r >= n0 ? r : b + r; | ||
}; | ||
var Gpows = undefined; // precomputes for base point G | ||
function pointFromXY(x, y) { | ||
return [x, y, n1, mod(x * y)]; | ||
} | ||
function pointFromHex(hex, zip215) { | ||
if (zip215 === void 0) { zip215 = false; } | ||
hex = toU8(hex, 32); | ||
var normed = hex.slice(); // copy the array to not mess it up | ||
normed[31] = hex[31] & ~0x80; // adjust first LE byte = last BE byte | ||
var y = b2n_LE(normed); // decode as little-endian, convert to num | ||
if (zip215) { | ||
if (!(n0 <= y && y < BigInt("0x1" + "00".repeat(32)) /* n2 ** 256n */)) { | ||
err('bad y coord 1'); | ||
} | ||
} | ||
else { | ||
var t = expMod(b, e / BigInt(2), m); | ||
t = (t * t) % m; | ||
if ((e % BigInt(2)) != BigInt(0)) { | ||
t = (0, positiveMod_1.positiveMod)(t * b, m); | ||
if (!(n0 <= y && y < P)) { | ||
err('bad y coord 2'); | ||
} | ||
return t; | ||
} | ||
var y2 = mod(y * y); // y² | ||
var u = mod(y2 - n1); // u=y²-1 | ||
var v = mod(CURVE_D * y2 + n1); // v=dy²+1 | ||
var _a = uvRatio(u, v), isValid = _a.isValid, x = _a.value; // (uv³)(uv⁷)^(p-5)/8; square root | ||
if (!isValid) | ||
err('bad y coordinate 3'); // not square root: bad point | ||
var isXOdd = (x & n1) === n1; // adjust sign of x coordinate | ||
var isHeadOdd = (hex[31] & 0x80) !== 0; | ||
if (isHeadOdd !== isXOdd) | ||
x = mod(-x); | ||
return [x, y, n1, mod(x * y)]; // Z=1, T=xy | ||
} | ||
function invert(n) { | ||
var a = (0, positiveMod_1.positiveMod)(n, Q); | ||
var b = Q; | ||
var x = BigInt(0); | ||
var y = BigInt(1); | ||
var u = BigInt(1); | ||
var v = BigInt(0); | ||
while (a !== BigInt(0)) { | ||
var q = b / a; | ||
var r = b % a; | ||
var m = x - u * q; | ||
var n_1 = y - v * q; | ||
b = a; | ||
a = r; | ||
x = u; | ||
y = v; | ||
u = m; | ||
v = n_1; | ||
} | ||
return (0, positiveMod_1.positiveMod)(x, Q); | ||
var BASE_PX = Gx; | ||
var BASE_PY = Gy; | ||
var BASE_PZ = n1; | ||
var BASE_PT = mod(Gx * Gy); | ||
var G = Object.freeze([ | ||
BASE_PX, | ||
BASE_PY, | ||
BASE_PZ, | ||
BASE_PT | ||
]); | ||
var ZERO_PX = n0; | ||
var ZERO_PY = n1; | ||
var ZERO_PZ = n1; | ||
var ZERO_PT = n0; | ||
var I = Object.freeze([ | ||
ZERO_PX, | ||
ZERO_PY, | ||
ZERO_PZ, | ||
ZERO_PT | ||
]); | ||
function equalsPoints(X1, Y1, Z1, X2, Y2, Z2) { | ||
return mod(X1 * Z2) === mod(X2 * Z1) && mod(Y1 * Z2) === mod(Y2 * Z1); | ||
} | ||
/** | ||
* @param {bigint} y | ||
* @returns {bigint} | ||
*/ | ||
function recoverX(y) { | ||
var yy = y * y; | ||
var xx = (yy - BigInt(1)) * invert(D * yy + BigInt(1)); | ||
var x = expMod(xx, Q38, Q); | ||
if (((x * x - xx) % Q) !== BigInt(0)) { | ||
x = (x * I) % Q; | ||
} | ||
if ((x % BigInt(2)) !== BigInt(0)) { | ||
x = Q - x; | ||
} | ||
return x; | ||
function pointIsZero(X1, Y1, Z1) { | ||
return equalsPoints(X1, Y1, Z1, ZERO_PX, ZERO_PY, ZERO_PZ); | ||
} | ||
/** | ||
* Curve point 'addition' | ||
* Note: this is probably the bottleneck of this Ed25519 implementation | ||
*/ | ||
function edwards(a, b) { | ||
var x1 = a[0]; | ||
var y1 = a[1]; | ||
var x2 = b[0]; | ||
var y2 = b[1]; | ||
var dxxyy = D * x1 * x2 * y1 * y2; | ||
var x3 = (x1 * y2 + x2 * y1) * invert(BigInt(1) + dxxyy); | ||
var y3 = (y1 * y2 + x1 * x2) * invert(BigInt(1) - dxxyy); | ||
return [(0, positiveMod_1.positiveMod)(x3, Q), (0, positiveMod_1.positiveMod)(y3, Q)]; | ||
function negatePoint(x, y, z, t) { | ||
return [mod(-x), y, z, mod(-t)]; | ||
} | ||
function scalarMul(point, n) { | ||
if (n === BigInt(0)) { | ||
return [BigInt(0), BigInt(1)]; | ||
} | ||
else { | ||
var sum = scalarMul(point, n / BigInt(2)); | ||
sum = edwards(sum, sum); | ||
if ((n % BigInt(2)) !== BigInt(0)) { | ||
sum = edwards(sum, point); | ||
function negatePointLike(_a) { | ||
var _b = __read(_a, 4), x = _b[0], y = _b[1], z = _b[2], t = _b[3]; | ||
return [mod(-x), y, z, mod(-t)]; | ||
} | ||
function negatePointLike_inplace(p) { | ||
p[0] = mod(-p[0]); | ||
p[3] = mod(-p[3]); | ||
} | ||
function doublePoint(X1, Y1, Z1) { | ||
var a = _n1; // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd | ||
var A = mod(X1 * X1); | ||
var B = mod(Y1 * Y1); | ||
var C = mod(n2 * mod(Z1 * Z1)); | ||
var D = mod(a * A); | ||
var x1y1 = X1 + Y1; | ||
var E = mod(mod(x1y1 * x1y1) - A - B); | ||
var G = D + B; | ||
var F = G - C; | ||
var H = D - B; | ||
var X3 = mod(E * F); | ||
var Y3 = mod(G * H); | ||
var T3 = mod(E * H); | ||
var Z3 = mod(F * G); | ||
return [X3, Y3, Z3, T3]; | ||
} | ||
function addPoints(X1, Y1, Z1, T1, X2, Y2, Z2, T2) { | ||
// http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-3 | ||
var A = mod(X1 * X2); | ||
var B = mod(Y1 * Y2); | ||
var C = mod(T1 * CURVE_D * T2); | ||
var D = mod(Z1 * Z2); | ||
var E = mod((X1 + Y1) * (X2 + Y2) - A - B); | ||
var F = mod(D - C); | ||
var G = mod(D + C); | ||
var H = mod(B - _n1 * A); | ||
var X3 = mod(E * F); | ||
var Y3 = mod(G * H); | ||
var T3 = mod(E * H); | ||
var Z3 = mod(F * G); | ||
return [X3, Y3, Z3, T3]; | ||
} | ||
function addPoinLikeInFirst(fst, snd) { | ||
var _a = __read(fst, 4), X1 = _a[0], Y1 = _a[1], Z1 = _a[2], T1 = _a[3]; | ||
var _b = __read(snd, 4), X2 = _b[0], Y2 = _b[1], Z2 = _b[2], T2 = _b[3]; | ||
// http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-3 | ||
var A = mod(X1 * X2); | ||
var B = mod(Y1 * Y2); | ||
var C = mod(T1 * CURVE_D * T2); | ||
var D = mod(Z1 * Z2); | ||
var E = mod((X1 + Y1) * (X2 + Y2) - A - B); | ||
var F = mod(D - C); | ||
var G = mod(D + C); | ||
var H = mod(B - _n1 * A); | ||
fst[0] = mod(E * F); | ||
fst[1] = mod(G * H); | ||
fst[2] = mod(E * H); | ||
fst[3] = mod(F * G); | ||
} | ||
function pointLikeScalarMul(point, n, safe) { | ||
if (safe === void 0) { safe = true; } | ||
} | ||
function scalarMul(X1, Y1, Z1, T1, n, safe) { | ||
var _a; | ||
if (safe === void 0) { safe = true; } | ||
if (n === n0) | ||
return safe === true ? err('cannot multiply by 0') : I; | ||
if (!(typeof n === 'bigint' && n0 < n && n < N)) | ||
err('invalid scalar, must be < L'); | ||
if (!safe && pointIsZero(X1, Y1, Z1) || n === n1) | ||
return [X1, Y1, Z1, T1]; // safe=true bans 0. safe=false allows 0. | ||
if (equalsPoints(X1, Y1, Z1, BASE_PX, BASE_PY, BASE_PZ)) | ||
return wNAF(n).p; // use wNAF precomputes for base points | ||
var p = I, f = G; // init result point & fake point | ||
for (; n > n0; | ||
// double-and-add ladder | ||
_a = __read(doublePoint(X1, Y1, Z1), 4), X1 = _a[0], Y1 = _a[1], Z1 = _a[2], T1 = _a[3], n >>= n1) { | ||
if (n & n1) | ||
p = addPoints(p[0], p[1], p[2], p[3], X1, Y1, Z1, T1); // if bit is present, add to point | ||
else if (safe) { | ||
// if not, add to fake for timing safety | ||
f = addPoints(f[0], f[1], f[2], f[3], X1, Y1, Z1, T1); | ||
} | ||
return sum; | ||
} | ||
return p; | ||
} | ||
/** | ||
* Curve point 'multiplication' | ||
*/ | ||
function encodeInt(y) { | ||
var bytes = Array.from(BigIntUtils_1.default.toBuffer(y)).reverse(); | ||
while (bytes.length < 32) { | ||
bytes.push(0); | ||
} | ||
return bytes; | ||
function getClearCofactor(X1, Y1, Z1, T1) { | ||
return scalarMul(X1, Y1, Z1, T1, BigInt(CURVE_H), false); | ||
} | ||
function decodeInt(s) { | ||
return BigInt("0x" + (0, types_1.byteArrToHex)(s.reverse())); | ||
function isSmallOrderPoint(X1, Y1, Z1, T1) { | ||
var _a; | ||
_a = __read(getClearCofactor(X1, Y1, Z1, T1), 3), X1 = _a[0], Y1 = _a[1], Z1 = _a[2]; | ||
return pointIsZero(X1, Y1, Z1); | ||
} | ||
function encodePoint(point) { | ||
var _a = __read(point, 2), x = _a[0], y = _a[1]; | ||
var bytes = encodeInt(y); | ||
// last bit is determined by x | ||
bytes[31] = ((bytes[31] & 255) | (Number(x & BigInt(1)) * 128)); | ||
return bytes; | ||
/** converts point to 2d xy affine point */ | ||
function toAffine(p) { | ||
var _a = __read(p, 3), x = _a[0], y = _a[1], z = _a[2]; // (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy) | ||
if (pointIsZero(x, y, z)) | ||
return { x: n0, y: n0 }; | ||
var iz = invert(z); // z^-1: invert z | ||
if (mod(z * iz) !== n1) | ||
err('invalid inverse'); // (z * z^-1) must be 1, otherwise bad math | ||
return { x: mod(x * iz), y: mod(y * iz) }; // x = x*z^-1; y = y*z^-1 | ||
} | ||
function getBit(bytes, i) { | ||
return ((bytes[Math.floor(i / 8)] >> i % 8) & 1); | ||
function toRawUint8Array(p) { | ||
var _a = toAffine(p), x = _a.x, y = _a.y; // convert to affine 2d point | ||
var b = n2b_32LE(y); // encode number to 32 Uint8Array | ||
b[31] |= x & n1 ? 0x80 : 0; // store sign in first LE byte | ||
return b; | ||
} | ||
function isOnCurve(point) { | ||
var x = point[0]; | ||
var y = point[1]; | ||
var xx = x * x; | ||
var yy = y * y; | ||
return (-xx + yy - BigInt(1) - D * xx * yy) % Q == BigInt(0); | ||
var padh = function (num, pad) { return num.toString(16).padStart(pad, '0'); }; | ||
var n2b_32LE = function (num) { return (0, uint8array_utils_1.fromHex)(padh(num, 32 * 2)).reverse(); }; // number to Uint8Array LE | ||
var b2n_LE = function (b) { return BigInt('0x' + (0, uint8array_utils_1.toHex)(u8n(au8(b)).reverse())); }; // Uint8Array LE to num | ||
var concatB = function () { | ||
var arrs = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
arrs[_i] = arguments[_i]; | ||
} | ||
var r = u8n(arrs.reduce(function (sum, a) { return sum + au8(a).length; }, 0)); // create u8a of summed length | ||
var pad = 0; // walk through each array, | ||
arrs.forEach(function (a) { r.set(a, pad); pad += a.length; }); // ensure they have proper type | ||
return r; | ||
}; | ||
var invert = function (num, md) { | ||
if (md === void 0) { md = P; } | ||
if (num === n0 || md <= n0) | ||
err('no inverse n=' + num + ' mod=' + md); // no neg exponent for now | ||
var a = mod(num, md), b = md, x = n0, y = n1, u = n1, v = n0; | ||
while (a !== n0) { // uses euclidean gcd algorithm | ||
var q = b / a, r = b % a; // not constant-time | ||
var m = x - u * q, n = y - v * q; | ||
b = a, a = r, x = u, y = v, u = m, v = n; | ||
} | ||
return b === n1 ? mod(x, md) : err('no inverse'); // b is gcd at this point | ||
}; | ||
var pow2 = function (x, power) { | ||
var r = x; | ||
while (power-- > n0) { | ||
r *= r; | ||
r %= P; | ||
} | ||
return r; | ||
}; | ||
var pow_2_252_3 = function (x) { | ||
var x2 = (x * x) % P; // x^2, bits 1 | ||
var b2 = (x2 * x) % P; // x^3, bits 11 | ||
var b4 = (pow2(b2, n2) * b2) % P; // x^(2^4-1), bits 1111 | ||
var b5 = (pow2(b4, n1) * x) % P; // x^(2^5-1), bits 11111 | ||
var b10 = (pow2(b5, BigInt(5)) * b5) % P; // x^(2^10) | ||
var b20 = (pow2(b10, BigInt(10)) * b10) % P; // x^(2^20) | ||
var b40 = (pow2(b20, BigInt(20)) * b20) % P; // x^(2^40) | ||
var b80 = (pow2(b40, BigInt(40)) * b40) % P; // x^(2^80) | ||
var b160 = (pow2(b80, BigInt(80)) * b80) % P; // x^(2^160) | ||
var b240 = (pow2(b160, BigInt(80)) * b80) % P; // x^(2^240) | ||
var b250 = (pow2(b240, BigInt(10)) * b10) % P; // x^(2^250) | ||
var pow_p_5_8 = (pow2(b250, n2) * x) % P; // < To pow to (p+3)/8, multiply it by x. | ||
return { pow_p_5_8: pow_p_5_8, b2: b2 }; | ||
}; | ||
var RM1 = BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"); // √-1 | ||
var uvRatio = function (u, v) { | ||
var v3 = mod(v * v * v); // v³ | ||
var v7 = mod(v3 * v3 * v); // v⁷ | ||
var pow = pow_2_252_3(u * v7).pow_p_5_8; // (uv⁷)^(p-5)/8 | ||
var x = mod(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8 | ||
var vx2 = mod(v * x * x); // vx² | ||
var root1 = x; // First root candidate | ||
var root2 = mod(x * RM1); // Second root candidate; RM1 is √-1 | ||
var useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root | ||
var useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4) | ||
var noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1 | ||
if (useRoot1) | ||
x = root1; | ||
if (useRoot2 || noRoot) | ||
x = root2; // We return root2 anyway, for const-time | ||
if ((mod(x) & n1) === n1) | ||
x = mod(-x); // edIsNegative | ||
return { isValid: useRoot1 || useRoot2, value: x }; | ||
}; | ||
var modL_LE = function (hash) { return mod(b2n_LE(hash), N); }; // modulo L; but little-endian | ||
var _shaS; | ||
var sha512s = function (message) { return new Uint8Array((0, sha2_512_1.sha2_512)((0, types_1.buffToByteArr)(message))); }; | ||
/** RFC8032 5.1.5 */ | ||
var hash2extK = function (hashed) { | ||
var head = hashed.slice(0, 32); // slice creates a copy, unlike subarray | ||
head[0] &= 248; // Clamp bits: 0b1111_1000, | ||
head[31] &= 127; // 0b0111_1111, | ||
head[31] |= 64; // 0b0100_0000 | ||
var prefix = hashed.slice(32, 64); // private key "prefix" | ||
var scalar = modL_LE(head); // modular division over curve order | ||
// public key point | ||
var point = scalarMul(BASE_PX, BASE_PY, BASE_PZ, BASE_PT, scalar); | ||
return { head: head, prefix: prefix, scalar: scalar, point: point, pointUint8Array: toRawUint8Array(point) }; | ||
}; | ||
// RFC8032 5.1.5; getPublicKey async, sync. Hash priv key and extract point. | ||
var getExtendedPublicKey = function (priv) { return hash2extK(sha512s(toU8(priv, 32))); }; | ||
var getPublicKey = function (priv) { return getExtendedPublicKey(priv).pointUint8Array; }; | ||
function hashFinish(res) { | ||
return res.finish(sha512s(res.hashable)); | ||
} | ||
function decodePoint(s) { | ||
JsRuntime_1.default.assert(s.length == 32, "point must have length of 32"); | ||
var bytes = s.slice(); | ||
bytes[31] = (bytes[31] & 127); | ||
var y = decodeInt(bytes); | ||
var x = recoverX(y); | ||
if (Number(x & BigInt(1)) != getBit(s, 255)) { | ||
x = Q - x; | ||
var _sign = function (e, rUint8Array, msg) { | ||
var P = e.pointUint8Array, s = e.scalar; | ||
var r = modL_LE(rUint8Array); // r was created outside, reduce it modulo L | ||
// R = [r]B | ||
var R = toRawUint8Array(scalarMul(BASE_PX, BASE_PY, BASE_PZ, BASE_PT, r)); | ||
var hashable = concatB(R, P, msg); // dom2(F, C) || R || A || PH(M) | ||
var finish = function (hashed) { | ||
var S = mod(r + modL_LE(hashed) * s, N); // S = (r + k * s) mod L; 0 <= s < l | ||
return au8(concatB(R, n2b_32LE(S)), 64); // 64-byte sig: 32b R.x + 32b LE(S) | ||
}; | ||
return { hashable: hashable, finish: finish }; | ||
}; | ||
var sign = function (msg, privKey) { | ||
var m = toU8(msg); // RFC8032 5.1.6: sign msg with key sync | ||
var e = getExtendedPublicKey(privKey); // pub,prfx | ||
var rUint8Array = sha512s(m); // r = SHA512(dom2(F, C) || prefix || PH(M)) | ||
return hashFinish(_sign(e, rUint8Array, m)); // gen R, k, S, then 64-byte signature | ||
}; | ||
var dvo = { zip215: true }; | ||
var _verify = function (sig, msg, pub, opts) { | ||
if (opts === void 0) { opts = dvo; } | ||
msg = toU8(msg); // Message hex str/Uint8Array | ||
sig = toU8(sig, 64); // Signature hex str/Uint8Array, must be 64 Uint8Array | ||
var zip215 = opts.zip215; // switch between zip215 and rfc8032 verif | ||
var A, R, s, SB, hashable = new Uint8Array(); | ||
try { | ||
A = pointFromHex(pub, zip215); // public key A decoded | ||
R = pointFromHex(sig.slice(0, 32), zip215); // 0 <= R < 2^256: ZIP215 R can be >= P | ||
s = b2n_LE(sig.slice(32, 64)); // Decode second half as an integer S | ||
// in the range 0 <= s < L | ||
SB = scalarMul(BASE_PX, BASE_PY, BASE_PZ, BASE_PT, s, false); | ||
hashable = concatB(toRawUint8Array(R), toRawUint8Array(A), msg); // dom2(F, C) || R || A || PH(M) | ||
} | ||
var point = [x, y]; | ||
if (!isOnCurve(point)) { | ||
throw new BasePlutsError_1.BasePlutsError("point isn't on curve"); | ||
catch (error) { } | ||
var finish = function (hashed) { | ||
if (SB == null) | ||
return false; // false if try-catch catched an error | ||
var k = modL_LE(hashed); // decode in little-endian, modulo L | ||
var A_mult_k = scalarMul(A[0], A[1], A[2], A[3], k, false); | ||
// [8]R + [8][k]A' | ||
var RkA = addPoints(R[0], R[1], R[2], R[3], A_mult_k[0], A_mult_k[1], A_mult_k[2], A_mult_k[3]); | ||
negatePointLike_inplace(SB); | ||
var added = addPoints.apply(void 0, __spreadArray(__spreadArray([], __read(RkA), false), __read(SB), false)); | ||
var _a = __read(getClearCofactor.apply(void 0, __spreadArray([], __read(added), false)), 3), x = _a[0], y = _a[1], z = _a[2]; | ||
return pointIsZero(x, y, z); // [8][S]B = [8]R + [8][k]A' | ||
}; | ||
return { hashable: hashable, finish: finish }; | ||
}; | ||
/** RFC8032 5.1.7: verification */ | ||
var verify = function (s, m, p, opts) { | ||
if (opts === void 0) { opts = dvo; } | ||
return hashFinish(_verify(s, m, p)); | ||
}; | ||
var cr = function () { | ||
return typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; | ||
}; | ||
// CSPRNG (random number generator) | ||
function randomUint8Array(len) { | ||
var crypto = cr(); // Can be shimmed in node.js <= 18 to prevent error: | ||
// import { webcrypto } from 'node:crypto'; | ||
// if (!globalThis.crypto) globalThis.crypto = webcrypto; | ||
if (!crypto) | ||
err('crypto.getRandomValues must be defined'); | ||
return crypto.getRandomValues(u8n(len)); | ||
} | ||
function randomPrivateKey() { | ||
return randomUint8Array(32); | ||
} | ||
var W = 8; // Precomputes-related code. W = window size | ||
var _2_pow_W_1 = Math.pow(2, (W - 1)); | ||
var _2_pow_W = Math.pow(2, W); | ||
var precompute = function () { | ||
var points = []; // 10x sign(), 2x verify(). To achieve this, | ||
var windows = 256 / W + 1; // app needs to spend 40ms+ to calculate | ||
var p = G, b = p; // a lot of points related to base point G. | ||
for (var w = 0; w < windows; w++) // Points are stored in array and used | ||
{ | ||
b = p; // any time Gx multiplication is done. | ||
points.push(b); // They consume 16-32 MiB of RAM. | ||
for (var i = 1; i < _2_pow_W_1; i++) { | ||
// needs to create a new point each time | ||
// otherwise we update a precomputed point | ||
b = addPoints.apply(void 0, __spreadArray(__spreadArray([], __read(b), false), __read(p), false)); | ||
points.push(b); | ||
} | ||
p = doublePoint(b[0], b[1], b[2]); // b.double();// Precomputes don't speed-up getSharedKey, | ||
} // which multiplies user point by scalar, | ||
return points; // when precomputes are using base point | ||
}; | ||
/** | ||
* w-ary non-adjacent form (wNAF) method. | ||
* Compared to other point mult methods, | ||
* stores 2x less points using subtraction | ||
* @param n | ||
* @returns | ||
*/ | ||
var wNAF = function (n) { | ||
var comp = Gpows !== null && Gpows !== void 0 ? Gpows : (Gpows = precompute()); | ||
var neg = function (cnd, p) { | ||
return cnd ? negatePointLike(p) : p; | ||
}; // negate | ||
// must clone here not to modify the constants | ||
var p = I.slice(), f = G.slice(); // f must be G, or could become I in the end | ||
var windows = 1 + 256 / W; // W=8 17 windows | ||
var wsize = _2_pow_W_1; // W=8 128 window size | ||
var mask = BigInt(_2_pow_W - 1); // W=8 will create mask 0b11111111 | ||
var maxNum = _2_pow_W; // W=8 256 | ||
var shiftBy = BigInt(W); // W=8 8 | ||
for (var w = 0; w < windows; w++) { | ||
var off = w * wsize; | ||
var wbits = Number(n & mask); // extract W bits. | ||
n >>= shiftBy; // shift number by W bits. | ||
if (wbits > wsize) { | ||
wbits -= maxNum; | ||
n += n1; | ||
} // split if bits > max: +224 => 256-32 | ||
var off1 = off, off2 = off + Math.abs(wbits) - 1; // offsets, evaluate both | ||
var cnd1 = w % 2 !== 0, cnd2 = wbits < 0; // conditions, evaluate both | ||
if (wbits === 0) { | ||
addPoinLikeInFirst(f, neg(cnd1, comp[off1])); | ||
// f = f.add(neg(cnd1, comp[off1])); // bits are 0: add garbage to fake point | ||
} | ||
else { // ^ can't add off2, off2 = I | ||
addPoinLikeInFirst(p, neg(cnd2, comp[off2])); | ||
// p = p.add(neg(cnd2, comp[off2])); // bits are 1: add to result point | ||
} | ||
} | ||
return point; | ||
return { p: p, f: f }; // return both real and fake points for JIT | ||
}; // !! you can disable precomputes by commenting-out call of the wNAF() inside PointLike#mul() | ||
function forceUint8Array(stuff) { | ||
if (typeof stuff === "string") | ||
return (0, uint8array_utils_1.fromHex)(stuff); | ||
return (0, uint8array_utils_1.isUint8Array)(stuff) ? stuff : new Uint8Array(stuff); | ||
} | ||
function getA(h) { | ||
var a = BigInt("28948022309329048855892746252171976963317496166410141009864396001978282409984"); // ipow2(253) | ||
var bytes = h.slice(0, 32); | ||
bytes[0] = (bytes[0] & 248); | ||
bytes[31] = (bytes[31] & 63); | ||
return a + BigInt("0x" + (0, types_1.byteArrToHex)(bytes.reverse())); | ||
/** | ||
* based on the [`globalThis.crypto`](https://developer.mozilla.org/en-US/docs/Web/API/crypto_property) property | ||
**/ | ||
function genKeys() { | ||
var privateKey = randomPrivateKey(); | ||
return { | ||
privateKey: privateKey, | ||
publicKey: getPublicKey(privateKey) | ||
}; | ||
} | ||
function ihash(m) { | ||
return decodeInt((0, sha2_512_1.sha2_512)(m)); | ||
} | ||
exports.genKeys = genKeys; | ||
function deriveEd25519PublicKey(privateKey) { | ||
var privateKeyHash = (0, sha2_512_1.sha2_512)(privateKey); | ||
var a = getA(privateKeyHash); | ||
var A = scalarMul(BASE, a); | ||
return encodePoint(A); | ||
return getPublicKey(forceUint8Array(privateKey)); | ||
} | ||
exports.deriveEd25519PublicKey = deriveEd25519PublicKey; | ||
function signEd25519(message, privateKey) { | ||
message = (0, uint8array_utils_1.isUint8Array)(message) ? (0, types_1.buffToByteArr)(message) : message; | ||
privateKey = (0, uint8array_utils_1.isUint8Array)(privateKey) ? (0, types_1.buffToByteArr)(privateKey) : privateKey; | ||
var privateKeyHash = (0, sha2_512_1.sha2_512)(privateKey); | ||
var a = getA(privateKeyHash); | ||
// for convenience getulate publicKey here: | ||
var publicKey = encodePoint(scalarMul(BASE, a)); | ||
var r = ihash(privateKeyHash.slice(32, 64).concat(message)); | ||
var R = scalarMul(BASE, r); | ||
var S = (0, positiveMod_1.positiveMod)(r + ihash(encodePoint(R).concat(publicKey).concat(message)) * a, CURVE_ORDER); | ||
return [publicKey, encodePoint(R).concat(encodeInt(S))]; | ||
return [ | ||
deriveEd25519PublicKey(privateKey), | ||
sign(forceUint8Array(message), forceUint8Array(privateKey)) | ||
]; | ||
} | ||
exports.signEd25519 = signEd25519; | ||
function getEd25519Signature(message, privateKey) { | ||
return signEd25519(message, privateKey)[1]; | ||
return sign(forceUint8Array(message), forceUint8Array(privateKey)); | ||
} | ||
exports.getEd25519Signature = getEd25519Signature; | ||
function verifyEd25519Signature(signature, message, publicKey) { | ||
if (signature.length !== 64 || publicKey.length != 32) { | ||
throw new BasePlutsError_1.BasePlutsError("unexpected signature length ".concat(signature.length)); | ||
} | ||
if ((0, uint8array_utils_1.isUint8Array)(signature)) { | ||
signature = (0, types_1.buffToByteArr)(signature); | ||
} | ||
if ((0, uint8array_utils_1.isUint8Array)(message)) { | ||
message = (0, types_1.buffToByteArr)(message); | ||
} | ||
if ((0, uint8array_utils_1.isUint8Array)(publicKey)) { | ||
publicKey = (0, types_1.buffToByteArr)(publicKey); | ||
} | ||
var R = decodePoint(signature.slice(0, 32)); | ||
var A = decodePoint(publicKey); | ||
var S = decodeInt(signature.slice(32, 64)); | ||
var h = ihash(signature.slice(0, 32).concat(publicKey).concat(message)); | ||
var left = scalarMul(BASE, S); | ||
var right = edwards(R, scalarMul(A, h)); | ||
return (left[0] == right[0]) && (left[1] == right[1]); | ||
return verify(forceUint8Array(signature), forceUint8Array(message), forceUint8Array(publicKey)); | ||
} | ||
exports.verifyEd25519Signature = verifyEd25519Signature; |
@@ -88,3 +88,3 @@ "use strict"; | ||
function forceUint64(n) { | ||
return (BigInt(n) & BigInt("18446744073709551615")); | ||
return (BigInt(n) & BigInt("0x" + "ff".repeat(8))); | ||
} | ||
@@ -95,3 +95,3 @@ exports.forceUint64 = forceUint64; | ||
n >= BigInt(0) && | ||
n < BigInt("18446744073709551616") // n < (1 << 64) | ||
n < BigInt("0x1" + "00".repeat(8)) // n < (1 << 64) | ||
); | ||
@@ -98,0 +98,0 @@ } |
@@ -16,3 +16,3 @@ import { NativeScript } from "./NativeScript.js"; | ||
export interface PlutusScriptJsonFormat<T extends PlutusScriptType = PlutusScriptType> { | ||
type: PlutusScriptType; | ||
type: T; | ||
description?: string; | ||
@@ -19,0 +19,0 @@ cborHex: string; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.cloneITxBuildInput = void 0; | ||
var CanBeData_1 = require("../../../../types/Data/CanBeData/index.js"); | ||
function cloneITxBuildInput(_a) { | ||
@@ -9,4 +10,4 @@ var utxo = _a.utxo, ref = _a.referenceScriptV2, inScript = _a.inputScript; | ||
refUtxo: ref.refUtxo.clone(), | ||
datum: ref.datum === "inline" ? "inline" : ref.datum.clone(), | ||
redeemer: ref.redeemer.clone() | ||
datum: ref.datum === "inline" ? "inline" : (0, CanBeData_1.cloneCanBeData)(ref.datum), | ||
redeemer: (0, CanBeData_1.cloneCanBeData)(ref.redeemer) | ||
}; | ||
@@ -16,4 +17,4 @@ var inputScript = inScript === undefined ? undefined : | ||
script: inScript.script.clone(), | ||
datum: inScript.datum === "inline" ? "inline" : inScript.datum.clone(), | ||
redeemer: inScript.redeemer.clone() | ||
datum: inScript.datum === "inline" ? "inline" : (0, CanBeData_1.cloneCanBeData)(inScript.datum), | ||
redeemer: (0, CanBeData_1.cloneCanBeData)(inScript.redeemer) | ||
}; | ||
@@ -20,0 +21,0 @@ return { |
@@ -72,3 +72,3 @@ "use strict"; | ||
var _a = __read((0, crypto_1.signEd25519)(_this.body.hash.toBuffer(), signer.toBuffer()), 2), derivedPubKey = _a[0], signature = _a[1]; | ||
_this.addVKeyWitness(new TxWitnessSet_2.VKeyWitness(new TxWitnessSet_2.VKey(new Uint8Array(derivedPubKey)), new hashes_1.Signature(new Uint8Array(signature)))); | ||
_this.addVKeyWitness(new TxWitnessSet_2.VKeyWitness(new TxWitnessSet_2.VKey(derivedPubKey), new hashes_1.Signature(signature))); | ||
}); | ||
@@ -75,0 +75,0 @@ Object.defineProperty(this, "isComplete", { |
@@ -13,3 +13,4 @@ import { Cloneable } from "../../../types/interfaces/Cloneable.js"; | ||
clone(): CEKFrames; | ||
_unsafe_clear(): void; | ||
} | ||
export declare function showFrames(frames: Readonly<CEKFrames>): string; |
@@ -31,2 +31,5 @@ "use strict"; | ||
}; | ||
CEKFrames.prototype._unsafe_clear = function () { | ||
this._frames.length = 0; | ||
}; | ||
return CEKFrames; | ||
@@ -33,0 +36,0 @@ }()); |
@@ -9,2 +9,3 @@ import { Cloneable } from "../../../types/interfaces/Cloneable.js"; | ||
get(idx: number): CEKValue | undefined; | ||
_unsafe_clear(): void; | ||
} |
@@ -26,4 +26,7 @@ "use strict"; | ||
}; | ||
CEKHeap.prototype._unsafe_clear = function () { | ||
this._heap.length = 0; | ||
}; | ||
return CEKHeap; | ||
}()); | ||
exports.CEKHeap = CEKHeap; |
@@ -0,5 +1,6 @@ | ||
import { Cloneable } from "../../../types/interfaces/Cloneable.js"; | ||
import { UPLCTerm } from "../../UPLC/UPLCTerm/index.js"; | ||
import { CEKEnv } from "../CEKEnv.js"; | ||
import { CEKValue } from "../CEKValue/index.js"; | ||
export declare class ComputeStep { | ||
export declare class ComputeStep implements Cloneable<ComputeStep> { | ||
private _term; | ||
@@ -10,7 +11,9 @@ get term(): UPLCTerm; | ||
constructor(term: UPLCTerm, env: CEKEnv); | ||
clone(): ComputeStep; | ||
} | ||
export declare class ReturnStep { | ||
export declare class ReturnStep implements Cloneable<ReturnStep> { | ||
private _value; | ||
get value(): CEKValue; | ||
constructor(value: CEKValue); | ||
clone(): ReturnStep; | ||
} | ||
@@ -24,4 +27,5 @@ export type CEKStep = ComputeStep | ReturnStep; | ||
top(): Readonly<CEKStep> | undefined; | ||
_unsafe_clear(): void; | ||
get topIsReturn(): boolean; | ||
get topIsCompute(): boolean; | ||
} |
"use strict"; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.CEKSteps = exports.ReturnStep = exports.ComputeStep = void 0; | ||
var JsRuntime_1 = __importDefault(require("../../../utils/JsRuntime/index.js")); | ||
var ComputeStep = /** @class */ (function () { | ||
@@ -23,2 +19,5 @@ function ComputeStep(term, env) { | ||
}); | ||
ComputeStep.prototype.clone = function () { | ||
return new ComputeStep(this._term.clone(), this._env.clone()); | ||
}; | ||
return ComputeStep; | ||
@@ -36,2 +35,5 @@ }()); | ||
}); | ||
ReturnStep.prototype.clone = function () { | ||
return new ReturnStep(this.value.clone()); | ||
}; | ||
return ReturnStep; | ||
@@ -53,4 +55,7 @@ }()); | ||
return undefined; | ||
return JsRuntime_1.default.objWithUnderscoreAsPrivate(this._steps[this._steps.length - 1]); | ||
return Object.freeze(this._steps[this._steps.length - 1]); | ||
}; | ||
CEKSteps.prototype._unsafe_clear = function () { | ||
this._steps.length = 0; | ||
}; | ||
Object.defineProperty(CEKSteps.prototype, "topIsReturn", { | ||
@@ -57,0 +62,0 @@ get: function () { |
@@ -6,3 +6,2 @@ "use strict"; | ||
var ConstValue_1 = require("../../UPLC/UPLCTerms/UPLCConst/ConstValue/index.js"); | ||
var BitStream_1 = require("../../../types/bits/BitStream/index.js"); | ||
var Application_1 = require("../../UPLC/UPLCTerms/Application.js"); | ||
@@ -13,3 +12,2 @@ var Builtin_1 = require("../../UPLC/UPLCTerms/Builtin/index.js"); | ||
var Force_1 = require("../../UPLC/UPLCTerms/Force.js"); | ||
var HoistedUPLC_1 = require("../../UPLC/UPLCTerms/HoistedUPLC/index.js"); | ||
var Lambda_1 = require("../../UPLC/UPLCTerms/Lambda.js"); | ||
@@ -25,5 +23,2 @@ var UPLCConst_1 = require("../../UPLC/UPLCTerms/UPLCConst/index.js"); | ||
return false; | ||
if (a instanceof HoistedUPLC_1.HoistedUPLC && b instanceof HoistedUPLC_1.HoistedUPLC) { | ||
return BitStream_1.BitStream.eq(a.compiled, b.compiled); | ||
} | ||
if (a instanceof DelayCEK_1.DelayCEK && b instanceof DelayCEK_1.DelayCEK) { | ||
@@ -30,0 +25,0 @@ return CEKEnv_1.CEKEnv.eq(a.env, b.env) && eqCEKValue(a.delayedTerm, b.delayedTerm); |
@@ -21,3 +21,2 @@ "use strict"; | ||
var Force_1 = require("../../UPLC/UPLCTerms/Force.js"); | ||
var HoistedUPLC_1 = require("../../UPLC/UPLCTerms/HoistedUPLC/index.js"); | ||
var Lambda_1 = require("../../UPLC/UPLCTerms/Lambda.js"); | ||
@@ -102,7 +101,2 @@ var UPLCConst_1 = require("../../UPLC/UPLCTerms/UPLCConst/index.js"); | ||
// n_compute++; | ||
if (term instanceof HoistedUPLC_1.HoistedUPLC) { | ||
// HoistedUPLC are always closed; do not need external variables | ||
steps.push(new CEKSteps_1.ComputeStep(term.UPLC, new CEKEnv_1.CEKEnv(heap))); | ||
return; | ||
} | ||
if (term instanceof ErrorUPLC_1.ErrorUPLC) { | ||
@@ -160,6 +154,2 @@ steps.push(new CEKSteps_1.ReturnStep(term)); | ||
// n_returns++; | ||
if (v instanceof HoistedUPLC_1.HoistedUPLC) { | ||
steps.push(new CEKSteps_1.ComputeStep(v.UPLC, new CEKEnv_1.CEKEnv(heap))); | ||
return; | ||
} | ||
if (v instanceof PartialBuiltin_1.PartialBuiltin) { | ||
@@ -286,7 +276,2 @@ if (v.nMissingArgs === 0) { | ||
hasComputeStep && onComputeStep(); | ||
if (term instanceof HoistedUPLC_1.HoistedUPLC) { | ||
// HoistedUPLC are always closed; do not need external variables | ||
steps.push(new CEKSteps_1.ComputeStep(term.UPLC, new CEKEnv_1.CEKEnv(heap))); | ||
return; | ||
} | ||
if (term instanceof ErrorUPLC_1.ErrorUPLC) { | ||
@@ -344,6 +329,2 @@ steps.push(new CEKSteps_1.ReturnStep(term)); | ||
// n_returns++; | ||
if (v instanceof HoistedUPLC_1.HoistedUPLC) { | ||
steps.push(new CEKSteps_1.ComputeStep(v.UPLC, new CEKEnv_1.CEKEnv(heap))); | ||
return; | ||
} | ||
if (v instanceof PartialBuiltin_1.PartialBuiltin) { | ||
@@ -350,0 +331,0 @@ if (v.nMissingArgs === 0) { |
@@ -55,2 +55,3 @@ "use strict"; | ||
var IRDelayed_1 = require("./IRDelayed.js"); | ||
var showIR_1 = require("../utils/showIR.js"); | ||
var defaultHoistedMeta = ObjectUtils_1.default.freezeAll({ | ||
@@ -67,4 +68,6 @@ forceHoist: false | ||
hoisted = hoisted.hoisted; | ||
if (!(0, isClosedIRTerm_1.isClosedIRTerm)(hoisted)) | ||
if (!(0, isClosedIRTerm_1.isClosedIRTerm)(hoisted)) { | ||
console.log((0, showIR_1.prettyIRJsonStr)(hoisted)); | ||
throw new BasePlutsError_1.BasePlutsError("only closed terms can be hoisted"); | ||
} | ||
// initialize without calling "set" | ||
@@ -71,0 +74,0 @@ var _hoisted = hoisted; |
@@ -67,2 +67,5 @@ "use strict"; | ||
// initialize without calling "set" | ||
// cloning here otherwhise breaks the tree | ||
// TODO: find what is breaking the tree | ||
// when solved add `this.value.clone()` to the `IRLetted.clone` method below | ||
var _value = toLet.clone(); | ||
@@ -157,3 +160,4 @@ _value.parent = this; | ||
ObjectUtils_1.default.defineReadOnlyProperty(this, "clone", function () { | ||
return new IRLetted(_this.dbn, _this.value.clone(), _this.meta); | ||
return new IRLetted(_this.dbn, _this.value, // .clone(), // cloned in constructor | ||
_this.meta); | ||
}); | ||
@@ -160,0 +164,0 @@ } |
@@ -35,2 +35,3 @@ "use strict"; | ||
}); | ||
var e = Error(); | ||
var _dbn; | ||
@@ -41,2 +42,3 @@ Object.defineProperty(this, "dbn", { | ||
if (!(Number.isSafeInteger(newDbn) && newDbn >= 0)) { | ||
console.log(e.stack); | ||
throw new BasePlutsError_1.BasePlutsError("invalid index for an `IRVar` instance; new DeBruijn was: " + newDbn); | ||
@@ -43,0 +45,0 @@ } |
import { IRTerm } from "../../IRTerm.js"; | ||
export declare function findAll(term: IRTerm, predicate: (elem: IRTerm) => boolean): IRTerm[]; | ||
export declare function findAllNoHoisted(term: IRTerm, predicate: (elem: IRTerm) => boolean): IRTerm[]; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.findAll = void 0; | ||
exports.findAllNoHoisted = exports.findAll = void 0; | ||
var IRApp_1 = require("../../IRNodes/IRApp.js"); | ||
@@ -34,4 +34,2 @@ var IRDelayed_1 = require("../../IRNodes/IRDelayed.js"); | ||
if (t instanceof IRHoisted_1.IRHoisted) { | ||
// 0 because hoisted are closed | ||
// for hoisted we keep track of the depth inside the term | ||
stack.push(t.hoisted); | ||
@@ -51,1 +49,40 @@ continue; | ||
exports.findAll = findAll; | ||
function findAllNoHoisted(term, predicate) { | ||
var stack = [term]; | ||
var result = []; | ||
while (stack.length > 0) { | ||
var t = stack.pop(); | ||
if (predicate(t)) | ||
result.push(t); | ||
if (t instanceof IRApp_1.IRApp) { | ||
stack.push(t.fn, t.arg); | ||
continue; | ||
} | ||
if (t instanceof IRDelayed_1.IRDelayed) { | ||
stack.push(t.delayed); | ||
continue; | ||
} | ||
if (t instanceof IRForced_1.IRForced) { | ||
stack.push(t.forced); | ||
continue; | ||
} | ||
if (t instanceof IRFunc_1.IRFunc) { | ||
stack.push(t.body); | ||
continue; | ||
} | ||
if (t instanceof IRHoisted_1.IRHoisted) { | ||
// this is `findAllNoHoisted` remember? | ||
// stack.push( t.hoisted ); | ||
continue; | ||
} | ||
if (t instanceof IRLetted_1.IRLetted) { | ||
// same stuff as the hoisted terms | ||
// the only difference is that depth is then incremented | ||
// once the letted term reaches its final position | ||
stack.push(t.value); | ||
continue; | ||
} | ||
} | ||
return result; | ||
} | ||
exports.findAllNoHoisted = findAllNoHoisted; |
import type { IRTerm } from "../../IRTerm.js"; | ||
type IRWithDept = IRTerm & { | ||
depth: number; | ||
}; | ||
export declare function lowestCommonAncestor(n1: IRWithDept | undefined, n2: IRWithDept | undefined): IRTerm | string; | ||
export {}; | ||
export declare function getDepthInMaxScope(term: IRTerm, maxScope: IRTerm): number | undefined; | ||
export declare function lowestCommonAncestor(n1: IRTerm | undefined, n2: IRTerm | undefined, maxScope: IRTerm): IRTerm | undefined; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.lowestCommonAncestor = void 0; | ||
exports.lowestCommonAncestor = exports.getDepthInMaxScope = void 0; | ||
var isIRTerm_1 = require("../../utils/isIRTerm.js"); | ||
function lowestCommonAncestor(n1, n2) { | ||
// type IRWithDepth = IRTerm & { depth: number } | ||
function getDepthInMaxScope(term, maxScope) { | ||
var depth = 0; | ||
while (term.parent !== maxScope) { | ||
depth++; | ||
if (term.parent === undefined) | ||
return undefined; | ||
term = term.parent; | ||
} | ||
return depth; | ||
} | ||
exports.getDepthInMaxScope = getDepthInMaxScope; | ||
function lowestCommonAncestor(n1, n2, maxScope) { | ||
if (!(0, isIRTerm_1.isIRTerm)(n1) || !(0, isIRTerm_1.isIRTerm)(n2)) | ||
return "not IR"; | ||
var d1 = n1.depth; | ||
var d2 = n2.depth; | ||
return undefined; | ||
var d1 = getDepthInMaxScope(n1, maxScope); | ||
var d2 = getDepthInMaxScope(n2, maxScope); | ||
if (d1 === undefined || d2 === undefined) { | ||
return undefined; | ||
} | ||
var diff = d1 - d2; | ||
@@ -25,8 +40,8 @@ // If node b is deeper, swap node a and node b | ||
return n1; | ||
// as any because undefined will exit the loop | ||
// undefined will exit the loop | ||
n1 = n1.parent; | ||
n2 = n2.parent; | ||
} | ||
return "no lca"; | ||
return undefined; | ||
} | ||
exports.lowestCommonAncestor = lowestCommonAncestor; |
@@ -11,2 +11,3 @@ "use strict"; | ||
var _irToUplc_1 = require("./_internal/_irToUplc.js"); | ||
var includesNode_1 = require("./_internal/includesNode.js"); | ||
function compileIRToUPLC(term) { | ||
@@ -51,3 +52,5 @@ /////////////////////////////////////////////////////////////////////////////// | ||
// replaced hoisted terms might include new letted terms | ||
(0, handleLetted_1.handleLetted)(term); | ||
while ((0, includesNode_1.includesNode)(term, function (node) { return node instanceof IRLetted_1.IRLetted; })) { | ||
(0, handleLetted_1.handleLetted)(term); | ||
} | ||
/////////////////////////////////////////////////////////////////////////////// | ||
@@ -54,0 +57,0 @@ // ------------------------------------------------------------------------- // |
@@ -16,5 +16,2 @@ "use strict"; | ||
var markRecursiveHoistsAsForced_1 = require("../markRecursiveHoistsAsForced.js"); | ||
function toHashArr(arr) { | ||
return arr.map(function (h) { return (0, uint8array_utils_1.toHex)(h.hash); }); | ||
} | ||
function handleHoistedAndReturnRoot(term) { | ||
@@ -36,2 +33,6 @@ // unwrap; | ||
var n = allHoisteds.length; | ||
// evaluating constants | ||
if (n === 0) { | ||
return term; | ||
} | ||
// nothing to do; shortcut. | ||
@@ -68,3 +69,2 @@ if (n === 0) | ||
root = root.parent; | ||
var prevRoot; | ||
function getIRVarForHoistedAtLevel(_hoistedHash, level) { | ||
@@ -82,3 +82,2 @@ var levelOfTerm = toHoist.findIndex(function (sortedH) { return (0, uint8array_utils_1.uint8ArrayEq)(sortedH.hash, _hoistedHash); }); | ||
var thisHoisted = toHoist[i]; | ||
prevRoot = root; | ||
root = new IRApp_1.IRApp(new IRFunc_1.IRFunc(1, root), thisHoisted.hoisted.clone()); | ||
@@ -101,3 +100,14 @@ } | ||
} | ||
// console.log( | ||
// showIRText( irTerm.parent as IRTerm ), | ||
// "\n\n", | ||
// showIRText( irTerm ), | ||
// ) | ||
(0, _modifyChildFromTo_1._modifyChildFromTo)(irTerm.parent, irTerm, irvar); | ||
Object.defineProperty(irTerm.meta, "handled", { | ||
value: true, | ||
writable: true, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return "continue"; | ||
@@ -104,0 +114,0 @@ } |
@@ -11,6 +11,10 @@ import { IRFunc } from "../../../IRNodes/IRFunc.js"; | ||
* | ||
* @param term | ||
* @returns {number | undefined} a `number` indicating the minimum debruijn `undefined` if the term is closed | ||
* @param _term | ||
* @returns {number | undefined} | ||
* a `number` if the `_term` param is open; | ||
* the number represents the debuijn an `IRVar` would have | ||
* pointing to the smallest scope that fulfills the term; | ||
* `undefined` if the term is closed | ||
*/ | ||
export declare function _getMinUnboundDbn(_term: IRTerm): number | undefined; | ||
export {}; |
@@ -68,4 +68,8 @@ "use strict"; | ||
* | ||
* @param term | ||
* @returns {number | undefined} a `number` indicating the minimum debruijn `undefined` if the term is closed | ||
* @param _term | ||
* @returns {number | undefined} | ||
* a `number` if the `_term` param is open; | ||
* the number represents the debuijn an `IRVar` would have | ||
* pointing to the smallest scope that fulfills the term; | ||
* `undefined` if the term is closed | ||
*/ | ||
@@ -72,0 +76,0 @@ function _getMinUnboundDbn(_term) { |
@@ -20,3 +20,2 @@ "use strict"; | ||
var IRVar_1 = require("../../../IRNodes/IRVar.js"); | ||
var _addDepth_1 = require("../../_internal/_addDepth.js"); | ||
var _modifyChildFromTo_1 = require("../../_internal/_modifyChildFromTo.js"); | ||
@@ -40,2 +39,7 @@ var findAll_1 = require("../../_internal/findAll.js"); | ||
var allLetteds = (0, IRLetted_1.getLettedTerms)(term); | ||
// most of the time we are just compiling small | ||
// pre-execuded terms (hence constants) | ||
// in these cases is likely we have no letted terms | ||
if (allLetteds.length === 0) | ||
return; | ||
// console.log("direct letted", allLetteds.map( jsonLettedSetEntry ) ); | ||
@@ -103,3 +107,3 @@ var groupedLetteds = (0, groupByScope_1.groupByScope)(allLetteds); | ||
*/ | ||
var refs = (0, findAll_1.findAll)(maxScope, function (elem) { | ||
var refs = (0, findAll_1.findAllNoHoisted)(maxScope, function (elem) { | ||
if (!(elem instanceof IRLetted_1.IRLetted)) | ||
@@ -122,2 +126,3 @@ return false; | ||
if (elem.dbn < lettedSet[lettedSetIdx].letted.dbn) { | ||
elem.meta.forceHoist = lettedSet[lettedSetIdx].letted.meta.forceHoist; | ||
lettedSet[lettedSetIdx].letted = elem; | ||
@@ -134,2 +139,3 @@ if (toLetIdx >= 0) { | ||
else { | ||
elem.meta.forceHoist = lettedSet[lettedSetIdx].letted.meta.forceHoist; | ||
lettedSet[lettedSetIdx].letted = elem; | ||
@@ -155,2 +161,3 @@ replacedLettedSetEntry[lettedSetIdx] = true; | ||
letted = lettedSet[i].letted; | ||
var forceHosit = letted.meta.forceHoist === true; | ||
if (letted.value instanceof IRVar_1.IRVar || // always inline vars | ||
@@ -169,20 +176,30 @@ // the letted hash is one of the ones to be inlined | ||
} | ||
// subtree migh change so depth will change | ||
// needs to be updated every loop | ||
(0, _addDepth_1._addDepths)(maxScope); | ||
var lca = refs[0]; | ||
for (var i_2 = 1; i_2 < refs.length; i_2++) { | ||
lca = (0, lowestCommonAncestor_1.lowestCommonAncestor)(lca, refs[i_2]); | ||
} | ||
if (!(0, isIRTerm_1.isIRTerm)(lca)) { | ||
throw new PlutsIRError_1.PlutsIRError(refs.length + " letting nodes with hash " + (0, uint8array_utils_1.toHex)(letted.hash) + " from different trees; error:" + lca); | ||
} | ||
while (!(lca instanceof IRFunc_1.IRFunc || | ||
lca instanceof IRDelayed_1.IRDelayed)) { | ||
lca = (_b = lca === null || lca === void 0 ? void 0 : lca.parent) !== null && _b !== void 0 ? _b : ""; | ||
if (!forceHosit) { | ||
// subtree migh change so depth will change | ||
// needs to be updated every loop | ||
// _addDepths( maxScope ); | ||
for (var i_2 = 1; i_2 < refs.length; i_2++) { | ||
lca = (0, lowestCommonAncestor_1.lowestCommonAncestor)(lca, refs[i_2], maxScope); | ||
if (!(0, isIRTerm_1.isIRTerm)(lca)) { | ||
break; | ||
} | ||
} | ||
if (!(0, isIRTerm_1.isIRTerm)(lca)) { | ||
throw new PlutsIRError_1.PlutsIRError("lowest common ancestor outside the max scope"); | ||
// default to maxScope | ||
lca = maxScope; | ||
throw new PlutsIRError_1.PlutsIRError("letting nodes with hash " + (0, uint8array_utils_1.toHex)(letted.hash) + " from different trees"); | ||
} | ||
else { | ||
// point to the first func or delay node | ||
while (!(lca instanceof IRFunc_1.IRFunc || | ||
lca instanceof IRDelayed_1.IRDelayed)) { | ||
lca = (_b = lca === null || lca === void 0 ? void 0 : lca.parent) !== null && _b !== void 0 ? _b : undefined; | ||
if (!(0, isIRTerm_1.isIRTerm)(lca)) { | ||
throw new PlutsIRError_1.PlutsIRError("lowest common ancestor outside the max scope"); | ||
} | ||
} | ||
} | ||
} | ||
var parentNode = lca; | ||
var parentNode = forceHosit ? maxScope : lca; | ||
var parentNodeDirectChild = parentNode instanceof IRFunc_1.IRFunc ? parentNode.body : parentNode.delayed; | ||
@@ -236,6 +253,21 @@ // add 1 to every var's DeBruijn that accesses stuff outside the parent node | ||
} | ||
letted = refs[0]; | ||
// console.log( | ||
// `maxScope includes parentNode: ${includesNode( maxScope, parentNode )}`, | ||
// `\nparentNode includes ${toHex( letted.hash )}: ${includesNode( parentNode, letted )}`, | ||
// `\nparentNode includes ref: ${includesNode( parentNode, refs[0] )}`, | ||
// ); | ||
// get the difference in DeBruijn | ||
// between the maxScope and the letted term | ||
var diffDbn = 0; // getDiffDbn( parentNodeDirectChild, letted ); | ||
/* | ||
if( diffDbn === undefined ) | ||
{ | ||
throw new PlutsIRError( | ||
"letted term was not part of the selected maxScope" | ||
); | ||
} | ||
//*/ | ||
//* | ||
var tmpNode = letted; | ||
var diffDbn = 0; | ||
while (tmpNode !== parentNode) { | ||
@@ -251,2 +283,3 @@ tmpNode = tmpNode.parent; | ||
} | ||
//*/ | ||
// console.log( "-------------------- adding letted value --------------------\n".repeat(3) ); | ||
@@ -253,0 +286,0 @@ // now we replace |
@@ -14,3 +14,3 @@ "use strict"; | ||
while (stack.length > 0) { | ||
var _a = stack.pop(), t = _a.term, isInRecursiveTerm = _a.isInRecursiveTerm; | ||
var _a = stack.pop(), t = _a.term, isInRecursiveTerm = _a.isInRecursiveTerm, isIRAppArg = _a.isIRAppArg; | ||
if (t instanceof IRApp_1.IRApp) { | ||
@@ -30,2 +30,20 @@ // must push the arg first and then the fucntion | ||
t instanceof IRLetted_1.IRLetted) { | ||
// if it is an hoisted/letted | ||
// DIRECTLY applied to something that makes it recursive | ||
if (isIRAppArg && | ||
t.parent instanceof IRApp_1.IRApp && | ||
t.parent.fn instanceof IRNative_1.IRNative && | ||
t.parent.fn.tag === -1 /* IRNativeTag.z_comb */) { | ||
// then check the hoisted/letted value instead of marking as hoisted | ||
if (t instanceof IRLetted_1.IRLetted) { | ||
stack.push({ term: t.value, isInRecursiveTerm: isInRecursiveTerm }); | ||
continue; | ||
} | ||
else // if( t instanceof IRHoisted ) | ||
{ | ||
stack.push({ term: t.hoisted, isInRecursiveTerm: isInRecursiveTerm }); | ||
continue; | ||
} | ||
continue; | ||
} | ||
if (isInRecursiveTerm) { | ||
@@ -32,0 +50,0 @@ t.meta.forceHoist = true; |
@@ -12,3 +12,3 @@ "use strict"; | ||
if (node instanceof IRLetted_1.IRLetted && (0, isClosedIRTerm_1.isClosedIRTerm)(node.value)) { | ||
(0, _modifyChildFromTo_1._modifyChildFromTo)(node.parent, node, new IRHoisted_1.IRHoisted(node.value)); | ||
(0, _modifyChildFromTo_1._modifyChildFromTo)(node.parent, node, new IRHoisted_1.IRHoisted(node.value, node.meta)); | ||
return true; | ||
@@ -15,0 +15,0 @@ } |
@@ -134,3 +134,3 @@ export * from "./ScriptContext/PScriptPurpose/index.js"; | ||
KeyRegistration: { | ||
_0: import("../../index.js").StructT<{ | ||
stakeKey: import("../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -154,3 +154,3 @@ _0: import("../../index.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../index.js").StructT<{ | ||
stakeKey: import("../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -296,3 +296,3 @@ _0: import("../../index.js").StructT<{ | ||
KeyRegistration: { | ||
_0: import("../../index.js").StructT<{ | ||
stakeKey: import("../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -316,3 +316,3 @@ _0: import("../../index.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../index.js").StructT<{ | ||
stakeKey: import("../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -480,3 +480,3 @@ _0: import("../../index.js").StructT<{ | ||
KeyRegistration: { | ||
_0: import("../../index.js").StructT<{ | ||
stakeKey: import("../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -500,3 +500,3 @@ _0: import("../../index.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../index.js").StructT<{ | ||
stakeKey: import("../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -642,3 +642,3 @@ _0: import("../../index.js").StructT<{ | ||
KeyRegistration: { | ||
_0: import("../../index.js").StructT<{ | ||
stakeKey: import("../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -662,3 +662,3 @@ _0: import("../../index.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../index.js").StructT<{ | ||
stakeKey: import("../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -834,3 +834,3 @@ _0: import("../../index.js").StructT<{ | ||
KeyRegistration: { | ||
_0: import("../../index.js").StructT<{ | ||
stakeKey: import("../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -854,3 +854,3 @@ _0: import("../../index.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../index.js").StructT<{ | ||
stakeKey: import("../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -857,0 +857,0 @@ _0: import("../../index.js").StructT<{ |
export declare const PDCert: import("../../../PTypes/PStruct/pstruct.js").PStruct<{ | ||
KeyRegistration: { | ||
_0: import("../../../type_system/types.js").StructT<{ | ||
stakeKey: import("../../../type_system/types.js").StructT<{ | ||
PStakingHash: { | ||
@@ -22,3 +22,3 @@ _0: import("../../../type_system/types.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../../type_system/types.js").StructT<{ | ||
stakeKey: import("../../../type_system/types.js").StructT<{ | ||
PStakingHash: { | ||
@@ -25,0 +25,0 @@ _0: import("../../../type_system/types.js").StructT<{ |
@@ -9,4 +9,4 @@ "use strict"; | ||
exports.PDCert = (0, pstruct_1.pstruct)({ | ||
KeyRegistration: { _0: PStakingCredential_1.PStakingCredential.type }, | ||
KeyDeRegistration: { _0: PStakingCredential_1.PStakingCredential.type }, | ||
KeyRegistration: { stakeKey: PStakingCredential_1.PStakingCredential.type }, | ||
KeyDeRegistration: { stakeKey: PStakingCredential_1.PStakingCredential.type }, | ||
KeyDelegation: { | ||
@@ -13,0 +13,0 @@ delegator: PStakingCredential_1.PStakingCredential.type, |
@@ -113,3 +113,3 @@ export declare const PScriptContext: import("../../../PTypes/PStruct/pstruct.js").PStruct<{ | ||
KeyRegistration: { | ||
_0: import("../../../index.js").StructT<{ | ||
stakeKey: import("../../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -133,3 +133,3 @@ _0: import("../../../index.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../../index.js").StructT<{ | ||
stakeKey: import("../../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -275,3 +275,3 @@ _0: import("../../../index.js").StructT<{ | ||
KeyRegistration: { | ||
_0: import("../../../index.js").StructT<{ | ||
stakeKey: import("../../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -295,3 +295,3 @@ _0: import("../../../index.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../../index.js").StructT<{ | ||
stakeKey: import("../../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -298,0 +298,0 @@ _0: import("../../../index.js").StructT<{ |
@@ -39,3 +39,3 @@ export declare const PScriptPurpose: import("../../../../PTypes/PStruct/pstruct.js").PStruct<{ | ||
KeyRegistration: { | ||
_0: import("../../../../index.js").StructT<{ | ||
stakeKey: import("../../../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -59,3 +59,3 @@ _0: import("../../../../index.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../../../index.js").StructT<{ | ||
stakeKey: import("../../../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -62,0 +62,0 @@ _0: import("../../../../index.js").StructT<{ |
@@ -111,3 +111,3 @@ export declare const PTxInfo: import("../../../../PTypes/PStruct/pstruct.js").PStruct<{ | ||
KeyRegistration: { | ||
_0: import("../../../../type_system/types.js").StructT<{ | ||
stakeKey: import("../../../../type_system/types.js").StructT<{ | ||
PStakingHash: { | ||
@@ -131,3 +131,3 @@ _0: import("../../../../type_system/types.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../../../type_system/types.js").StructT<{ | ||
stakeKey: import("../../../../type_system/types.js").StructT<{ | ||
PStakingHash: { | ||
@@ -134,0 +134,0 @@ _0: import("../../../../type_system/types.js").StructT<{ |
@@ -199,3 +199,3 @@ export declare const PScriptContext: import("../../../PTypes/PStruct/pstruct.js").PStruct<{ | ||
KeyRegistration: { | ||
_0: import("../../../index.js").StructT<{ | ||
stakeKey: import("../../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -219,3 +219,3 @@ _0: import("../../../index.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../../index.js").StructT<{ | ||
stakeKey: import("../../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -353,3 +353,3 @@ _0: import("../../../index.js").StructT<{ | ||
KeyRegistration: { | ||
_0: import("../../../index.js").StructT<{ | ||
stakeKey: import("../../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -373,3 +373,3 @@ _0: import("../../../index.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../../index.js").StructT<{ | ||
stakeKey: import("../../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -471,3 +471,3 @@ _0: import("../../../index.js").StructT<{ | ||
KeyRegistration: { | ||
_0: import("../../../index.js").StructT<{ | ||
stakeKey: import("../../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -491,3 +491,3 @@ _0: import("../../../index.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../../index.js").StructT<{ | ||
stakeKey: import("../../../index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -494,0 +494,0 @@ _0: import("../../../index.js").StructT<{ |
@@ -197,3 +197,3 @@ export declare const PTxInfo: import("../../../../PTypes/PStruct/pstruct.js").PStruct<{ | ||
KeyRegistration: { | ||
_0: import("../../../../type_system/index.js").StructT<{ | ||
stakeKey: import("../../../../type_system/index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -217,3 +217,3 @@ _0: import("../../../../type_system/index.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../../../type_system/index.js").StructT<{ | ||
stakeKey: import("../../../../type_system/index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -351,3 +351,3 @@ _0: import("../../../../type_system/index.js").StructT<{ | ||
KeyRegistration: { | ||
_0: import("../../../../type_system/index.js").StructT<{ | ||
stakeKey: import("../../../../type_system/index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -371,3 +371,3 @@ _0: import("../../../../type_system/index.js").StructT<{ | ||
KeyDeRegistration: { | ||
_0: import("../../../../type_system/index.js").StructT<{ | ||
stakeKey: import("../../../../type_system/index.js").StructT<{ | ||
PStakingHash: { | ||
@@ -374,0 +374,0 @@ _0: import("../../../../type_system/index.js").StructT<{ |
@@ -5,9 +5,9 @@ import type { TermFn, PString } from "../../PTypes/index.js"; | ||
export declare function ptrace<ReturnT extends TermType>(returnT: ReturnT): TermFn<[PString, ToPType<ReturnT>], ToPType<ReturnT>>; | ||
export declare const ptraceIfTrue: Term<import("../../PTypes/index.js").PLam<PString, import("../../PTypes/index.js").PLam<import("../../PTypes/index.js").PBool, import("../../PTypes/index.js").PBool>>> & { | ||
$: (input: import("../index.js").PappArg<PString>) => Term<import("../../PTypes/index.js").PLam<import("../../PTypes/index.js").PBool, import("../../PTypes/index.js").PBool>> & { | ||
export declare const ptraceIfTrue: Term<import("../../PTypes/index.js").PLam<import("../../PTypes/index.js").PDelayed<PString>, import("../../PTypes/index.js").PLam<import("../../PTypes/index.js").PBool, import("../../PTypes/index.js").PBool>>> & { | ||
$: (input: Term<import("../../PTypes/index.js").PDelayed<PString>>) => Term<import("../../PTypes/index.js").PLam<import("../../PTypes/index.js").PBool, import("../../PTypes/index.js").PBool>> & { | ||
$: (input: import("../index.js").PappArg<import("../../PTypes/index.js").PBool>) => import("../index.js").UtilityTermOf<import("../../PTypes/index.js").PBool>; | ||
}; | ||
}; | ||
export declare const ptraceIfFalse: Term<import("../../PTypes/index.js").PLam<PString, import("../../PTypes/index.js").PLam<import("../../PTypes/index.js").PBool, import("../../PTypes/index.js").PBool>>> & { | ||
$: (input: import("../index.js").PappArg<PString>) => Term<import("../../PTypes/index.js").PLam<import("../../PTypes/index.js").PBool, import("../../PTypes/index.js").PBool>> & { | ||
export declare const ptraceIfFalse: Term<import("../../PTypes/index.js").PLam<import("../../PTypes/index.js").PDelayed<PString>, import("../../PTypes/index.js").PLam<import("../../PTypes/index.js").PBool, import("../../PTypes/index.js").PBool>>> & { | ||
$: (input: Term<import("../../PTypes/index.js").PDelayed<PString>>) => Term<import("../../PTypes/index.js").PLam<import("../../PTypes/index.js").PBool, import("../../PTypes/index.js").PBool>> & { | ||
$: (input: import("../index.js").PappArg<import("../../PTypes/index.js").PBool>) => import("../index.js").UtilityTermOf<import("../../PTypes/index.js").PBool>; | ||
@@ -14,0 +14,0 @@ }; |
@@ -21,11 +21,11 @@ "use strict"; | ||
exports.ptraceIfTrue = (0, phoist_1.phoist)((0, pfn_1.pfn)([ | ||
type_system_1.str, | ||
(0, type_system_1.delayed)(type_system_1.str), | ||
type_system_1.bool, | ||
], type_system_1.bool)(function (msg, boolean) { | ||
return (0, bool_1.pif)(type_system_1.bool).$(boolean) | ||
.then(ptrace(type_system_1.bool).$(msg).$((0, pBool_1.pBool)(true))) | ||
.then(ptrace(type_system_1.bool).$((0, pforce_1.pforce)(msg)).$((0, pBool_1.pBool)(true))) | ||
.else((0, pBool_1.pBool)(false)); | ||
})); | ||
exports.ptraceIfFalse = (0, phoist_1.phoist)((0, pfn_1.pfn)([ | ||
type_system_1.str, | ||
(0, type_system_1.delayed)(type_system_1.str), | ||
type_system_1.bool, | ||
@@ -35,3 +35,3 @@ ], type_system_1.bool)(function (msg, boolean) { | ||
.then((0, pBool_1.pBool)(true)) | ||
.else(ptrace(type_system_1.bool).$(msg).$((0, pBool_1.pBool)(false))); | ||
.else(ptrace(type_system_1.bool).$((0, pforce_1.pforce)(msg)).$((0, pBool_1.pBool)(false))); | ||
})); | ||
@@ -38,0 +38,0 @@ function ptraceError(t, somemsg) { |
@@ -54,4 +54,4 @@ "use strict"; | ||
(0, utils_1.termTypeToString)(arg.type) + | ||
"; which doesn't extends expected " + | ||
(0, utils_1.termTypeToString)(mustExtend)); | ||
"; which doesn't extends expected `" + | ||
(0, utils_1.termTypeToString)(mustExtend) + "`"); | ||
} | ||
@@ -64,4 +64,4 @@ return arg; | ||
// TODO: add proper error | ||
throw new BasePlutsError_1.BasePlutsError("pappArgToTerm :: `arg` was a possible `unit`; which doesn't extends expected type " + | ||
(0, utils_1.termTypeToString)(mustExtend)); | ||
throw new BasePlutsError_1.BasePlutsError("pappArgToTerm :: `arg` was `undefined` (a possible `unit`); which doesn't extends expected type `" + | ||
(0, utils_1.termTypeToString)(mustExtend) + "`"); | ||
} | ||
@@ -68,0 +68,0 @@ return (0, pmakeUnit_1.pmakeUnit)(); |
@@ -5,14 +5,4 @@ import type { PType } from "../../PType/index.js"; | ||
export type LettedTerm<PVarT extends PType> = UtilityTermOf<PVarT> & { | ||
/** | ||
* @deprecated you can use the result of `plet` directly | ||
* | ||
* @example | ||
* ```ts | ||
* const myTerm = plet( myValue ); | ||
* ``` | ||
* | ||
* ## the `in` method will be removed in a future version | ||
**/ | ||
in: <PExprResult extends PType>(expr: (value: UtilityTermOf<PVarT>) => Term<PExprResult>) => Term<PExprResult>; | ||
}; | ||
export declare function plet<PVarT extends PType, SomeExtension extends object>(varValue: Term<PVarT> & SomeExtension): LettedTerm<PVarT>; |
@@ -11,2 +11,4 @@ "use strict"; | ||
var fromData_minimal_1 = require("../std/data/conversion/fromData_minimal.js"); | ||
var isClosedIRTerm_1 = require("../../../IR/utils/isClosedIRTerm.js"); | ||
var IRHoisted_1 = require("../../../IR/IRNodes/IRHoisted.js"); | ||
function plet(varValue) { | ||
@@ -16,3 +18,16 @@ // unwrap 'asData' if is the case | ||
var type = varValue.type; | ||
var letted = new Term_1.Term(type, function (dbn) { return new IRLetted_1.IRLetted(Number(dbn), varValue.toIR(dbn)); }); | ||
var letted = new Term_1.Term(type, function (dbn) { | ||
var ir = varValue.toIR(dbn); | ||
// `compileIRToUPLC` can handle it even if this check is not present | ||
// but why spend useful tree iterations if we can avoid them here? | ||
if (ir instanceof IRLetted_1.IRLetted || | ||
ir instanceof IRHoisted_1.IRHoisted || | ||
ir instanceof IRVar_1.IRVar) { | ||
return ir; | ||
} | ||
if ((0, isClosedIRTerm_1.isClosedIRTerm)(ir)) { | ||
return new IRHoisted_1.IRHoisted(ir); | ||
} | ||
return new IRLetted_1.IRLetted(Number(dbn), ir); | ||
}); | ||
var continuation = function (expr) { | ||
@@ -19,0 +34,0 @@ var withUtility = (0, addUtilityForType_1.addUtilityForType)(varValue.type); |
@@ -6,15 +6,21 @@ "use strict"; | ||
var IRLetted_1 = require("../../../IR/IRNodes/IRLetted.js"); | ||
var IRVar_1 = require("../../../IR/IRNodes/IRVar.js"); | ||
var isClosedIRTerm_1 = require("../../../IR/utils/isClosedIRTerm.js"); | ||
var Term_1 = require("../../Term/index.js"); | ||
function _plet(varValue) { | ||
var valueToIR = varValue.toIR; | ||
return new Term_1.Term(varValue.type, function (dbn) { | ||
var ir = valueToIR(dbn); | ||
if (ir instanceof IRLetted_1.IRLetted || ir instanceof IRHoisted_1.IRHoisted) | ||
var ir = varValue.toIR(dbn); | ||
// `compileIRToUPLC` can handle it even if this check is not present | ||
// but why spend useful tree iterations if we can avoid them here? | ||
if (ir instanceof IRLetted_1.IRLetted || | ||
ir instanceof IRHoisted_1.IRHoisted || | ||
ir instanceof IRVar_1.IRVar) { | ||
return ir; | ||
if ((0, isClosedIRTerm_1.isClosedIRTerm)(ir)) | ||
} | ||
if ((0, isClosedIRTerm_1.isClosedIRTerm)(ir)) { | ||
return new IRHoisted_1.IRHoisted(ir); | ||
return new IRLetted_1.IRLetted(Number(dbn), valueToIR(dbn)); | ||
} | ||
return new IRLetted_1.IRLetted(Number(dbn), ir); | ||
}); | ||
} | ||
exports._plet = _plet; |
@@ -9,6 +9,14 @@ import { Term } from "../../../Term/index.js"; | ||
import { TermBool } from "./TermBool.js"; | ||
import { PData } from "../../../PTypes/index.js"; | ||
import { UtilityTermOf } from "../../addUtilityForType.js"; | ||
import { TermInt } from "./TermInt.js"; | ||
import { TermList } from "./TermList.js"; | ||
export type RawStruct = { | ||
readonly index: TermInt; | ||
readonly fields: TermList<PData>; | ||
}; | ||
export type TermStruct<SDef extends StructDefinition> = Term<PStruct<SDef>> & { | ||
readonly eqTerm: TermFn<[PStruct<SDef>], PBool>; | ||
readonly eq: (other: Term<PStruct<SDef>>) => TermBool; | ||
readonly raw: RawStruct; | ||
} & (IsSingleKey<SDef> extends true ? StructInstance<SDef[keyof SDef]> & { | ||
@@ -15,0 +23,0 @@ /** |
@@ -24,2 +24,4 @@ "use strict"; | ||
var IRVar_1 = require("../../../../IR/IRNodes/IRVar.js"); | ||
var TermInt_1 = require("./TermInt.js"); | ||
var TermList_1 = require("./TermList.js"); | ||
var getterOnly = { | ||
@@ -77,4 +79,11 @@ set: function () { }, | ||
ObjectUtils_1.default.defineReadOnlyProperty(struct, "eq", function (other) { return data_1.peqData.$(struct).$(other); }); | ||
var letted_unconstred = new Term_1.Term((0, type_system_1.pair)(type_system_1.int, (0, type_system_1.list)(type_system_1.data)), function (dbn) { return new IRLetted_1.IRLetted(Number(dbn), new IRApp_1.IRApp(IRNative_1.IRNative.unConstrData, struct.toIR(dbn))); }); | ||
var letted_ctorIdx = new Term_1.Term(type_system_1.int, function (dbn) { return new IRLetted_1.IRLetted(Number(dbn), new IRApp_1.IRApp(IRNative_1.IRNative.fstPair, letted_unconstred.toIR(dbn))); }); | ||
var letted_rawFields = new Term_1.Term((0, type_system_1.list)(type_system_1.data), function (dbn) { return new IRLetted_1.IRLetted(Number(dbn), new IRApp_1.IRApp(IRNative_1.IRNative.sndPair, letted_unconstred.toIR(dbn))); }); | ||
ObjectUtils_1.default.defineReadOnlyProperty(struct, "raw", Object.freeze({ | ||
index: (0, TermInt_1.addPIntMethods)(letted_ctorIdx), | ||
fields: (0, TermList_1.addPListMethods)(letted_rawFields) | ||
})); | ||
return struct; | ||
} | ||
exports.addPStructMethods = addPStructMethods; |
@@ -158,3 +158,5 @@ "use strict"; | ||
"eqTerm", | ||
"extract" | ||
"extract", | ||
"in", | ||
"raw" | ||
]); | ||
@@ -161,0 +163,0 @@ function pstruct(def) { |
import { ConstValue } from "../UPLCTerms/UPLCConst/ConstValue/index.js"; | ||
import { UPLCTerm, PureUPLCTerm } from "../UPLCTerm/index.js"; | ||
import { PureUPLCTerm } from "../UPLCTerm/index.js"; | ||
import { BitStream } from "../../../types/bits/BitStream/index.js"; | ||
@@ -20,15 +20,2 @@ import { ByteString } from "../../../types/HexString/ByteString.js"; | ||
export declare function serializeBuiltin(bn: Builtin): BitStream; | ||
/** | ||
* ### !! Important !! | ||
* | ||
* **_SIDE-EFFECT_**: modifies the input; in particular replaces | ||
* ```HoistedTerm```s with ```UPLCVar```s that are free in the term | ||
* | ||
* @param uplc **after this call is not guaranteed the term passed is closed** | ||
* | ||
* @returns {PureUPLCTerm} a term without HoistedUPLC, closed if the input was closed | ||
* | ||
* exported for only for testing | ||
*/ | ||
export declare function replaceHoistedTermsInplace(uplc: UPLCTerm): PureUPLCTerm; | ||
export declare class UPLCEncoder { | ||
@@ -35,0 +22,0 @@ private _ctx; |
@@ -6,3 +6,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.UPLCEncoder = exports.replaceHoistedTermsInplace = exports.serializeBuiltin = void 0; | ||
exports.UPLCEncoder = exports.serializeBuiltin = void 0; | ||
var JsRuntime_1 = __importDefault(require("../../../utils/JsRuntime/index.js")); | ||
@@ -14,3 +14,2 @@ var UPLCFlatUtils_1 = __importDefault(require("../../../utils/UPLCFlatUtils/index.js")); | ||
var UPLCTerm_1 = require("../UPLCTerm/index.js"); | ||
var HoistedUPLC_1 = require("../UPLCTerms/HoistedUPLC/index.js"); | ||
var BinaryString_1 = require("../../../types/bits/BinaryString.js"); | ||
@@ -148,87 +147,4 @@ var BitStream_1 = require("../../../types/bits/BitStream/index.js"); | ||
return new Builtin_1.Builtin(uplc.tag); | ||
if (uplc instanceof HoistedUPLC_1.HoistedUPLC) | ||
return new HoistedUPLC_1.HoistedUPLC(uplc.UPLC, undefined); | ||
throw new BasePlutsError_1.BasePlutsError("unknown UPLC in 'properlyCloneUPLC'"); | ||
} | ||
/** | ||
* ### !! Important !! | ||
* | ||
* **_SIDE-EFFECT_**: modifies the input; in particular replaces | ||
* ```HoistedTerm```s with ```UPLCVar```s that are free in the term | ||
* | ||
* @param uplc **after this call is not guaranteed the term passed is closed** | ||
* | ||
* @returns {PureUPLCTerm} a term without HoistedUPLC, closed if the input was closed | ||
* | ||
* exported for only for testing | ||
*/ | ||
function replaceHoistedTermsInplace(uplc) { | ||
/** | ||
* reference to the outermost term | ||
*/ | ||
var program = uplc; | ||
var sortedHoistedSet = (0, HoistedUPLC_1.getSortedHoistedSet)((0, UPLCTerm_1.getHoistedTerms)(uplc)); | ||
// adds the actual terms | ||
for (var i = sortedHoistedSet.length - 1; i >= 0; i--) { | ||
program = new Application_1.Application(new Lambda_1.Lambda(program), sortedHoistedSet[i].UPLC); | ||
} | ||
function getUPLCVarForHoistedAtLevel(_hoisted, level) { | ||
var levelOfTerm = sortedHoistedSet.findIndex(function (sortedH) { return BitStream_1.BitStream.eq(sortedH.compiled, _hoisted.compiled); }); | ||
return new UPLCVar_1.UPLCVar(level - (levelOfTerm + 1)); | ||
} | ||
/** | ||
* replaces HoistedUPLC instances with UPLCVar | ||
* (HoistedTerms with dependecies included) | ||
*/ | ||
function replaceWithUPLCVar(t, dbnLevel) { | ||
if (t instanceof UPLCVar_1.UPLCVar) | ||
return; | ||
if (t instanceof Delay_1.Delay) { | ||
if (t.delayedTerm instanceof HoistedUPLC_1.HoistedUPLC) | ||
t.delayedTerm = getUPLCVarForHoistedAtLevel(t.delayedTerm, dbnLevel); | ||
else | ||
replaceWithUPLCVar(t.delayedTerm, dbnLevel); | ||
return; | ||
} | ||
if (t instanceof Lambda_1.Lambda) { | ||
if (t.body instanceof HoistedUPLC_1.HoistedUPLC) | ||
t.body = getUPLCVarForHoistedAtLevel(t.body, dbnLevel + 1); | ||
else | ||
replaceWithUPLCVar(t.body, dbnLevel + 1); | ||
return; | ||
} | ||
if (t instanceof Application_1.Application) { | ||
if (t.argTerm instanceof HoistedUPLC_1.HoistedUPLC) | ||
t.argTerm = getUPLCVarForHoistedAtLevel(t.argTerm, dbnLevel); | ||
else | ||
replaceWithUPLCVar(t.argTerm, dbnLevel); | ||
if (t.funcTerm instanceof HoistedUPLC_1.HoistedUPLC) | ||
t.funcTerm = getUPLCVarForHoistedAtLevel(t.funcTerm, dbnLevel); | ||
else | ||
replaceWithUPLCVar(t.funcTerm, dbnLevel); | ||
return; | ||
} | ||
if (t instanceof UPLCConst_1.UPLCConst) | ||
return; | ||
if (t instanceof Force_1.Force) { | ||
if (t.termToForce instanceof HoistedUPLC_1.HoistedUPLC) | ||
t.termToForce = getUPLCVarForHoistedAtLevel(t.termToForce, dbnLevel); | ||
else | ||
replaceWithUPLCVar(t.termToForce, dbnLevel); | ||
return; | ||
} | ||
if (t instanceof ErrorUPLC_1.ErrorUPLC) | ||
return; | ||
if (t instanceof Builtin_1.Builtin) | ||
return; | ||
if (t instanceof HoistedUPLC_1.HoistedUPLC) { | ||
throw JsRuntime_1.default.makeNotSupposedToHappenError("'replaceWithUPLCVar', local funciton in 'replaceHoistedTermsInplace';" + | ||
"encountered an 'HoistedUPLC'; this was supposed to be replaced in the parent term case."); | ||
} | ||
throw JsRuntime_1.default.makeNotSupposedToHappenError("'replaceWithUPLCVar', local funciton in 'replaceHoistedTermsInplace'; did not match any 'UPLCTerm' constructor"); | ||
} | ||
replaceWithUPLCVar(program, 0); | ||
return program; | ||
} | ||
exports.replaceHoistedTermsInplace = replaceHoistedTermsInplace; | ||
var UPLCEncoder = /** @class */ (function () { | ||
@@ -245,10 +161,6 @@ function UPLCEncoder() { | ||
var uplc = program.body; | ||
var progrTerm = replaceHoistedTermsInplace( | ||
// HoistedUPLC relies on this clone | ||
// if this ever changes make sure that `HositeUPLC` is safe | ||
uplc.clone()); | ||
if (!(0, UPLCTerm_1.isPureUPLCTerm)(progrTerm)) { | ||
if (!(0, UPLCTerm_1.isPureUPLCTerm)(uplc)) { | ||
throw JsRuntime_1.default.makeNotSupposedToHappenError("'replaceHoisteTerm' did not returned a 'PureUPLCTerm'"); | ||
} | ||
result.append(this.encodeTerm(progrTerm)); | ||
result.append(this.encodeTerm(uplc)); | ||
UPLCFlatUtils_1.default.padToByte(result); | ||
@@ -255,0 +167,0 @@ return result; |
@@ -9,7 +9,6 @@ import { UPLCVar } from "../UPLCTerms/UPLCVar/index.js"; | ||
import { Builtin } from "../UPLCTerms/Builtin/index.js"; | ||
import { HoistedUPLC } from "../UPLCTerms/HoistedUPLC/index.js"; | ||
import { ConstType } from "../UPLCTerms/UPLCConst/ConstType/index.js"; | ||
import { ConstValue } from "../UPLCTerms/UPLCConst/ConstValue/index.js"; | ||
export type PureUPLCTerm = UPLCVar | Delay | Lambda | Application | UPLCConst | Force | ErrorUPLC | Builtin; | ||
export type UPLCTerm = PureUPLCTerm | HoistedUPLC; | ||
export type UPLCTerm = PureUPLCTerm; | ||
/** | ||
@@ -53,2 +52,1 @@ * **_O(1)_** | ||
export declare function getUPLCVarRefsInTerm(term: UPLCTerm, varDeBruijn?: number | bigint): number; | ||
export declare function getHoistedTerms(t: Readonly<UPLCTerm>): HoistedUPLC[]; |
"use strict"; | ||
var __read = (this && this.__read) || function (o, n) { | ||
var m = typeof Symbol === "function" && o[Symbol.iterator]; | ||
if (!m) return o; | ||
var i = m.call(o), r, ar = [], e; | ||
try { | ||
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); | ||
} | ||
catch (error) { e = { error: error }; } | ||
finally { | ||
try { | ||
if (r && !r.done && (m = i["return"])) m.call(i); | ||
} | ||
finally { if (e) throw e.error; } | ||
} | ||
return ar; | ||
}; | ||
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) { | ||
@@ -31,3 +6,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getHoistedTerms = exports.getUPLCVarRefsInTerm = exports.hasMultipleRefsInTerm = exports.hasAnyRefsInTerm = exports.prettyUPLC = exports.showUPLC = exports.showConstType = exports.showUPLCConstValue = exports.isClosedTerm = exports.isPureUPLCTerm = exports.isUPLCTerm = void 0; | ||
exports.getUPLCVarRefsInTerm = exports.hasMultipleRefsInTerm = exports.hasAnyRefsInTerm = exports.prettyUPLC = exports.showUPLC = exports.showConstType = exports.showUPLCConstValue = exports.isClosedTerm = exports.isPureUPLCTerm = exports.isUPLCTerm = void 0; | ||
var JsRuntime_1 = __importDefault(require("../../../utils/JsRuntime/index.js")); | ||
@@ -42,3 +17,2 @@ var UPLCVar_1 = require("../UPLCTerms/UPLCVar/index.js"); | ||
var Builtin_1 = require("../UPLCTerms/Builtin/index.js"); | ||
var HoistedUPLC_1 = require("../UPLCTerms/HoistedUPLC/index.js"); | ||
var ConstType_1 = require("../UPLCTerms/UPLCConst/ConstType/index.js"); | ||
@@ -51,3 +25,2 @@ var UPLCBuiltinTag_1 = require("../UPLCTerms/Builtin/UPLCBuiltinTag.js"); | ||
var Pair_1 = require("../../../types/structs/Pair/index.js"); | ||
var UPLCEncoder_1 = require("../UPLCEncoder/index.js"); | ||
/** | ||
@@ -68,4 +41,3 @@ * **_O(1)_** | ||
proto === ErrorUPLC_1.ErrorUPLC.prototype || | ||
proto === Builtin_1.Builtin.prototype || | ||
proto === HoistedUPLC_1.HoistedUPLC.prototype); | ||
proto === Builtin_1.Builtin.prototype); | ||
} | ||
@@ -97,4 +69,2 @@ exports.isUPLCTerm = isUPLCTerm; | ||
return true; | ||
if (t instanceof HoistedUPLC_1.HoistedUPLC) | ||
return false; | ||
return false; | ||
@@ -130,6 +100,2 @@ } | ||
return true; | ||
else if (t instanceof HoistedUPLC_1.HoistedUPLC) | ||
// in order to hoist a trem it has to be closed; | ||
// the condition is checked in the constructor (kinda mutually recursive). | ||
return true; | ||
else | ||
@@ -172,10 +138,10 @@ throw JsRuntime_1.default.makeNotSupposedToHappenError("unexpected execution flow in 'isClodeTerm'; all possibilieties should have already been handled; input term is: " + t.toString()); | ||
var vars = "abcdefghilmopqrstuvzwxyjkABCDEFGHILJMNOPQRSTUVZWXYJK".split(''); | ||
function getVarNameForDbn(dbn) { | ||
if (dbn < 0) | ||
return "(".concat(dbn, ")"); | ||
if (dbn < vars.length) | ||
return vars[dbn]; | ||
return vars[Math.floor(dbn / vars.length)] + getVarNameForDbn(dbn - vars.length); | ||
} | ||
function showUPLC(term) { | ||
function getVarNameForDbn(dbn) { | ||
if (dbn < 0) | ||
return "(".concat(dbn, ")"); | ||
if (dbn < vars.length) | ||
return vars[dbn]; | ||
return vars[Math.floor(dbn / vars.length)] + getVarNameForDbn(dbn - vars.length); | ||
} | ||
function loop(t, dbn) { | ||
@@ -202,7 +168,5 @@ if (t instanceof UPLCVar_1.UPLCVar) { | ||
} | ||
if (t instanceof HoistedUPLC_1.HoistedUPLC) | ||
return loop(t.UPLC, dbn); | ||
return ""; | ||
} | ||
return loop((0, UPLCEncoder_1.replaceHoistedTermsInplace)(term.clone()), 0); | ||
return loop(term, 0); | ||
} | ||
@@ -244,7 +208,5 @@ exports.showUPLC = showUPLC; | ||
} | ||
if (t instanceof HoistedUPLC_1.HoistedUPLC) | ||
return loop(t.UPLC, dbn, depth); | ||
return ""; | ||
} | ||
return loop((0, UPLCEncoder_1.replaceHoistedTermsInplace)(term.clone()), 0, 0); | ||
return loop(term, 0, 0); | ||
} | ||
@@ -277,5 +239,2 @@ exports.prettyUPLC = prettyUPLC; | ||
return false; | ||
// hoisted terms are closed, ence do not have references to external variables for sure | ||
if (t instanceof HoistedUPLC_1.HoistedUPLC) | ||
return false; | ||
throw JsRuntime_1.default.makeNotSupposedToHappenError("'hasAnyRefsInTerm' did not matched any possible 'UPLCTerm' constructor"); | ||
@@ -312,6 +271,2 @@ } | ||
return false; | ||
// hoisted terms are closed, ence do not have references to external variables for sure | ||
if (t instanceof HoistedUPLC_1.HoistedUPLC) | ||
return false; | ||
; | ||
throw JsRuntime_1.default.makeNotSupposedToHappenError("getUPLCVarRefsInTerm did not matched any possible 'UPLCTerm' constructor"); | ||
@@ -346,5 +301,2 @@ } | ||
return countedUntilNow; | ||
// hoisted terms are closed, ence do not have references to external variables for sure | ||
if (t instanceof HoistedUPLC_1.HoistedUPLC) | ||
return countedUntilNow; | ||
throw JsRuntime_1.default.makeNotSupposedToHappenError("getUPLCVarRefsInTerm did not matched any possible 'UPLCTerm' constructor"); | ||
@@ -355,114 +307,1 @@ } | ||
exports.getUPLCVarRefsInTerm = getUPLCVarRefsInTerm; | ||
function getHoistedTerms(t) { | ||
if (!isUPLCTerm(t)) | ||
return []; | ||
/* | ||
```Application``` adds sub terms dependecies | ||
```HoistedUPLC``` adds itself and it's own dependecies if any | ||
*/ | ||
if (t instanceof UPLCVar_1.UPLCVar) | ||
return []; | ||
if (t instanceof Delay_1.Delay) | ||
return getHoistedTerms(t.delayedTerm); | ||
if (t instanceof Lambda_1.Lambda) | ||
return getHoistedTerms(t.body); | ||
if (t instanceof Application_1.Application) | ||
return __spreadArray(__spreadArray([], __read(getHoistedTerms(t.argTerm)), false), __read(getHoistedTerms(t.funcTerm)), false); | ||
if (t instanceof UPLCConst_1.UPLCConst) | ||
return []; | ||
if (t instanceof Force_1.Force) | ||
return getHoistedTerms(t.termToForce); | ||
if (t instanceof ErrorUPLC_1.ErrorUPLC) | ||
return []; | ||
if (t instanceof Builtin_1.Builtin) | ||
return []; | ||
if (t instanceof HoistedUPLC_1.HoistedUPLC) | ||
return __spreadArray(__spreadArray([], __read(t.dependencies.map(function (dep) { return dep.clone(); })), false), [t.clone()], false); | ||
return []; | ||
} | ||
exports.getHoistedTerms = getHoistedTerms; | ||
/* experimental: getHoistedTermsAndRefs | ||
type HoistedRef = { | ||
compiled: BitStream, | ||
number: number | ||
}; | ||
type HoistedRefs = HoistedRef[] | ||
function mergeRefs( a: HoistedRefs, b: HoistedRefs ): HoistedRefs | ||
{ | ||
const aCompiled = a.map( ref => ref.compiled ); | ||
const bCompiled = b.map( ref => ref.compiled ); | ||
const result: HoistedRefs = a; | ||
for( const bComp of bCompiled ) | ||
{ | ||
if( aCompiled.some( aComp => BitStream.eq( aComp, bComp ) ) ) | ||
{ | ||
// b hoisted already present between a's ones | ||
const idx = result.findIndex( href => BitStream.eq( href.compiled, bComp ) ) | ||
// add number to exsisting ref | ||
result[ idx ] = { | ||
compiled: result[ idx ].compiled, | ||
number: result[ idx ].number + | ||
( b.find( bRef => BitStream.eq( bRef.compiled, bComp ) )?.number ?? 0 ) | ||
} | ||
} | ||
else // hoisted not present in the a refs | ||
{ | ||
// add new entry from b; | ||
result.push({ | ||
compiled: bComp.clone(), | ||
number: b.find( bRef => BitStream.eq( bRef.compiled, bComp ) )?.number ?? 0 | ||
}) | ||
} | ||
} | ||
return result; | ||
} | ||
just like ```getHoistedTerms``` but returns also the number of references per hoisted term found | ||
@fixme ```HoistedUPLC``` currently "hides" the number of refernces of its dependecies | ||
export function getHoistedTermsAndRefs( t: UPLCTerm ) | ||
: { | ||
terms: HoistedUPLC[], | ||
refs: HoistedRefs | ||
} | ||
{ | ||
const empty: { | ||
terms: HoistedUPLC[], | ||
refs: HoistedRefs | ||
} = { | ||
terms: [], | ||
refs: [] | ||
}; | ||
if( !isUPLCTerm( t ) ) return empty; | ||
if( t instanceof UPLCVar ) | ||
return empty; | ||
if( t instanceof Delay ) return getHoistedTermsAndRefs( t.delayedTerm ); | ||
if( t instanceof Lambda ) return getHoistedTermsAndRefs( t.body ); | ||
if( t instanceof Application ) | ||
{ | ||
const argResult = getHoistedTermsAndRefs( t.argTerm ) ; | ||
const funcResult = getHoistedTermsAndRefs( t.funcTerm ); | ||
return { | ||
terms: [ ...argResult.terms , ...funcResult.terms ], | ||
refs: mergeRefs( argResult.refs, funcResult.refs ) | ||
}; | ||
} | ||
if( t instanceof UPLCConst ) return empty; | ||
if( t instanceof Force ) return getHoistedTermsAndRefs( t.termToForce ); | ||
if( t instanceof ErrorUPLC ) return empty; | ||
if( t instanceof Builtin ) return empty; | ||
if( t instanceof HoistedUPLC ) return [ t, ...t.dependencies ]; | ||
return empty; | ||
} | ||
// experimental: getHoistedTermsAndRefs */ |
import { CborObj } from "../../../cbor/CborObj/index.js"; | ||
import { CborString } from "../../../cbor/CborString/index.js"; | ||
import { Data } from "../Data.js"; | ||
import { Term } from "../../../onchain/pluts/Term/index.js"; | ||
import { PData } from "../../../onchain/pluts/PTypes/PData/PData.js"; | ||
import { PStruct } from "../../../onchain/pluts/PTypes/PStruct/pstruct.js"; | ||
export type CanBeData = Data | Term<PData> | Term<PStruct<any>> | CborObj | CborString; | ||
import { ToUPLC } from "../../../onchain/UPLC/interfaces/ToUPLC.js"; | ||
export type CanBeData = Data | ToUPLC | CborObj | CborString | string; | ||
export declare function cloneCanBeData(stuff: CanBeData): CanBeData; | ||
export declare function canBeData(something: any): something is CanBeData; | ||
export declare function forceData(data: CanBeData): Data; |
@@ -6,3 +6,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.forceData = exports.canBeData = void 0; | ||
exports.forceData = exports.canBeData = exports.cloneCanBeData = void 0; | ||
var JsRuntime_1 = __importDefault(require("../../../utils/JsRuntime/index.js")); | ||
@@ -15,12 +15,33 @@ var CborObj_1 = require("../../../cbor/CborObj/index.js"); | ||
var UPLCConst_1 = require("../../../onchain/UPLC/UPLCTerms/UPLCConst/index.js"); | ||
var Term_1 = require("../../../onchain/pluts/Term/index.js"); | ||
var fromCbor_1 = require("../fromCbor.js"); | ||
var types_1 = require("../../../onchain/pluts/type_system/types.js"); | ||
var typeExtends_1 = require("../../../onchain/pluts/type_system/typeExtends.js"); | ||
var ObjectUtils_1 = __importDefault(require("../../../utils/ObjectUtils/index.js")); | ||
var HexString_1 = require("../../HexString/index.js"); | ||
function cloneCanBeData(stuff) { | ||
if (typeof stuff === "string") | ||
return stuff; | ||
if (stuff instanceof CborString_1.CborString || | ||
(0, CborObj_1.isCborObj)(stuff) || | ||
(0, Data_1.isData)(stuff)) | ||
return stuff.clone(); | ||
var result = Machine_1.Machine.evalSimple(stuff.toUPLC()); | ||
if (!(result instanceof UPLCConst_1.UPLCConst)) { | ||
throw new BasePlutsError_1.BasePlutsError("`CanBeData` object that implements `ToUPLC` did not evaluated to a constant"); | ||
} | ||
var value = result.value; | ||
if (!(0, Data_1.isData)(value)) { | ||
throw new BasePlutsError_1.BasePlutsError("`CanBeData` object that implements `ToUPLC` evaluated to a constant with a non-Data value"); | ||
} | ||
return value; | ||
} | ||
exports.cloneCanBeData = cloneCanBeData; | ||
function canBeData(something) { | ||
if (typeof something === "string" && | ||
(0, HexString_1.isHex)(something)) | ||
return true; | ||
if (typeof something !== "object") | ||
return false; | ||
return ((0, Data_1.isData)(something) || | ||
(something instanceof Term_1.Term && | ||
(0, typeExtends_1.typeExtends)(something.type, types_1.data)) || | ||
(typeof something === "object" && | ||
ObjectUtils_1.default.hasOwn(something, "toUPLC") && | ||
typeof something.toUPLC === "function") || | ||
something instanceof CborString_1.CborString || | ||
@@ -30,12 +51,12 @@ (0, CborObj_1.isCborObj)(something)); | ||
exports.canBeData = canBeData; | ||
var data_t = types_1.data; | ||
function forceData(data) { | ||
if (typeof data === "string") | ||
data = (0, fromCbor_1.dataFromCbor)(data); | ||
if ((0, Data_1.isData)(data)) { | ||
return data; | ||
} | ||
if (data instanceof Term_1.Term) { | ||
if (!(0, typeExtends_1.typeExtends)(data.type, data_t)) { | ||
throw new BasePlutsError_1.BasePlutsError("datum was a term of a type that doesn't extends 'data'"); | ||
} | ||
var uplcData = Machine_1.Machine.evalSimple(data); | ||
if (typeof data === "object" && | ||
ObjectUtils_1.default.hasOwn(data, "toUPLC") && | ||
typeof data.toUPLC === "function") { | ||
var uplcData = Machine_1.Machine.evalSimple(data.toUPLC()); | ||
if (!(uplcData instanceof UPLCConst_1.UPLCConst)) { | ||
@@ -42,0 +63,0 @@ throw new BasePlutsError_1.BasePlutsError("term passed as 'datum' field evaluated to an error"); |
@@ -11,2 +11,3 @@ export * from "./Data.js"; | ||
export * from "./hashData.js"; | ||
export * from "./CanBeData/index.js"; | ||
export * from "./toData/interface.js"; |
@@ -27,2 +27,3 @@ "use strict"; | ||
__exportStar(require("./hashData.js"), exports); | ||
__exportStar(require("./CanBeData/index.js"), exports); | ||
__exportStar(require("./toData/interface.js"), exports); |
{ | ||
"name": "@harmoniclabs/plu-ts", | ||
"version": "0.3.0-dev1", | ||
"version": "0.3.0-dev10", | ||
"description": "An embedded DSL for Cardano smart contracts creation coupled with a library for Cardano transactions, all in Typescript", | ||
@@ -19,5 +19,6 @@ "main": "./dist/index.js", | ||
"test-coverage": "jest --coverage", | ||
"build": "tsc --project ./tsconfig.json && tsc-alias -p ./tsconfig.json", | ||
"build": "rm -rf ./dist && tsc --project ./tsconfig.json && tsc-alias -p ./tsconfig.json", | ||
"build:light": "tsc --project ./tsconfig.json && tsc-alias -p ./tsconfig.json", | ||
"buidl": "npm run build", | ||
"prerelease": "npm run test && npm run build", | ||
"ci": "npm run test && npm run build", | ||
"start": "npm-run-all --parallel build:watch run:watch" | ||
@@ -24,0 +25,0 @@ }, |
Sorry, the diff of this file is too big to display
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
2112676
43540
905