(self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push([[514],{ /***/ 8161: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { const elliptic = __webpack_require__(6266); const BN = __webpack_require__(3783); const { sha256 } = __webpack_require__(2023); const { sha512 } = __webpack_require__(3434); const EC = new elliptic.ec('secp256k1'); function toBytesInt32(num) { return new Uint8Array([ (num & 0xff000000) >> 24, (num & 0x00ff0000) >> 16, (num & 0x0000ff00) >> 8, num & 0x000000ff, ]); } const one = new BN(1); function Unmarshal(data) { const byteLen = (EC.n.bitLength() + 7) >> 3; EC.g.mul(10); if ((data[0] & ~1) != 2) { return [null, null]; } if (data.length != 1 + byteLen) return [null, null]; const tx = new BN(data.slice(1, 1 + byteLen)); try { const p = EC.curve.pointFromX(tx); return [p.x, p.y]; } catch (e) { return [null, null]; } } /** * @param {number[] | Uint8Array} m data * @returns {elliptic.curve.base.BasePoint} point */ function H1(m) { let x = null, y = null; const byteLen = (EC.n.bitLength() + 7) >> 3; let i = 0; while (x == null && i < 100) { const res = sha512.array(new Uint8Array([...toBytesInt32(i), ...m])); const r = [2, ...res]; [x, y] = Unmarshal(r.slice(0, byteLen + 1)); i++; } return EC.curve.point(x, y); } /** * @param {number[] | Uint8Array} m data * @returns {BN} BN */ function H2(m) { const byteLen = (EC.n.bitLength() + 7) >> 3; let i = 0; while (true) { const res = sha512.array(new Uint8Array([...toBytesInt32(i), ...m])); const k = new BN(res.slice(0, byteLen)); if (k.cmp(EC.curve.n.sub(one)) == -1) { return k.add(one); } i++; } } /** * @param {number[] | Uint8Array} privateKey private key * @param {number[] | Uint8Array} m data * @returns {[Uint8Array, Uint8Array]} index, proof */ function Evaluate(privateKey, m) { const currentKey = EC.keyFromPrivate(privateKey); const r = EC.genKeyPair(); const rBN = r.getPrivate(); // H = H1(m) const pointH = H1(m); // VRF_k(m) = [k]H const point = pointH.mul(privateKey); // vrf 65 bytes const vrf = point.encode(); const rgPoint = EC.curve.g.mul(rBN); const rhPoint = pointH.mul(rBN); const b = [ ...EC.curve.g.encode(), ...pointH.encode(), ...currentKey.getPublic().encode(), ...vrf, ...rgPoint.encode(), ...rhPoint.encode(), ]; const s = H2(b); const t = rBN.sub(s.mul(currentKey.getPrivate())).umod(EC.curve.n); const index = sha256.array(new Uint8Array(vrf)); const buf = [ ...new Array(32 - s.byteLength()).fill(0), ...s.toArray(), ...new Array(32 - t.byteLength()).fill(0), ...t.toArray(), ...vrf, ]; return [index, buf]; } /** * @param {number[] | Uint8Array} publicKey public key * @param {number[] | Uint8Array} data data * @param {number[] | Uint8Array} proof VRF proof * @returns {Uint8Array} index * @throws Will throw if VRF proof is invalid */ function ProofHoHash(publicKey, data, proof) { const currentKey = EC.keyFromPublic(publicKey); if (proof.length !== 64 + 65) { throw new Error('invalid vrf'); } const s = proof.slice(0, 32); const t = proof.slice(32, 64); const vrf = proof.slice(64, 64 + 65); const uhPoint = decodePoint(vrf); if (!uhPoint) { throw new Error('invalid vrf'); } // [t]G + [s]([k]G) = [t+ks]G const tgPoint = EC.curve.g.mul(t); const ksgPoint = currentKey.getPublic().mul(s); const tksgPoint = tgPoint.add(ksgPoint); // H = H1(m) // [t]H + [s]VRF = [t+ks]H const hPoint = H1(data); const thPoint = hPoint.mul(t); const shPoint = uhPoint.mul(s); const tkshPoint = thPoint.add(shPoint); const b = [ ...EC.curve.g.encode(), ...hPoint.encode(), ...currentKey.getPublic().encode(), ...vrf, ...tksgPoint.encode(), ...tkshPoint.encode(), ]; const h2 = H2(b); const buf = [...new Array(32 - h2.byteLength()).fill(0), ...h2.toArray()]; let equal = true; for (let i = 0; i < buf.length; i++) { if (s[i] !== buf[i]) { equal = false; } } if (!equal) { throw new Error('invalid vrf'); } return sha256.array(new Uint8Array(vrf)); } /** * @param {number[] | Uint8Array} data point data * @returns {elliptic.curve.base.BasePoint} point */ function decodePoint(data) { try { return EC.curve.decodePoint(data); } catch { return null; } } module.exports = { Evaluate, ProofHoHash, }; /***/ }), /***/ 3783: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /* module decorator */ module = __webpack_require__.nmd(module); (function (module, exports) { 'use strict'; // Utils function assert (val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } // Could use `inherits` module, but don't want to move from single file // architecture yet. function inherits (ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } // BN function BN (number, base, endian) { if (BN.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; // Reduction context this.red = null; if (number !== null) { if (base === 'le' || base === 'be') { endian = base; base = 10; } this._init(number || 0, base || 10, endian || 'be'); } } if (typeof module === 'object') { module.exports = BN; } else { exports.BN = BN; } BN.BN = BN; BN.wordSize = 26; var Buffer; try { if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { Buffer = window.Buffer; } else { Buffer = (__webpack_require__(136).Buffer); } } catch (e) { } BN.isBN = function isBN (num) { if (num instanceof BN) { return true; } return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; BN.max = function max (left, right) { if (left.cmp(right) > 0) return left; return right; }; BN.min = function min (left, right) { if (left.cmp(right) < 0) return left; return right; }; BN.prototype._init = function init (number, base, endian) { if (typeof number === 'number') { return this._initNumber(number, base, endian); } if (typeof number === 'object') { return this._initArray(number, base, endian); } if (base === 'hex') { base = 16; } assert(base === (base | 0) && base >= 2 && base <= 36); number = number.toString().replace(/\s+/g, ''); var start = 0; if (number[0] === '-') { start++; this.negative = 1; } if (start < number.length) { if (base === 16) { this._parseHex(number, start, endian); } else { this._parseBase(number, base, start); if (endian === 'le') { this._initArray(this.toArray(), base, endian); } } } }; BN.prototype._initNumber = function _initNumber (number, base, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 0x4000000) { this.words = [number & 0x3ffffff]; this.length = 1; } else if (number < 0x10000000000000) { this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff ]; this.length = 2; } else { assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff, 1 ]; this.length = 3; } if (endian !== 'le') return; // Reverse the bytes this._initArray(this.toArray(), base, endian); }; BN.prototype._initArray = function _initArray (number, base, endian) { // Perhaps a Uint8Array assert(typeof number.length === 'number'); if (number.length <= 0) { this.words = [0]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; var off = 0; if (endian === 'be') { for (i = number.length - 1, j = 0; i >= 0; i -= 3) { w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } else if (endian === 'le') { for (i = 0, j = 0; i < number.length; i += 3) { w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } return this._strip(); }; function parseHex4Bits (string, index) { var c = string.charCodeAt(index); // '0' - '9' if (c >= 48 && c <= 57) { return c - 48; // 'A' - 'F' } else if (c >= 65 && c <= 70) { return c - 55; // 'a' - 'f' } else if (c >= 97 && c <= 102) { return c - 87; } else { assert(false, 'Invalid character in ' + string); } } function parseHexByte (string, lowerBound, index) { var r = parseHex4Bits(string, index); if (index - 1 >= lowerBound) { r |= parseHex4Bits(string, index - 1) << 4; } return r; } BN.prototype._parseHex = function _parseHex (number, start, endian) { // Create possibly bigger array to ensure that it fits the number this.length = Math.ceil((number.length - start) / 6); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } // 24-bits chunks var off = 0; var j = 0; var w; if (endian === 'be') { for (i = number.length - 1; i >= start; i -= 2) { w = parseHexByte(number, start, i) << off; this.words[j] |= w & 0x3ffffff; if (off >= 18) { off -= 18; j += 1; this.words[j] |= w >>> 26; } else { off += 8; } } } else { var parseLength = number.length - start; for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { w = parseHexByte(number, start, i) << off; this.words[j] |= w & 0x3ffffff; if (off >= 18) { off -= 18; j += 1; this.words[j] |= w >>> 26; } else { off += 8; } } } this._strip(); }; function parseBase (str, start, end, mul) { var r = 0; var b = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r *= mul; // 'a' if (c >= 49) { b = c - 49 + 0xa; // 'A' } else if (c >= 17) { b = c - 17 + 0xa; // '0' - '9' } else { b = c; } assert(c >= 0 && b < mul, 'Invalid character'); r += b; } return r; } BN.prototype._parseBase = function _parseBase (number, base, start) { // Initialize as zero this.words = [0]; this.length = 1; // Find length of limb in base for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { limbLen++; } limbLen--; limbPow = (limbPow / base) | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i = start; i < end; i += limbLen) { word = parseBase(number, i, i + limbLen, base); this.imuln(limbPow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i, number.length, base); for (i = 0; i < mod; i++) { pow *= base; } this.imuln(pow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } this._strip(); }; BN.prototype.copy = function copy (dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { dest.words[i] = this.words[i]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; function move (dest, src) { dest.words = src.words; dest.length = src.length; dest.negative = src.negative; dest.red = src.red; } BN.prototype._move = function _move (dest) { move(dest, this); }; BN.prototype.clone = function clone () { var r = new BN(null); this.copy(r); return r; }; BN.prototype._expand = function _expand (size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; // Remove leading `0` from `this` BN.prototype._strip = function strip () { while (this.length > 1 && this.words[this.length - 1] === 0) { this.length--; } return this._normSign(); }; BN.prototype._normSign = function _normSign () { // -0 = 0 if (this.length === 1 && this.words[0] === 0) { this.negative = 0; } return this; }; // Check Symbol.for because not everywhere where Symbol defined // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') { try { BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect; } catch (e) { BN.prototype.inspect = inspect; } } else { BN.prototype.inspect = inspect; } function inspect () { return (this.red ? ''; } /* var zeros = []; var groupSizes = []; var groupBases = []; var s = ''; var i = -1; while (++i < BN.wordSize) { zeros[i] = s; s += '0'; } groupSizes[0] = 0; groupSizes[1] = 0; groupBases[0] = 0; groupBases[1] = 0; var base = 2 - 1; while (++base < 36 + 1) { var groupSize = 0; var groupBase = 1; while (groupBase < (1 << BN.wordSize) / base) { groupBase *= base; groupSize += 1; } groupSizes[base] = groupSize; groupBases[base] = groupBase; } */ var zeros = [ '', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000' ]; var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]; var groupBases = [ 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 ]; BN.prototype.toString = function toString (base, padding) { base = base || 10; padding = padding | 0 || 1; var out; if (base === 16 || base === 'hex') { out = ''; var off = 0; var carry = 0; for (var i = 0; i < this.length; i++) { var w = this.words[i]; var word = (((w << off) | carry) & 0xffffff).toString(16); carry = (w >>> (24 - off)) & 0xffffff; off += 2; if (off >= 26) { off -= 26; i--; } if (carry !== 0 || i !== this.length - 1) { out = zeros[6 - word.length] + word + out; } else { out = word + out; } } if (carry !== 0) { out = carry.toString(16) + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } if (base === (base | 0) && base >= 2 && base <= 36) { // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); var groupBase = groupBases[base]; out = ''; var c = this.clone(); c.negative = 0; while (!c.isZero()) { var r = c.modrn(groupBase).toString(base); c = c.idivn(groupBase); if (!c.isZero()) { out = zeros[groupSize - r.length] + r + out; } else { out = r + out; } } if (this.isZero()) { out = '0' + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } assert(false, 'Base should be between 2 and 36'); }; BN.prototype.toNumber = function toNumber () { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 0x4000000; } else if (this.length === 3 && this.words[2] === 0x01) { // NOTE: at this stage it is known that the top bit is set ret += 0x10000000000000 + (this.words[1] * 0x4000000); } else if (this.length > 2) { assert(false, 'Number can only safely store up to 53 bits'); } return (this.negative !== 0) ? -ret : ret; }; BN.prototype.toJSON = function toJSON () { return this.toString(16, 2); }; if (Buffer) { BN.prototype.toBuffer = function toBuffer (endian, length) { return this.toArrayLike(Buffer, endian, length); }; } BN.prototype.toArray = function toArray (endian, length) { return this.toArrayLike(Array, endian, length); }; var allocate = function allocate (ArrayType, size) { if (ArrayType.allocUnsafe) { return ArrayType.allocUnsafe(size); } return new ArrayType(size); }; BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { this._strip(); var byteLength = this.byteLength(); var reqLength = length || Math.max(1, byteLength); assert(byteLength <= reqLength, 'byte array longer than desired length'); assert(reqLength > 0, 'Requested array length <= 0'); var res = allocate(ArrayType, reqLength); var postfix = endian === 'le' ? 'LE' : 'BE'; this['_toArrayLike' + postfix](res, byteLength); return res; }; BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) { var position = 0; var carry = 0; for (var i = 0, shift = 0; i < this.length; i++) { var word = (this.words[i] << shift) | carry; res[position++] = word & 0xff; if (position < res.length) { res[position++] = (word >> 8) & 0xff; } if (position < res.length) { res[position++] = (word >> 16) & 0xff; } if (shift === 6) { if (position < res.length) { res[position++] = (word >> 24) & 0xff; } carry = 0; shift = 0; } else { carry = word >>> 24; shift += 2; } } if (position < res.length) { res[position++] = carry; while (position < res.length) { res[position++] = 0; } } }; BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) { var position = res.length - 1; var carry = 0; for (var i = 0, shift = 0; i < this.length; i++) { var word = (this.words[i] << shift) | carry; res[position--] = word & 0xff; if (position >= 0) { res[position--] = (word >> 8) & 0xff; } if (position >= 0) { res[position--] = (word >> 16) & 0xff; } if (shift === 6) { if (position >= 0) { res[position--] = (word >> 24) & 0xff; } carry = 0; shift = 0; } else { carry = word >>> 24; shift += 2; } } if (position >= 0) { res[position--] = carry; while (position >= 0) { res[position--] = 0; } } }; if (Math.clz32) { BN.prototype._countBits = function _countBits (w) { return 32 - Math.clz32(w); }; } else { BN.prototype._countBits = function _countBits (w) { var t = w; var r = 0; if (t >= 0x1000) { r += 13; t >>>= 13; } if (t >= 0x40) { r += 7; t >>>= 7; } if (t >= 0x8) { r += 4; t >>>= 4; } if (t >= 0x02) { r += 2; t >>>= 2; } return r + t; }; } BN.prototype._zeroBits = function _zeroBits (w) { // Short-cut if (w === 0) return 26; var t = w; var r = 0; if ((t & 0x1fff) === 0) { r += 13; t >>>= 13; } if ((t & 0x7f) === 0) { r += 7; t >>>= 7; } if ((t & 0xf) === 0) { r += 4; t >>>= 4; } if ((t & 0x3) === 0) { r += 2; t >>>= 2; } if ((t & 0x1) === 0) { r++; } return r; }; // Return number of used bits in a BN BN.prototype.bitLength = function bitLength () { var w = this.words[this.length - 1]; var hi = this._countBits(w); return (this.length - 1) * 26 + hi; }; function toBitArray (num) { var w = new Array(num.bitLength()); for (var bit = 0; bit < w.length; bit++) { var off = (bit / 26) | 0; var wbit = bit % 26; w[bit] = (num.words[off] >>> wbit) & 0x01; } return w; } // Number of trailing zero bits BN.prototype.zeroBits = function zeroBits () { if (this.isZero()) return 0; var r = 0; for (var i = 0; i < this.length; i++) { var b = this._zeroBits(this.words[i]); r += b; if (b !== 26) break; } return r; }; BN.prototype.byteLength = function byteLength () { return Math.ceil(this.bitLength() / 8); }; BN.prototype.toTwos = function toTwos (width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN.prototype.fromTwos = function fromTwos (width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN.prototype.isNeg = function isNeg () { return this.negative !== 0; }; // Return negative clone of `this` BN.prototype.neg = function neg () { return this.clone().ineg(); }; BN.prototype.ineg = function ineg () { if (!this.isZero()) { this.negative ^= 1; } return this; }; // Or `num` with `this` in-place BN.prototype.iuor = function iuor (num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i = 0; i < num.length; i++) { this.words[i] = this.words[i] | num.words[i]; } return this._strip(); }; BN.prototype.ior = function ior (num) { assert((this.negative | num.negative) === 0); return this.iuor(num); }; // Or `num` with `this` BN.prototype.or = function or (num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN.prototype.uor = function uor (num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; // And `num` with `this` in-place BN.prototype.iuand = function iuand (num) { // b = min-length(num, this) var b; if (this.length > num.length) { b = num; } else { b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = this.words[i] & num.words[i]; } this.length = b.length; return this._strip(); }; BN.prototype.iand = function iand (num) { assert((this.negative | num.negative) === 0); return this.iuand(num); }; // And `num` with `this` BN.prototype.and = function and (num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN.prototype.uand = function uand (num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; // Xor `num` with `this` in-place BN.prototype.iuxor = function iuxor (num) { // a.length > b.length var a; var b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = a.words[i] ^ b.words[i]; } if (this !== a) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = a.length; return this._strip(); }; BN.prototype.ixor = function ixor (num) { assert((this.negative | num.negative) === 0); return this.iuxor(num); }; // Xor `num` with `this` BN.prototype.xor = function xor (num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN.prototype.uxor = function uxor (num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; // Not ``this`` with ``width`` bitwidth BN.prototype.inotn = function inotn (width) { assert(typeof width === 'number' && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; // Extend the buffer with leading zeroes this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } // Handle complete words for (var i = 0; i < bytesNeeded; i++) { this.words[i] = ~this.words[i] & 0x3ffffff; } // Handle the residue if (bitsLeft > 0) { this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); } // And remove leading zeroes return this._strip(); }; BN.prototype.notn = function notn (width) { return this.clone().inotn(width); }; // Set `bit` of `this` BN.prototype.setn = function setn (bit, val) { assert(typeof bit === 'number' && bit >= 0); var off = (bit / 26) | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | (1 << wbit); } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this._strip(); }; // Add `num` to `this` in-place BN.prototype.iadd = function iadd (num) { var r; // negative + positive if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r = this.isub(num); this.negative ^= 1; return this._normSign(); // positive + negative } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r = this.isub(num); num.negative = 1; return r._normSign(); } // a.length > b.length var a, b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) + (b.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } this.length = a.length; if (carry !== 0) { this.words[this.length] = carry; this.length++; // Copy the rest of the words } else if (a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } return this; }; // Add `num` to `this` BN.prototype.add = function add (num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; // Subtract `num` from `this` in-place BN.prototype.isub = function isub (num) { // this - (-num) = this + num if (num.negative !== 0) { num.negative = 0; var r = this.iadd(num); num.negative = 1; return r._normSign(); // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } // At this point both numbers are positive var cmp = this.cmp(num); // Optimization - zeroify if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } // a > b var a, b; if (cmp > 0) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) - (b.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } // Copy rest of the words if (carry === 0 && i < a.length && a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = Math.max(this.length, i); if (a !== this) { this.negative = 1; } return this._strip(); }; // Subtract `num` from `this` BN.prototype.sub = function sub (num) { return this.clone().isub(num); }; function smallMulTo (self, num, out) { out.negative = num.negative ^ self.negative; var len = (self.length + num.length) | 0; out.length = len; len = (len - 1) | 0; // Peel one iteration (compiler can't do it, because of code complexity) var a = self.words[0] | 0; var b = num.words[0] | 0; var r = a * b; var lo = r & 0x3ffffff; var carry = (r / 0x4000000) | 0; out.words[0] = lo; for (var k = 1; k < len; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = carry >>> 26; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = (k - j) | 0; a = self.words[i] | 0; b = num.words[j] | 0; r = a * b + rword; ncarry += (r / 0x4000000) | 0; rword = r & 0x3ffffff; } out.words[k] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k] = carry | 0; } else { out.length--; } return out._strip(); } // TODO(indutny): it may be reasonable to omit it for users who don't need // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit // multiplication (like elliptic secp256k1). var comb10MulTo = function comb10MulTo (self, num, out) { var a = self.words; var b = num.words; var o = out.words; var c = 0; var lo; var mid; var hi; var a0 = a[0] | 0; var al0 = a0 & 0x1fff; var ah0 = a0 >>> 13; var a1 = a[1] | 0; var al1 = a1 & 0x1fff; var ah1 = a1 >>> 13; var a2 = a[2] | 0; var al2 = a2 & 0x1fff; var ah2 = a2 >>> 13; var a3 = a[3] | 0; var al3 = a3 & 0x1fff; var ah3 = a3 >>> 13; var a4 = a[4] | 0; var al4 = a4 & 0x1fff; var ah4 = a4 >>> 13; var a5 = a[5] | 0; var al5 = a5 & 0x1fff; var ah5 = a5 >>> 13; var a6 = a[6] | 0; var al6 = a6 & 0x1fff; var ah6 = a6 >>> 13; var a7 = a[7] | 0; var al7 = a7 & 0x1fff; var ah7 = a7 >>> 13; var a8 = a[8] | 0; var al8 = a8 & 0x1fff; var ah8 = a8 >>> 13; var a9 = a[9] | 0; var al9 = a9 & 0x1fff; var ah9 = a9 >>> 13; var b0 = b[0] | 0; var bl0 = b0 & 0x1fff; var bh0 = b0 >>> 13; var b1 = b[1] | 0; var bl1 = b1 & 0x1fff; var bh1 = b1 >>> 13; var b2 = b[2] | 0; var bl2 = b2 & 0x1fff; var bh2 = b2 >>> 13; var b3 = b[3] | 0; var bl3 = b3 & 0x1fff; var bh3 = b3 >>> 13; var b4 = b[4] | 0; var bl4 = b4 & 0x1fff; var bh4 = b4 >>> 13; var b5 = b[5] | 0; var bl5 = b5 & 0x1fff; var bh5 = b5 >>> 13; var b6 = b[6] | 0; var bl6 = b6 & 0x1fff; var bh6 = b6 >>> 13; var b7 = b[7] | 0; var bl7 = b7 & 0x1fff; var bh7 = b7 >>> 13; var b8 = b[8] | 0; var bl8 = b8 & 0x1fff; var bh8 = b8 >>> 13; var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ lo = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = (mid + Math.imul(ah0, bl0)) | 0; hi = Math.imul(ah0, bh0); var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; w0 &= 0x3ffffff; /* k = 1 */ lo = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = (mid + Math.imul(ah1, bl0)) | 0; hi = Math.imul(ah1, bh0); lo = (lo + Math.imul(al0, bl1)) | 0; mid = (mid + Math.imul(al0, bh1)) | 0; mid = (mid + Math.imul(ah0, bl1)) | 0; hi = (hi + Math.imul(ah0, bh1)) | 0; var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; w1 &= 0x3ffffff; /* k = 2 */ lo = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = (mid + Math.imul(ah2, bl0)) | 0; hi = Math.imul(ah2, bh0); lo = (lo + Math.imul(al1, bl1)) | 0; mid = (mid + Math.imul(al1, bh1)) | 0; mid = (mid + Math.imul(ah1, bl1)) | 0; hi = (hi + Math.imul(ah1, bh1)) | 0; lo = (lo + Math.imul(al0, bl2)) | 0; mid = (mid + Math.imul(al0, bh2)) | 0; mid = (mid + Math.imul(ah0, bl2)) | 0; hi = (hi + Math.imul(ah0, bh2)) | 0; var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; w2 &= 0x3ffffff; /* k = 3 */ lo = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = (mid + Math.imul(ah3, bl0)) | 0; hi = Math.imul(ah3, bh0); lo = (lo + Math.imul(al2, bl1)) | 0; mid = (mid + Math.imul(al2, bh1)) | 0; mid = (mid + Math.imul(ah2, bl1)) | 0; hi = (hi + Math.imul(ah2, bh1)) | 0; lo = (lo + Math.imul(al1, bl2)) | 0; mid = (mid + Math.imul(al1, bh2)) | 0; mid = (mid + Math.imul(ah1, bl2)) | 0; hi = (hi + Math.imul(ah1, bh2)) | 0; lo = (lo + Math.imul(al0, bl3)) | 0; mid = (mid + Math.imul(al0, bh3)) | 0; mid = (mid + Math.imul(ah0, bl3)) | 0; hi = (hi + Math.imul(ah0, bh3)) | 0; var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; w3 &= 0x3ffffff; /* k = 4 */ lo = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = (mid + Math.imul(ah4, bl0)) | 0; hi = Math.imul(ah4, bh0); lo = (lo + Math.imul(al3, bl1)) | 0; mid = (mid + Math.imul(al3, bh1)) | 0; mid = (mid + Math.imul(ah3, bl1)) | 0; hi = (hi + Math.imul(ah3, bh1)) | 0; lo = (lo + Math.imul(al2, bl2)) | 0; mid = (mid + Math.imul(al2, bh2)) | 0; mid = (mid + Math.imul(ah2, bl2)) | 0; hi = (hi + Math.imul(ah2, bh2)) | 0; lo = (lo + Math.imul(al1, bl3)) | 0; mid = (mid + Math.imul(al1, bh3)) | 0; mid = (mid + Math.imul(ah1, bl3)) | 0; hi = (hi + Math.imul(ah1, bh3)) | 0; lo = (lo + Math.imul(al0, bl4)) | 0; mid = (mid + Math.imul(al0, bh4)) | 0; mid = (mid + Math.imul(ah0, bl4)) | 0; hi = (hi + Math.imul(ah0, bh4)) | 0; var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; w4 &= 0x3ffffff; /* k = 5 */ lo = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = (mid + Math.imul(ah5, bl0)) | 0; hi = Math.imul(ah5, bh0); lo = (lo + Math.imul(al4, bl1)) | 0; mid = (mid + Math.imul(al4, bh1)) | 0; mid = (mid + Math.imul(ah4, bl1)) | 0; hi = (hi + Math.imul(ah4, bh1)) | 0; lo = (lo + Math.imul(al3, bl2)) | 0; mid = (mid + Math.imul(al3, bh2)) | 0; mid = (mid + Math.imul(ah3, bl2)) | 0; hi = (hi + Math.imul(ah3, bh2)) | 0; lo = (lo + Math.imul(al2, bl3)) | 0; mid = (mid + Math.imul(al2, bh3)) | 0; mid = (mid + Math.imul(ah2, bl3)) | 0; hi = (hi + Math.imul(ah2, bh3)) | 0; lo = (lo + Math.imul(al1, bl4)) | 0; mid = (mid + Math.imul(al1, bh4)) | 0; mid = (mid + Math.imul(ah1, bl4)) | 0; hi = (hi + Math.imul(ah1, bh4)) | 0; lo = (lo + Math.imul(al0, bl5)) | 0; mid = (mid + Math.imul(al0, bh5)) | 0; mid = (mid + Math.imul(ah0, bl5)) | 0; hi = (hi + Math.imul(ah0, bh5)) | 0; var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; w5 &= 0x3ffffff; /* k = 6 */ lo = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = (mid + Math.imul(ah6, bl0)) | 0; hi = Math.imul(ah6, bh0); lo = (lo + Math.imul(al5, bl1)) | 0; mid = (mid + Math.imul(al5, bh1)) | 0; mid = (mid + Math.imul(ah5, bl1)) | 0; hi = (hi + Math.imul(ah5, bh1)) | 0; lo = (lo + Math.imul(al4, bl2)) | 0; mid = (mid + Math.imul(al4, bh2)) | 0; mid = (mid + Math.imul(ah4, bl2)) | 0; hi = (hi + Math.imul(ah4, bh2)) | 0; lo = (lo + Math.imul(al3, bl3)) | 0; mid = (mid + Math.imul(al3, bh3)) | 0; mid = (mid + Math.imul(ah3, bl3)) | 0; hi = (hi + Math.imul(ah3, bh3)) | 0; lo = (lo + Math.imul(al2, bl4)) | 0; mid = (mid + Math.imul(al2, bh4)) | 0; mid = (mid + Math.imul(ah2, bl4)) | 0; hi = (hi + Math.imul(ah2, bh4)) | 0; lo = (lo + Math.imul(al1, bl5)) | 0; mid = (mid + Math.imul(al1, bh5)) | 0; mid = (mid + Math.imul(ah1, bl5)) | 0; hi = (hi + Math.imul(ah1, bh5)) | 0; lo = (lo + Math.imul(al0, bl6)) | 0; mid = (mid + Math.imul(al0, bh6)) | 0; mid = (mid + Math.imul(ah0, bl6)) | 0; hi = (hi + Math.imul(ah0, bh6)) | 0; var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; w6 &= 0x3ffffff; /* k = 7 */ lo = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = (mid + Math.imul(ah7, bl0)) | 0; hi = Math.imul(ah7, bh0); lo = (lo + Math.imul(al6, bl1)) | 0; mid = (mid + Math.imul(al6, bh1)) | 0; mid = (mid + Math.imul(ah6, bl1)) | 0; hi = (hi + Math.imul(ah6, bh1)) | 0; lo = (lo + Math.imul(al5, bl2)) | 0; mid = (mid + Math.imul(al5, bh2)) | 0; mid = (mid + Math.imul(ah5, bl2)) | 0; hi = (hi + Math.imul(ah5, bh2)) | 0; lo = (lo + Math.imul(al4, bl3)) | 0; mid = (mid + Math.imul(al4, bh3)) | 0; mid = (mid + Math.imul(ah4, bl3)) | 0; hi = (hi + Math.imul(ah4, bh3)) | 0; lo = (lo + Math.imul(al3, bl4)) | 0; mid = (mid + Math.imul(al3, bh4)) | 0; mid = (mid + Math.imul(ah3, bl4)) | 0; hi = (hi + Math.imul(ah3, bh4)) | 0; lo = (lo + Math.imul(al2, bl5)) | 0; mid = (mid + Math.imul(al2, bh5)) | 0; mid = (mid + Math.imul(ah2, bl5)) | 0; hi = (hi + Math.imul(ah2, bh5)) | 0; lo = (lo + Math.imul(al1, bl6)) | 0; mid = (mid + Math.imul(al1, bh6)) | 0; mid = (mid + Math.imul(ah1, bl6)) | 0; hi = (hi + Math.imul(ah1, bh6)) | 0; lo = (lo + Math.imul(al0, bl7)) | 0; mid = (mid + Math.imul(al0, bh7)) | 0; mid = (mid + Math.imul(ah0, bl7)) | 0; hi = (hi + Math.imul(ah0, bh7)) | 0; var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; w7 &= 0x3ffffff; /* k = 8 */ lo = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = (mid + Math.imul(ah8, bl0)) | 0; hi = Math.imul(ah8, bh0); lo = (lo + Math.imul(al7, bl1)) | 0; mid = (mid + Math.imul(al7, bh1)) | 0; mid = (mid + Math.imul(ah7, bl1)) | 0; hi = (hi + Math.imul(ah7, bh1)) | 0; lo = (lo + Math.imul(al6, bl2)) | 0; mid = (mid + Math.imul(al6, bh2)) | 0; mid = (mid + Math.imul(ah6, bl2)) | 0; hi = (hi + Math.imul(ah6, bh2)) | 0; lo = (lo + Math.imul(al5, bl3)) | 0; mid = (mid + Math.imul(al5, bh3)) | 0; mid = (mid + Math.imul(ah5, bl3)) | 0; hi = (hi + Math.imul(ah5, bh3)) | 0; lo = (lo + Math.imul(al4, bl4)) | 0; mid = (mid + Math.imul(al4, bh4)) | 0; mid = (mid + Math.imul(ah4, bl4)) | 0; hi = (hi + Math.imul(ah4, bh4)) | 0; lo = (lo + Math.imul(al3, bl5)) | 0; mid = (mid + Math.imul(al3, bh5)) | 0; mid = (mid + Math.imul(ah3, bl5)) | 0; hi = (hi + Math.imul(ah3, bh5)) | 0; lo = (lo + Math.imul(al2, bl6)) | 0; mid = (mid + Math.imul(al2, bh6)) | 0; mid = (mid + Math.imul(ah2, bl6)) | 0; hi = (hi + Math.imul(ah2, bh6)) | 0; lo = (lo + Math.imul(al1, bl7)) | 0; mid = (mid + Math.imul(al1, bh7)) | 0; mid = (mid + Math.imul(ah1, bl7)) | 0; hi = (hi + Math.imul(ah1, bh7)) | 0; lo = (lo + Math.imul(al0, bl8)) | 0; mid = (mid + Math.imul(al0, bh8)) | 0; mid = (mid + Math.imul(ah0, bl8)) | 0; hi = (hi + Math.imul(ah0, bh8)) | 0; var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; w8 &= 0x3ffffff; /* k = 9 */ lo = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = (mid + Math.imul(ah9, bl0)) | 0; hi = Math.imul(ah9, bh0); lo = (lo + Math.imul(al8, bl1)) | 0; mid = (mid + Math.imul(al8, bh1)) | 0; mid = (mid + Math.imul(ah8, bl1)) | 0; hi = (hi + Math.imul(ah8, bh1)) | 0; lo = (lo + Math.imul(al7, bl2)) | 0; mid = (mid + Math.imul(al7, bh2)) | 0; mid = (mid + Math.imul(ah7, bl2)) | 0; hi = (hi + Math.imul(ah7, bh2)) | 0; lo = (lo + Math.imul(al6, bl3)) | 0; mid = (mid + Math.imul(al6, bh3)) | 0; mid = (mid + Math.imul(ah6, bl3)) | 0; hi = (hi + Math.imul(ah6, bh3)) | 0; lo = (lo + Math.imul(al5, bl4)) | 0; mid = (mid + Math.imul(al5, bh4)) | 0; mid = (mid + Math.imul(ah5, bl4)) | 0; hi = (hi + Math.imul(ah5, bh4)) | 0; lo = (lo + Math.imul(al4, bl5)) | 0; mid = (mid + Math.imul(al4, bh5)) | 0; mid = (mid + Math.imul(ah4, bl5)) | 0; hi = (hi + Math.imul(ah4, bh5)) | 0; lo = (lo + Math.imul(al3, bl6)) | 0; mid = (mid + Math.imul(al3, bh6)) | 0; mid = (mid + Math.imul(ah3, bl6)) | 0; hi = (hi + Math.imul(ah3, bh6)) | 0; lo = (lo + Math.imul(al2, bl7)) | 0; mid = (mid + Math.imul(al2, bh7)) | 0; mid = (mid + Math.imul(ah2, bl7)) | 0; hi = (hi + Math.imul(ah2, bh7)) | 0; lo = (lo + Math.imul(al1, bl8)) | 0; mid = (mid + Math.imul(al1, bh8)) | 0; mid = (mid + Math.imul(ah1, bl8)) | 0; hi = (hi + Math.imul(ah1, bh8)) | 0; lo = (lo + Math.imul(al0, bl9)) | 0; mid = (mid + Math.imul(al0, bh9)) | 0; mid = (mid + Math.imul(ah0, bl9)) | 0; hi = (hi + Math.imul(ah0, bh9)) | 0; var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; w9 &= 0x3ffffff; /* k = 10 */ lo = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = (mid + Math.imul(ah9, bl1)) | 0; hi = Math.imul(ah9, bh1); lo = (lo + Math.imul(al8, bl2)) | 0; mid = (mid + Math.imul(al8, bh2)) | 0; mid = (mid + Math.imul(ah8, bl2)) | 0; hi = (hi + Math.imul(ah8, bh2)) | 0; lo = (lo + Math.imul(al7, bl3)) | 0; mid = (mid + Math.imul(al7, bh3)) | 0; mid = (mid + Math.imul(ah7, bl3)) | 0; hi = (hi + Math.imul(ah7, bh3)) | 0; lo = (lo + Math.imul(al6, bl4)) | 0; mid = (mid + Math.imul(al6, bh4)) | 0; mid = (mid + Math.imul(ah6, bl4)) | 0; hi = (hi + Math.imul(ah6, bh4)) | 0; lo = (lo + Math.imul(al5, bl5)) | 0; mid = (mid + Math.imul(al5, bh5)) | 0; mid = (mid + Math.imul(ah5, bl5)) | 0; hi = (hi + Math.imul(ah5, bh5)) | 0; lo = (lo + Math.imul(al4, bl6)) | 0; mid = (mid + Math.imul(al4, bh6)) | 0; mid = (mid + Math.imul(ah4, bl6)) | 0; hi = (hi + Math.imul(ah4, bh6)) | 0; lo = (lo + Math.imul(al3, bl7)) | 0; mid = (mid + Math.imul(al3, bh7)) | 0; mid = (mid + Math.imul(ah3, bl7)) | 0; hi = (hi + Math.imul(ah3, bh7)) | 0; lo = (lo + Math.imul(al2, bl8)) | 0; mid = (mid + Math.imul(al2, bh8)) | 0; mid = (mid + Math.imul(ah2, bl8)) | 0; hi = (hi + Math.imul(ah2, bh8)) | 0; lo = (lo + Math.imul(al1, bl9)) | 0; mid = (mid + Math.imul(al1, bh9)) | 0; mid = (mid + Math.imul(ah1, bl9)) | 0; hi = (hi + Math.imul(ah1, bh9)) | 0; var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; w10 &= 0x3ffffff; /* k = 11 */ lo = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = (mid + Math.imul(ah9, bl2)) | 0; hi = Math.imul(ah9, bh2); lo = (lo + Math.imul(al8, bl3)) | 0; mid = (mid + Math.imul(al8, bh3)) | 0; mid = (mid + Math.imul(ah8, bl3)) | 0; hi = (hi + Math.imul(ah8, bh3)) | 0; lo = (lo + Math.imul(al7, bl4)) | 0; mid = (mid + Math.imul(al7, bh4)) | 0; mid = (mid + Math.imul(ah7, bl4)) | 0; hi = (hi + Math.imul(ah7, bh4)) | 0; lo = (lo + Math.imul(al6, bl5)) | 0; mid = (mid + Math.imul(al6, bh5)) | 0; mid = (mid + Math.imul(ah6, bl5)) | 0; hi = (hi + Math.imul(ah6, bh5)) | 0; lo = (lo + Math.imul(al5, bl6)) | 0; mid = (mid + Math.imul(al5, bh6)) | 0; mid = (mid + Math.imul(ah5, bl6)) | 0; hi = (hi + Math.imul(ah5, bh6)) | 0; lo = (lo + Math.imul(al4, bl7)) | 0; mid = (mid + Math.imul(al4, bh7)) | 0; mid = (mid + Math.imul(ah4, bl7)) | 0; hi = (hi + Math.imul(ah4, bh7)) | 0; lo = (lo + Math.imul(al3, bl8)) | 0; mid = (mid + Math.imul(al3, bh8)) | 0; mid = (mid + Math.imul(ah3, bl8)) | 0; hi = (hi + Math.imul(ah3, bh8)) | 0; lo = (lo + Math.imul(al2, bl9)) | 0; mid = (mid + Math.imul(al2, bh9)) | 0; mid = (mid + Math.imul(ah2, bl9)) | 0; hi = (hi + Math.imul(ah2, bh9)) | 0; var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; w11 &= 0x3ffffff; /* k = 12 */ lo = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = (mid + Math.imul(ah9, bl3)) | 0; hi = Math.imul(ah9, bh3); lo = (lo + Math.imul(al8, bl4)) | 0; mid = (mid + Math.imul(al8, bh4)) | 0; mid = (mid + Math.imul(ah8, bl4)) | 0; hi = (hi + Math.imul(ah8, bh4)) | 0; lo = (lo + Math.imul(al7, bl5)) | 0; mid = (mid + Math.imul(al7, bh5)) | 0; mid = (mid + Math.imul(ah7, bl5)) | 0; hi = (hi + Math.imul(ah7, bh5)) | 0; lo = (lo + Math.imul(al6, bl6)) | 0; mid = (mid + Math.imul(al6, bh6)) | 0; mid = (mid + Math.imul(ah6, bl6)) | 0; hi = (hi + Math.imul(ah6, bh6)) | 0; lo = (lo + Math.imul(al5, bl7)) | 0; mid = (mid + Math.imul(al5, bh7)) | 0; mid = (mid + Math.imul(ah5, bl7)) | 0; hi = (hi + Math.imul(ah5, bh7)) | 0; lo = (lo + Math.imul(al4, bl8)) | 0; mid = (mid + Math.imul(al4, bh8)) | 0; mid = (mid + Math.imul(ah4, bl8)) | 0; hi = (hi + Math.imul(ah4, bh8)) | 0; lo = (lo + Math.imul(al3, bl9)) | 0; mid = (mid + Math.imul(al3, bh9)) | 0; mid = (mid + Math.imul(ah3, bl9)) | 0; hi = (hi + Math.imul(ah3, bh9)) | 0; var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; w12 &= 0x3ffffff; /* k = 13 */ lo = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = (mid + Math.imul(ah9, bl4)) | 0; hi = Math.imul(ah9, bh4); lo = (lo + Math.imul(al8, bl5)) | 0; mid = (mid + Math.imul(al8, bh5)) | 0; mid = (mid + Math.imul(ah8, bl5)) | 0; hi = (hi + Math.imul(ah8, bh5)) | 0; lo = (lo + Math.imul(al7, bl6)) | 0; mid = (mid + Math.imul(al7, bh6)) | 0; mid = (mid + Math.imul(ah7, bl6)) | 0; hi = (hi + Math.imul(ah7, bh6)) | 0; lo = (lo + Math.imul(al6, bl7)) | 0; mid = (mid + Math.imul(al6, bh7)) | 0; mid = (mid + Math.imul(ah6, bl7)) | 0; hi = (hi + Math.imul(ah6, bh7)) | 0; lo = (lo + Math.imul(al5, bl8)) | 0; mid = (mid + Math.imul(al5, bh8)) | 0; mid = (mid + Math.imul(ah5, bl8)) | 0; hi = (hi + Math.imul(ah5, bh8)) | 0; lo = (lo + Math.imul(al4, bl9)) | 0; mid = (mid + Math.imul(al4, bh9)) | 0; mid = (mid + Math.imul(ah4, bl9)) | 0; hi = (hi + Math.imul(ah4, bh9)) | 0; var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; w13 &= 0x3ffffff; /* k = 14 */ lo = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = (mid + Math.imul(ah9, bl5)) | 0; hi = Math.imul(ah9, bh5); lo = (lo + Math.imul(al8, bl6)) | 0; mid = (mid + Math.imul(al8, bh6)) | 0; mid = (mid + Math.imul(ah8, bl6)) | 0; hi = (hi + Math.imul(ah8, bh6)) | 0; lo = (lo + Math.imul(al7, bl7)) | 0; mid = (mid + Math.imul(al7, bh7)) | 0; mid = (mid + Math.imul(ah7, bl7)) | 0; hi = (hi + Math.imul(ah7, bh7)) | 0; lo = (lo + Math.imul(al6, bl8)) | 0; mid = (mid + Math.imul(al6, bh8)) | 0; mid = (mid + Math.imul(ah6, bl8)) | 0; hi = (hi + Math.imul(ah6, bh8)) | 0; lo = (lo + Math.imul(al5, bl9)) | 0; mid = (mid + Math.imul(al5, bh9)) | 0; mid = (mid + Math.imul(ah5, bl9)) | 0; hi = (hi + Math.imul(ah5, bh9)) | 0; var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; w14 &= 0x3ffffff; /* k = 15 */ lo = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = (mid + Math.imul(ah9, bl6)) | 0; hi = Math.imul(ah9, bh6); lo = (lo + Math.imul(al8, bl7)) | 0; mid = (mid + Math.imul(al8, bh7)) | 0; mid = (mid + Math.imul(ah8, bl7)) | 0; hi = (hi + Math.imul(ah8, bh7)) | 0; lo = (lo + Math.imul(al7, bl8)) | 0; mid = (mid + Math.imul(al7, bh8)) | 0; mid = (mid + Math.imul(ah7, bl8)) | 0; hi = (hi + Math.imul(ah7, bh8)) | 0; lo = (lo + Math.imul(al6, bl9)) | 0; mid = (mid + Math.imul(al6, bh9)) | 0; mid = (mid + Math.imul(ah6, bl9)) | 0; hi = (hi + Math.imul(ah6, bh9)) | 0; var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; w15 &= 0x3ffffff; /* k = 16 */ lo = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = (mid + Math.imul(ah9, bl7)) | 0; hi = Math.imul(ah9, bh7); lo = (lo + Math.imul(al8, bl8)) | 0; mid = (mid + Math.imul(al8, bh8)) | 0; mid = (mid + Math.imul(ah8, bl8)) | 0; hi = (hi + Math.imul(ah8, bh8)) | 0; lo = (lo + Math.imul(al7, bl9)) | 0; mid = (mid + Math.imul(al7, bh9)) | 0; mid = (mid + Math.imul(ah7, bl9)) | 0; hi = (hi + Math.imul(ah7, bh9)) | 0; var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; w16 &= 0x3ffffff; /* k = 17 */ lo = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = (mid + Math.imul(ah9, bl8)) | 0; hi = Math.imul(ah9, bh8); lo = (lo + Math.imul(al8, bl9)) | 0; mid = (mid + Math.imul(al8, bh9)) | 0; mid = (mid + Math.imul(ah8, bl9)) | 0; hi = (hi + Math.imul(ah8, bh9)) | 0; var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; w17 &= 0x3ffffff; /* k = 18 */ lo = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = (mid + Math.imul(ah9, bl9)) | 0; hi = Math.imul(ah9, bh9); var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; w18 &= 0x3ffffff; o[0] = w0; o[1] = w1; o[2] = w2; o[3] = w3; o[4] = w4; o[5] = w5; o[6] = w6; o[7] = w7; o[8] = w8; o[9] = w9; o[10] = w10; o[11] = w11; o[12] = w12; o[13] = w13; o[14] = w14; o[15] = w15; o[16] = w16; o[17] = w17; o[18] = w18; if (c !== 0) { o[19] = c; out.length++; } return out; }; // Polyfill comb if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo (self, num, out) { out.negative = num.negative ^ self.negative; out.length = self.length + num.length; var carry = 0; var hncarry = 0; for (var k = 0; k < out.length - 1; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = hncarry; hncarry = 0; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = k - j; var a = self.words[i] | 0; var b = num.words[j] | 0; var r = a * b; var lo = r & 0x3ffffff; ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; lo = (lo + rword) | 0; rword = lo & 0x3ffffff; ncarry = (ncarry + (lo >>> 26)) | 0; hncarry += ncarry >>> 26; ncarry &= 0x3ffffff; } out.words[k] = rword; carry = ncarry; ncarry = hncarry; } if (carry !== 0) { out.words[k] = carry; } else { out.length--; } return out._strip(); } function jumboMulTo (self, num, out) { // Temporary disable, see https://github.com/indutny/bn.js/issues/211 // var fftm = new FFTM(); // return fftm.mulp(self, num, out); return bigMulTo(self, num, out); } BN.prototype.mulTo = function mulTo (num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; // Cooley-Tukey algorithm for FFT // slightly revisited to rely on looping instead of recursion function FFTM (x, y) { this.x = x; this.y = y; } FFTM.prototype.makeRBT = function makeRBT (N) { var t = new Array(N); var l = BN.prototype._countBits(N) - 1; for (var i = 0; i < N; i++) { t[i] = this.revBin(i, l, N); } return t; }; // Returns binary-reversed representation of `x` FFTM.prototype.revBin = function revBin (x, l, N) { if (x === 0 || x === N - 1) return x; var rb = 0; for (var i = 0; i < l; i++) { rb |= (x & 1) << (l - i - 1); x >>= 1; } return rb; }; // Performs "tweedling" phase, therefore 'emulating' // behaviour of the recursive algorithm FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { for (var i = 0; i < N; i++) { rtws[i] = rws[rbt[i]]; itws[i] = iws[rbt[i]]; } }; FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { this.permute(rbt, rws, iws, rtws, itws, N); for (var s = 1; s < N; s <<= 1) { var l = s << 1; var rtwdf = Math.cos(2 * Math.PI / l); var itwdf = Math.sin(2 * Math.PI / l); for (var p = 0; p < N; p += l) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j = 0; j < s; j++) { var re = rtws[p + j]; var ie = itws[p + j]; var ro = rtws[p + j + s]; var io = itws[p + j + s]; var rx = rtwdf_ * ro - itwdf_ * io; io = rtwdf_ * io + itwdf_ * ro; ro = rx; rtws[p + j] = re + ro; itws[p + j] = ie + io; rtws[p + j + s] = re - ro; itws[p + j + s] = ie - io; /* jshint maxdepth : false */ if (j !== l) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; var i = 0; for (N = N / 2 | 0; N; N = N >>> 1) { i++; } return 1 << i + 1 + odd; }; FFTM.prototype.conjugate = function conjugate (rws, iws, N) { if (N <= 1) return; for (var i = 0; i < N / 2; i++) { var t = rws[i]; rws[i] = rws[N - i - 1]; rws[N - i - 1] = t; t = iws[i]; iws[i] = -iws[N - i - 1]; iws[N - i - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b (ws, N) { var carry = 0; for (var i = 0; i < N / 2; i++) { var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry; ws[i] = w & 0x3ffffff; if (w < 0x4000000) { carry = 0; } else { carry = w / 0x4000000 | 0; } } return ws; }; FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { var carry = 0; for (var i = 0; i < len; i++) { carry = carry + (ws[i] | 0); rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; } // Pad with zeroes for (i = 2 * len; i < N; ++i) { rws[i] = 0; } assert(carry === 0); assert((carry & ~0x1fff) === 0); }; FFTM.prototype.stub = function stub (N) { var ph = new Array(N); for (var i = 0; i < N; i++) { ph[i] = 0; } return ph; }; FFTM.prototype.mulp = function mulp (x, y, out) { var N = 2 * this.guessLen13b(x.length, y.length); var rbt = this.makeRBT(N); var _ = this.stub(N); var rws = new Array(N); var rwst = new Array(N); var iwst = new Array(N); var nrws = new Array(N); var nrwst = new Array(N); var niwst = new Array(N); var rmws = out.words; rmws.length = N; this.convert13b(x.words, x.length, rws, N); this.convert13b(y.words, y.length, nrws, N); this.transform(rws, _, rwst, iwst, N, rbt); this.transform(nrws, _, nrwst, niwst, N, rbt); for (var i = 0; i < N; i++) { var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; rwst[i] = rx; } this.conjugate(rwst, iwst, N); this.transform(rwst, iwst, rmws, _, N, rbt); this.conjugate(rmws, _, N); this.normalize13b(rmws, N); out.negative = x.negative ^ y.negative; out.length = x.length + y.length; return out._strip(); }; // Multiply `this` by `num` BN.prototype.mul = function mul (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; // Multiply employing FFT BN.prototype.mulf = function mulf (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; // In-place Multiplication BN.prototype.imul = function imul (num) { return this.clone().mulTo(num, this); }; BN.prototype.imuln = function imuln (num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert(typeof num === 'number'); assert(num < 0x4000000); // Carry var carry = 0; for (var i = 0; i < this.length; i++) { var w = (this.words[i] | 0) * num; var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); carry >>= 26; carry += (w / 0x4000000) | 0; // NOTE: lo is 27bit maximum carry += lo >>> 26; this.words[i] = lo & 0x3ffffff; } if (carry !== 0) { this.words[i] = carry; this.length++; } return isNegNum ? this.ineg() : this; }; BN.prototype.muln = function muln (num) { return this.clone().imuln(num); }; // `this` * `this` BN.prototype.sqr = function sqr () { return this.mul(this); }; // `this` * `this` in-place BN.prototype.isqr = function isqr () { return this.imul(this.clone()); }; // Math.pow(`this`, `num`) BN.prototype.pow = function pow (num) { var w = toBitArray(num); if (w.length === 0) return new BN(1); // Skip leading zeroes var res = this; for (var i = 0; i < w.length; i++, res = res.sqr()) { if (w[i] !== 0) break; } if (++i < w.length) { for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { if (w[i] === 0) continue; res = res.mul(q); } } return res; }; // Shift-left in-place BN.prototype.iushln = function iushln (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); var i; if (r !== 0) { var carry = 0; for (i = 0; i < this.length; i++) { var newCarry = this.words[i] & carryMask; var c = ((this.words[i] | 0) - newCarry) << r; this.words[i] = c | carry; carry = newCarry >>> (26 - r); } if (carry) { this.words[i] = carry; this.length++; } } if (s !== 0) { for (i = this.length - 1; i >= 0; i--) { this.words[i + s] = this.words[i]; } for (i = 0; i < s; i++) { this.words[i] = 0; } this.length += s; } return this._strip(); }; BN.prototype.ishln = function ishln (bits) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushln(bits); }; // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits BN.prototype.iushrn = function iushrn (bits, hint, extended) { assert(typeof bits === 'number' && bits >= 0); var h; if (hint) { h = (hint - (hint % 26)) / 26; } else { h = 0; } var r = bits % 26; var s = Math.min((bits - r) / 26, this.length); var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); var maskedWords = extended; h -= s; h = Math.max(0, h); // Extended mode, copy masked part if (maskedWords) { for (var i = 0; i < s; i++) { maskedWords.words[i] = this.words[i]; } maskedWords.length = s; } if (s === 0) { // No-op, we should not move anything at all } else if (this.length > s) { this.length -= s; for (i = 0; i < this.length; i++) { this.words[i] = this.words[i + s]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { var word = this.words[i] | 0; this.words[i] = (carry << (26 - r)) | (word >>> r); carry = word & mask; } // Push carried bits as a mask if (maskedWords && carry !== 0) { maskedWords.words[maskedWords.length++] = carry; } if (this.length === 0) { this.words[0] = 0; this.length = 1; } return this._strip(); }; BN.prototype.ishrn = function ishrn (bits, hint, extended) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushrn(bits, hint, extended); }; // Shift-left BN.prototype.shln = function shln (bits) { return this.clone().ishln(bits); }; BN.prototype.ushln = function ushln (bits) { return this.clone().iushln(bits); }; // Shift-right BN.prototype.shrn = function shrn (bits) { return this.clone().ishrn(bits); }; BN.prototype.ushrn = function ushrn (bits) { return this.clone().iushrn(bits); }; // Test if n bit is set BN.prototype.testn = function testn (bit) { assert(typeof bit === 'number' && bit >= 0); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) return false; // Check bit and return var w = this.words[s]; return !!(w & q); }; // Return only lowers bits of number (in-place) BN.prototype.imaskn = function imaskn (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; assert(this.negative === 0, 'imaskn works only with positive numbers'); if (this.length <= s) { return this; } if (r !== 0) { s++; } this.length = Math.min(s, this.length); if (r !== 0) { var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); this.words[this.length - 1] &= mask; } return this._strip(); }; // Return only lowers bits of number BN.prototype.maskn = function maskn (bits) { return this.clone().imaskn(bits); }; // Add plain number `num` to `this` BN.prototype.iaddn = function iaddn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.isubn(-num); // Possible sign change if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) <= num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } // Add without checks return this._iaddn(num); }; BN.prototype._iaddn = function _iaddn (num) { this.words[0] += num; // Carry for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { this.words[i] -= 0x4000000; if (i === this.length - 1) { this.words[i + 1] = 1; } else { this.words[i + 1]++; } } this.length = Math.max(this.length, i + 1); return this; }; // Subtract plain number `num` from `this` BN.prototype.isubn = function isubn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { // Carry for (var i = 0; i < this.length && this.words[i] < 0; i++) { this.words[i] += 0x4000000; this.words[i + 1] -= 1; } } return this._strip(); }; BN.prototype.addn = function addn (num) { return this.clone().iaddn(num); }; BN.prototype.subn = function subn (num) { return this.clone().isubn(num); }; BN.prototype.iabs = function iabs () { this.negative = 0; return this; }; BN.prototype.abs = function abs () { return this.clone().iabs(); }; BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { var len = num.length + shift; var i; this._expand(len); var w; var carry = 0; for (i = 0; i < num.length; i++) { w = (this.words[i + shift] | 0) + carry; var right = (num.words[i] | 0) * mul; w -= right & 0x3ffffff; carry = (w >> 26) - ((right / 0x4000000) | 0); this.words[i + shift] = w & 0x3ffffff; } for (; i < this.length - shift; i++) { w = (this.words[i + shift] | 0) + carry; carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } if (carry === 0) return this._strip(); // Subtraction overflow assert(carry === -1); carry = 0; for (i = 0; i < this.length; i++) { w = -(this.words[i] | 0) + carry; carry = w >> 26; this.words[i] = w & 0x3ffffff; } this.negative = 1; return this._strip(); }; BN.prototype._wordDiv = function _wordDiv (num, mode) { var shift = this.length - num.length; var a = this.clone(); var b = num; // Normalize var bhi = b.words[b.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b = b.ushln(shift); a.iushln(shift); bhi = b.words[b.length - 1] | 0; } // Initialize quotient var m = a.length - b.length; var q; if (mode !== 'mod') { q = new BN(null); q.length = m + 1; q.words = new Array(q.length); for (var i = 0; i < q.length; i++) { q.words[i] = 0; } } var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; if (q) { q.words[m] = 1; } } for (var j = m - 1; j >= 0; j--) { var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max // (0x7ffffff) qj = Math.min((qj / bhi) | 0, 0x3ffffff); a._ishlnsubmul(b, qj, j); while (a.negative !== 0) { qj--; a.negative = 0; a._ishlnsubmul(b, 1, j); if (!a.isZero()) { a.negative ^= 1; } } if (q) { q.words[j] = qj; } } if (q) { q._strip(); } a._strip(); // Denormalize if (mode !== 'div' && shift !== 0) { a.iushrn(shift); } return { div: q || null, mod: a }; }; // NOTE: 1) `mode` can be set to `mod` to request mod only, // to `div` to request div only, or be absent to // request both div & mod // 2) `positive` is true if unsigned mod is requested BN.prototype.divmod = function divmod (num, mode, positive) { assert(!num.isZero()); if (this.isZero()) { return { div: new BN(0), mod: new BN(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== 'mod') { div = res.div.neg(); } if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div: div, mod: mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== 'mod') { div = res.div.neg(); } return { div: div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod: mod }; } // Both numbers are positive at this point // Strip both numbers to approximate shift value if (num.length > this.length || this.cmp(num) < 0) { return { div: new BN(0), mod: this }; } // Very short reduction if (num.length === 1) { if (mode === 'div') { return { div: this.divn(num.words[0]), mod: null }; } if (mode === 'mod') { return { div: null, mod: new BN(this.modrn(num.words[0])) }; } return { div: this.divn(num.words[0]), mod: new BN(this.modrn(num.words[0])) }; } return this._wordDiv(num, mode); }; // Find `this` / `num` BN.prototype.div = function div (num) { return this.divmod(num, 'div', false).div; }; // Find `this` % `num` BN.prototype.mod = function mod (num) { return this.divmod(num, 'mod', false).mod; }; BN.prototype.umod = function umod (num) { return this.divmod(num, 'mod', true).mod; }; // Find Round(`this` / `num`) BN.prototype.divRound = function divRound (num) { var dm = this.divmod(num); // Fast case - exact division if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(1); var r2 = num.andln(1); var cmp = mod.cmp(half); // Round down if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div; // Round up return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); }; BN.prototype.modrn = function modrn (num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert(num <= 0x3ffffff); var p = (1 << 26) % num; var acc = 0; for (var i = this.length - 1; i >= 0; i--) { acc = (p * acc + (this.words[i] | 0)) % num; } return isNegNum ? -acc : acc; }; // WARNING: DEPRECATED BN.prototype.modn = function modn (num) { return this.modrn(num); }; // In-place division by number BN.prototype.idivn = function idivn (num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert(num <= 0x3ffffff); var carry = 0; for (var i = this.length - 1; i >= 0; i--) { var w = (this.words[i] | 0) + carry * 0x4000000; this.words[i] = (w / num) | 0; carry = w % num; } this._strip(); return isNegNum ? this.ineg() : this; }; BN.prototype.divn = function divn (num) { return this.clone().idivn(num); }; BN.prototype.egcd = function egcd (p) { assert(p.negative === 0); assert(!p.isZero()); var x = this; var y = p.clone(); if (x.negative !== 0) { x = x.umod(p); } else { x = x.clone(); } // A * x + B * y = x var A = new BN(1); var B = new BN(0); // C * x + D * y = y var C = new BN(0); var D = new BN(1); var g = 0; while (x.isEven() && y.isEven()) { x.iushrn(1); y.iushrn(1); ++g; } var yp = y.clone(); var xp = x.clone(); while (!x.isZero()) { for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { x.iushrn(i); while (i-- > 0) { if (A.isOdd() || B.isOdd()) { A.iadd(yp); B.isub(xp); } A.iushrn(1); B.iushrn(1); } } for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { y.iushrn(j); while (j-- > 0) { if (C.isOdd() || D.isOdd()) { C.iadd(yp); D.isub(xp); } C.iushrn(1); D.iushrn(1); } } if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); B.isub(D); } else { y.isub(x); C.isub(A); D.isub(B); } } return { a: C, b: D, gcd: y.iushln(g) }; }; // This is reduced incarnation of the binary EEA // above, designated to invert members of the // _prime_ fields F(p) at a maximal speed BN.prototype._invmp = function _invmp (p) { assert(p.negative === 0); assert(!p.isZero()); var a = this; var b = p.clone(); if (a.negative !== 0) { a = a.umod(p); } else { a = a.clone(); } var x1 = new BN(1); var x2 = new BN(0); var delta = b.clone(); while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { a.iushrn(i); while (i-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { b.iushrn(j); while (j-- > 0) { if (x2.isOdd()) { x2.iadd(delta); } x2.iushrn(1); } } if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); } else { b.isub(a); x2.isub(x1); } } var res; if (a.cmpn(1) === 0) { res = x1; } else { res = x2; } if (res.cmpn(0) < 0) { res.iadd(p); } return res; }; BN.prototype.gcd = function gcd (num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a = this.clone(); var b = num.clone(); a.negative = 0; b.negative = 0; // Remove common factor of two for (var shift = 0; a.isEven() && b.isEven(); shift++) { a.iushrn(1); b.iushrn(1); } do { while (a.isEven()) { a.iushrn(1); } while (b.isEven()) { b.iushrn(1); } var r = a.cmp(b); if (r < 0) { // Swap `a` and `b` to make `a` always bigger than `b` var t = a; a = b; b = t; } else if (r === 0 || b.cmpn(1) === 0) { break; } a.isub(b); } while (true); return b.iushln(shift); }; // Invert number in the field F(num) BN.prototype.invm = function invm (num) { return this.egcd(num).a.umod(num); }; BN.prototype.isEven = function isEven () { return (this.words[0] & 1) === 0; }; BN.prototype.isOdd = function isOdd () { return (this.words[0] & 1) === 1; }; // And first word and num BN.prototype.andln = function andln (num) { return this.words[0] & num; }; // Increment at the bit position in-line BN.prototype.bincn = function bincn (bit) { assert(typeof bit === 'number'); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) { this._expand(s + 1); this.words[s] |= q; return this; } // Add bit and propagate, if needed var carry = q; for (var i = s; carry !== 0 && i < this.length; i++) { var w = this.words[i] | 0; w += carry; carry = w >>> 26; w &= 0x3ffffff; this.words[i] = w; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.isZero = function isZero () { return this.length === 1 && this.words[0] === 0; }; BN.prototype.cmpn = function cmpn (num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this._strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert(num <= 0x3ffffff, 'Number is too big'); var w = this.words[0] | 0; res = w === num ? 0 : w < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; // Compare two numbers and return: // 1 - if `this` > `num` // 0 - if `this` == `num` // -1 - if `this` < `num` BN.prototype.cmp = function cmp (num) { if (this.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; return res; }; // Unsigned comparison BN.prototype.ucmp = function ucmp (num) { // At this point both numbers have the same sign if (this.length > num.length) return 1; if (this.length < num.length) return -1; var res = 0; for (var i = this.length - 1; i >= 0; i--) { var a = this.words[i] | 0; var b = num.words[i] | 0; if (a === b) continue; if (a < b) { res = -1; } else if (a > b) { res = 1; } break; } return res; }; BN.prototype.gtn = function gtn (num) { return this.cmpn(num) === 1; }; BN.prototype.gt = function gt (num) { return this.cmp(num) === 1; }; BN.prototype.gten = function gten (num) { return this.cmpn(num) >= 0; }; BN.prototype.gte = function gte (num) { return this.cmp(num) >= 0; }; BN.prototype.ltn = function ltn (num) { return this.cmpn(num) === -1; }; BN.prototype.lt = function lt (num) { return this.cmp(num) === -1; }; BN.prototype.lten = function lten (num) { return this.cmpn(num) <= 0; }; BN.prototype.lte = function lte (num) { return this.cmp(num) <= 0; }; BN.prototype.eqn = function eqn (num) { return this.cmpn(num) === 0; }; BN.prototype.eq = function eq (num) { return this.cmp(num) === 0; }; // // A reduce context, could be using montgomery or something better, depending // on the `m` itself. // BN.red = function red (num) { return new Red(num); }; BN.prototype.toRed = function toRed (ctx) { assert(!this.red, 'Already a number in reduction context'); assert(this.negative === 0, 'red works only with positives'); return ctx.convertTo(this)._forceRed(ctx); }; BN.prototype.fromRed = function fromRed () { assert(this.red, 'fromRed works only with numbers in reduction context'); return this.red.convertFrom(this); }; BN.prototype._forceRed = function _forceRed (ctx) { this.red = ctx; return this; }; BN.prototype.forceRed = function forceRed (ctx) { assert(!this.red, 'Already a number in reduction context'); return this._forceRed(ctx); }; BN.prototype.redAdd = function redAdd (num) { assert(this.red, 'redAdd works only with red numbers'); return this.red.add(this, num); }; BN.prototype.redIAdd = function redIAdd (num) { assert(this.red, 'redIAdd works only with red numbers'); return this.red.iadd(this, num); }; BN.prototype.redSub = function redSub (num) { assert(this.red, 'redSub works only with red numbers'); return this.red.sub(this, num); }; BN.prototype.redISub = function redISub (num) { assert(this.red, 'redISub works only with red numbers'); return this.red.isub(this, num); }; BN.prototype.redShl = function redShl (num) { assert(this.red, 'redShl works only with red numbers'); return this.red.shl(this, num); }; BN.prototype.redMul = function redMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.mul(this, num); }; BN.prototype.redIMul = function redIMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.imul(this, num); }; BN.prototype.redSqr = function redSqr () { assert(this.red, 'redSqr works only with red numbers'); this.red._verify1(this); return this.red.sqr(this); }; BN.prototype.redISqr = function redISqr () { assert(this.red, 'redISqr works only with red numbers'); this.red._verify1(this); return this.red.isqr(this); }; // Square root over p BN.prototype.redSqrt = function redSqrt () { assert(this.red, 'redSqrt works only with red numbers'); this.red._verify1(this); return this.red.sqrt(this); }; BN.prototype.redInvm = function redInvm () { assert(this.red, 'redInvm works only with red numbers'); this.red._verify1(this); return this.red.invm(this); }; // Return negative clone of `this` % `red modulo` BN.prototype.redNeg = function redNeg () { assert(this.red, 'redNeg works only with red numbers'); this.red._verify1(this); return this.red.neg(this); }; BN.prototype.redPow = function redPow (num) { assert(this.red && !num.red, 'redPow(normalNum)'); this.red._verify1(this); return this.red.pow(this, num); }; // Prime numbers with efficient reduction var primes = { k256: null, p224: null, p192: null, p25519: null }; // Pseudo-Mersenne prime function MPrime (name, p) { // P = 2 ^ N - K this.name = name; this.p = new BN(p, 16); this.n = this.p.bitLength(); this.k = new BN(1).iushln(this.n).isub(this.p); this.tmp = this._tmp(); } MPrime.prototype._tmp = function _tmp () { var tmp = new BN(null); tmp.words = new Array(Math.ceil(this.n / 13)); return tmp; }; MPrime.prototype.ireduce = function ireduce (num) { // Assumes that `num` is less than `P^2` // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) var r = num; var rlen; do { this.split(r, this.tmp); r = this.imulK(r); r = r.iadd(this.tmp); rlen = r.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r.ucmp(this.p); if (cmp === 0) { r.words[0] = 0; r.length = 1; } else if (cmp > 0) { r.isub(this.p); } else { if (r.strip !== undefined) { // r is a BN v4 instance r.strip(); } else { // r is a BN v5 instance r._strip(); } } return r; }; MPrime.prototype.split = function split (input, out) { input.iushrn(this.n, 0, out); }; MPrime.prototype.imulK = function imulK (num) { return num.imul(this.k); }; function K256 () { MPrime.call( this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); } inherits(K256, MPrime); K256.prototype.split = function split (input, output) { // 256 = 9 * 26 + 22 var mask = 0x3fffff; var outLen = Math.min(input.length, 9); for (var i = 0; i < outLen; i++) { output.words[i] = input.words[i]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } // Shift by 9 limbs var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i = 10; i < input.length; i++) { var next = input.words[i] | 0; input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); prev = next; } prev >>>= 22; input.words[i - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK (num) { // K = 0x1000003d1 = [ 0x40, 0x3d1 ] num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 var lo = 0; for (var i = 0; i < num.length; i++) { var w = num.words[i] | 0; lo += w * 0x3d1; num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 0); } // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224 () { MPrime.call( this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); function P192 () { MPrime.call( this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); function P25519 () { // 2 ^ 255 - 19 MPrime.call( this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK (num) { // K = 0x13 var carry = 0; for (var i = 0; i < num.length; i++) { var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 26; num.words[i] = lo; carry = hi; } if (carry !== 0) { num.words[num.length++] = carry; } return num; }; // Exported mostly for testing purposes, use plain name instead BN._prime = function prime (name) { // Cached version of prime if (primes[name]) return primes[name]; var prime; if (name === 'k256') { prime = new K256(); } else if (name === 'p224') { prime = new P224(); } else if (name === 'p192') { prime = new P192(); } else if (name === 'p25519') { prime = new P25519(); } else { throw new Error('Unknown prime ' + name); } primes[name] = prime; return prime; }; // // Base reduction engine // function Red (m) { if (typeof m === 'string') { var prime = BN._prime(m); this.m = prime.p; this.prime = prime; } else { assert(m.gtn(1), 'modulus must be greater than 1'); this.m = m; this.prime = null; } } Red.prototype._verify1 = function _verify1 (a) { assert(a.negative === 0, 'red works only with positives'); assert(a.red, 'red works only with red numbers'); }; Red.prototype._verify2 = function _verify2 (a, b) { assert((a.negative | b.negative) === 0, 'red works only with positives'); assert(a.red && a.red === b.red, 'red works only with red numbers'); }; Red.prototype.imod = function imod (a) { if (this.prime) return this.prime.ireduce(a)._forceRed(this); move(a, a.umod(this.m)._forceRed(this)); return a; }; Red.prototype.neg = function neg (a) { if (a.isZero()) { return a.clone(); } return this.m.sub(a)._forceRed(this); }; Red.prototype.add = function add (a, b) { this._verify2(a, b); var res = a.add(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res._forceRed(this); }; Red.prototype.iadd = function iadd (a, b) { this._verify2(a, b); var res = a.iadd(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res; }; Red.prototype.sub = function sub (a, b) { this._verify2(a, b); var res = a.sub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res._forceRed(this); }; Red.prototype.isub = function isub (a, b) { this._verify2(a, b); var res = a.isub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res; }; Red.prototype.shl = function shl (a, num) { this._verify1(a); return this.imod(a.ushln(num)); }; Red.prototype.imul = function imul (a, b) { this._verify2(a, b); return this.imod(a.imul(b)); }; Red.prototype.mul = function mul (a, b) { this._verify2(a, b); return this.imod(a.mul(b)); }; Red.prototype.isqr = function isqr (a) { return this.imul(a, a.clone()); }; Red.prototype.sqr = function sqr (a) { return this.mul(a, a); }; Red.prototype.sqrt = function sqrt (a) { if (a.isZero()) return a.clone(); var mod3 = this.m.andln(3); assert(mod3 % 2 === 1); // Fast case if (mod3 === 3) { var pow = this.m.add(new BN(1)).iushrn(2); return this.pow(a, pow); } // Tonelli-Shanks algorithm (Totally unoptimized and slow) // // Find Q and S, that Q * 2 ^ S = (P - 1) var q = this.m.subn(1); var s = 0; while (!q.isZero() && q.andln(1) === 0) { s++; q.iushrn(1); } assert(!q.isZero()); var one = new BN(1).toRed(this); var nOne = one.redNeg(); // Find quadratic non-residue // NOTE: Max is such because of generalized Riemann hypothesis. var lpow = this.m.subn(1).iushrn(1); var z = this.m.bitLength(); z = new BN(2 * z * z).toRed(this); while (this.pow(z, lpow).cmp(nOne) !== 0) { z.redIAdd(nOne); } var c = this.pow(z, q); var r = this.pow(a, q.addn(1).iushrn(1)); var t = this.pow(a, q); var m = s; while (t.cmp(one) !== 0) { var tmp = t; for (var i = 0; tmp.cmp(one) !== 0; i++) { tmp = tmp.redSqr(); } assert(i < m); var b = this.pow(c, new BN(1).iushln(m - i - 1)); r = r.redMul(b); c = b.redSqr(); t = t.redMul(c); m = i; } return r; }; Red.prototype.invm = function invm (a) { var inv = a._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow (a, num) { if (num.isZero()) return new BN(1).toRed(this); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); wnd[1] = a; for (var i = 2; i < wnd.length; i++) { wnd[i] = this.mul(wnd[i - 1], a); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i = num.length - 1; i >= 0; i--) { var word = num.words[i]; for (var j = start - 1; j >= 0; j--) { var bit = (word >> j) & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo (num) { var r = num.umod(this.m); return r === num ? r.clone() : r; }; Red.prototype.convertFrom = function convertFrom (num) { var res = num.clone(); res.red = null; return res; }; // // Montgomery method engine // BN.mont = function mont (num) { return new Mont(num); }; function Mont (m) { Red.call(this, m); this.shift = this.m.bitLength(); if (this.shift % 26 !== 0) { this.shift += 26 - (this.shift % 26); } this.r = new BN(1).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo (num) { return this.imod(num.ushln(this.shift)); }; Mont.prototype.convertFrom = function convertFrom (num) { var r = this.imod(num.mul(this.rinv)); r.red = null; return r; }; Mont.prototype.imul = function imul (a, b) { if (a.isZero() || b.isZero()) { a.words[0] = 0; a.length = 1; return a; } var t = a.imul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.mul = function mul (a, b) { if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); var t = a.mul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.invm = function invm (a) { // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R var res = this.imod(a._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })( false || module, this); /***/ }), /***/ 9464: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const { fromCallback } = __webpack_require__(6957) const ModuleError = __webpack_require__(4473) const { getCallback, getOptions } = __webpack_require__(2520) const kPromise = Symbol('promise') const kStatus = Symbol('status') const kOperations = Symbol('operations') const kFinishClose = Symbol('finishClose') const kCloseCallbacks = Symbol('closeCallbacks') class AbstractChainedBatch { constructor (db) { if (typeof db !== 'object' || db === null) { const hint = db === null ? 'null' : typeof db throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`) } this[kOperations] = [] this[kCloseCallbacks] = [] this[kStatus] = 'open' this[kFinishClose] = this[kFinishClose].bind(this) this.db = db this.db.attachResource(this) this.nextTick = db.nextTick } get length () { return this[kOperations].length } put (key, value, options) { if (this[kStatus] !== 'open') { throw new ModuleError('Batch is not open: cannot call put() after write() or close()', { code: 'LEVEL_BATCH_NOT_OPEN' }) } const err = this.db._checkKey(key) || this.db._checkValue(value) if (err) throw err const db = options && options.sublevel != null ? options.sublevel : this.db const original = options const keyEncoding = db.keyEncoding(options && options.keyEncoding) const valueEncoding = db.valueEncoding(options && options.valueEncoding) const keyFormat = keyEncoding.format // Forward encoding options options = { ...options, keyEncoding: keyFormat, valueEncoding: valueEncoding.format } // Prevent double prefixing if (db !== this.db) { options.sublevel = null } const mappedKey = db.prefixKey(keyEncoding.encode(key), keyFormat) const mappedValue = valueEncoding.encode(value) this._put(mappedKey, mappedValue, options) this[kOperations].push({ ...original, type: 'put', key, value }) return this } _put (key, value, options) {} del (key, options) { if (this[kStatus] !== 'open') { throw new ModuleError('Batch is not open: cannot call del() after write() or close()', { code: 'LEVEL_BATCH_NOT_OPEN' }) } const err = this.db._checkKey(key) if (err) throw err const db = options && options.sublevel != null ? options.sublevel : this.db const original = options const keyEncoding = db.keyEncoding(options && options.keyEncoding) const keyFormat = keyEncoding.format // Forward encoding options options = { ...options, keyEncoding: keyFormat } // Prevent double prefixing if (db !== this.db) { options.sublevel = null } this._del(db.prefixKey(keyEncoding.encode(key), keyFormat), options) this[kOperations].push({ ...original, type: 'del', key }) return this } _del (key, options) {} clear () { if (this[kStatus] !== 'open') { throw new ModuleError('Batch is not open: cannot call clear() after write() or close()', { code: 'LEVEL_BATCH_NOT_OPEN' }) } this._clear() this[kOperations] = [] return this } _clear () {} write (options, callback) { callback = getCallback(options, callback) callback = fromCallback(callback, kPromise) options = getOptions(options) if (this[kStatus] !== 'open') { this.nextTick(callback, new ModuleError('Batch is not open: cannot call write() after write() or close()', { code: 'LEVEL_BATCH_NOT_OPEN' })) } else if (this.length === 0) { this.close(callback) } else { this[kStatus] = 'writing' this._write(options, (err) => { this[kStatus] = 'closing' this[kCloseCallbacks].push(() => callback(err)) // Emit after setting 'closing' status, because event may trigger a // db close which in turn triggers (idempotently) closing this batch. if (!err) this.db.emit('batch', this[kOperations]) this._close(this[kFinishClose]) }) } return callback[kPromise] } _write (options, callback) {} close (callback) { callback = fromCallback(callback, kPromise) if (this[kStatus] === 'closing') { this[kCloseCallbacks].push(callback) } else if (this[kStatus] === 'closed') { this.nextTick(callback) } else { this[kCloseCallbacks].push(callback) if (this[kStatus] !== 'writing') { this[kStatus] = 'closing' this._close(this[kFinishClose]) } } return callback[kPromise] } _close (callback) { this.nextTick(callback) } [kFinishClose] () { this[kStatus] = 'closed' this.db.detachResource(this) const callbacks = this[kCloseCallbacks] this[kCloseCallbacks] = [] for (const cb of callbacks) { cb() } } } exports.AbstractChainedBatch = AbstractChainedBatch /***/ }), /***/ 3961: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const { fromCallback } = __webpack_require__(6957) const ModuleError = __webpack_require__(4473) const { getOptions, getCallback } = __webpack_require__(2520) const kPromise = Symbol('promise') const kCallback = Symbol('callback') const kWorking = Symbol('working') const kHandleOne = Symbol('handleOne') const kHandleMany = Symbol('handleMany') const kAutoClose = Symbol('autoClose') const kFinishWork = Symbol('finishWork') const kReturnMany = Symbol('returnMany') const kClosing = Symbol('closing') const kHandleClose = Symbol('handleClose') const kClosed = Symbol('closed') const kCloseCallbacks = Symbol('closeCallbacks') const kKeyEncoding = Symbol('keyEncoding') const kValueEncoding = Symbol('valueEncoding') const kAbortOnClose = Symbol('abortOnClose') const kLegacy = Symbol('legacy') const kKeys = Symbol('keys') const kValues = Symbol('values') const kLimit = Symbol('limit') const kCount = Symbol('count') const emptyOptions = Object.freeze({}) const noop = () => {} let warnedEnd = false // This class is an internal utility for common functionality between AbstractIterator, // AbstractKeyIterator and AbstractValueIterator. It's not exported. class CommonIterator { constructor (db, options, legacy) { if (typeof db !== 'object' || db === null) { const hint = db === null ? 'null' : typeof db throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`) } if (typeof options !== 'object' || options === null) { throw new TypeError('The second argument must be an options object') } this[kClosed] = false this[kCloseCallbacks] = [] this[kWorking] = false this[kClosing] = false this[kAutoClose] = false this[kCallback] = null this[kHandleOne] = this[kHandleOne].bind(this) this[kHandleMany] = this[kHandleMany].bind(this) this[kHandleClose] = this[kHandleClose].bind(this) this[kKeyEncoding] = options[kKeyEncoding] this[kValueEncoding] = options[kValueEncoding] this[kLegacy] = legacy this[kLimit] = Number.isInteger(options.limit) && options.limit >= 0 ? options.limit : Infinity this[kCount] = 0 // Undocumented option to abort pending work on close(). Used by the // many-level module as a temporary solution to a blocked close(). // TODO (next major): consider making this the default behavior. Native // implementations should have their own logic to safely close iterators. this[kAbortOnClose] = !!options.abortOnClose this.db = db this.db.attachResource(this) this.nextTick = db.nextTick } get count () { return this[kCount] } get limit () { return this[kLimit] } next (callback) { let promise if (callback === undefined) { promise = new Promise((resolve, reject) => { callback = (err, key, value) => { if (err) reject(err) else if (!this[kLegacy]) resolve(key) else if (key === undefined && value === undefined) resolve() else resolve([key, value]) } }) } else if (typeof callback !== 'function') { throw new TypeError('Callback must be a function') } if (this[kClosing]) { this.nextTick(callback, new ModuleError('Iterator is not open: cannot call next() after close()', { code: 'LEVEL_ITERATOR_NOT_OPEN' })) } else if (this[kWorking]) { this.nextTick(callback, new ModuleError('Iterator is busy: cannot call next() until previous call has completed', { code: 'LEVEL_ITERATOR_BUSY' })) } else { this[kWorking] = true this[kCallback] = callback if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleOne], null) else this._next(this[kHandleOne]) } return promise } _next (callback) { this.nextTick(callback) } nextv (size, options, callback) { callback = getCallback(options, callback) callback = fromCallback(callback, kPromise) options = getOptions(options, emptyOptions) if (!Number.isInteger(size)) { this.nextTick(callback, new TypeError("The first argument 'size' must be an integer")) return callback[kPromise] } if (this[kClosing]) { this.nextTick(callback, new ModuleError('Iterator is not open: cannot call nextv() after close()', { code: 'LEVEL_ITERATOR_NOT_OPEN' })) } else if (this[kWorking]) { this.nextTick(callback, new ModuleError('Iterator is busy: cannot call nextv() until previous call has completed', { code: 'LEVEL_ITERATOR_BUSY' })) } else { if (size < 1) size = 1 if (this[kLimit] < Infinity) size = Math.min(size, this[kLimit] - this[kCount]) this[kWorking] = true this[kCallback] = callback if (size <= 0) this.nextTick(this[kHandleMany], null, []) else this._nextv(size, options, this[kHandleMany]) } return callback[kPromise] } _nextv (size, options, callback) { const acc = [] const onnext = (err, key, value) => { if (err) { return callback(err) } else if (this[kLegacy] ? key === undefined && value === undefined : key === undefined) { return callback(null, acc) } acc.push(this[kLegacy] ? [key, value] : key) if (acc.length === size) { callback(null, acc) } else { this._next(onnext) } } this._next(onnext) } all (options, callback) { callback = getCallback(options, callback) callback = fromCallback(callback, kPromise) options = getOptions(options, emptyOptions) if (this[kClosing]) { this.nextTick(callback, new ModuleError('Iterator is not open: cannot call all() after close()', { code: 'LEVEL_ITERATOR_NOT_OPEN' })) } else if (this[kWorking]) { this.nextTick(callback, new ModuleError('Iterator is busy: cannot call all() until previous call has completed', { code: 'LEVEL_ITERATOR_BUSY' })) } else { this[kWorking] = true this[kCallback] = callback this[kAutoClose] = true if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleMany], null, []) else this._all(options, this[kHandleMany]) } return callback[kPromise] } _all (options, callback) { // Must count here because we're directly calling _nextv() let count = this[kCount] const acc = [] const nextv = () => { // Not configurable, because implementations should optimize _all(). const size = this[kLimit] < Infinity ? Math.min(1e3, this[kLimit] - count) : 1e3 if (size <= 0) { this.nextTick(callback, null, acc) } else { this._nextv(size, emptyOptions, onnextv) } } const onnextv = (err, items) => { if (err) { callback(err) } else if (items.length === 0) { callback(null, acc) } else { acc.push.apply(acc, items) count += items.length nextv() } } nextv() } [kFinishWork] () { const cb = this[kCallback] // Callback will be null if work was aborted on close if (this[kAbortOnClose] && cb === null) return noop this[kWorking] = false this[kCallback] = null if (this[kClosing]) this._close(this[kHandleClose]) return cb } [kReturnMany] (cb, err, items) { if (this[kAutoClose]) { this.close(cb.bind(null, err, items)) } else { cb(err, items) } } seek (target, options) { options = getOptions(options, emptyOptions) if (this[kClosing]) { // Don't throw here, to be kind to implementations that wrap // another db and don't necessarily control when the db is closed } else if (this[kWorking]) { throw new ModuleError('Iterator is busy: cannot call seek() until next() has completed', { code: 'LEVEL_ITERATOR_BUSY' }) } else { const keyEncoding = this.db.keyEncoding(options.keyEncoding || this[kKeyEncoding]) const keyFormat = keyEncoding.format if (options.keyEncoding !== keyFormat) { options = { ...options, keyEncoding: keyFormat } } const mapped = this.db.prefixKey(keyEncoding.encode(target), keyFormat) this._seek(mapped, options) } } _seek (target, options) { throw new ModuleError('Iterator does not support seek()', { code: 'LEVEL_NOT_SUPPORTED' }) } close (callback) { callback = fromCallback(callback, kPromise) if (this[kClosed]) { this.nextTick(callback) } else if (this[kClosing]) { this[kCloseCallbacks].push(callback) } else { this[kClosing] = true this[kCloseCallbacks].push(callback) if (!this[kWorking]) { this._close(this[kHandleClose]) } else if (this[kAbortOnClose]) { // Don't wait for work to finish. Subsequently ignore the result. const cb = this[kFinishWork]() cb(new ModuleError('Aborted on iterator close()', { code: 'LEVEL_ITERATOR_NOT_OPEN' })) } } return callback[kPromise] } _close (callback) { this.nextTick(callback) } [kHandleClose] () { this[kClosed] = true this.db.detachResource(this) const callbacks = this[kCloseCallbacks] this[kCloseCallbacks] = [] for (const cb of callbacks) { cb() } } async * [Symbol.asyncIterator] () { try { let item while ((item = (await this.next())) !== undefined) { yield item } } finally { if (!this[kClosed]) await this.close() } } } // For backwards compatibility this class is not (yet) called AbstractEntryIterator. class AbstractIterator extends CommonIterator { constructor (db, options) { super(db, options, true) this[kKeys] = options.keys !== false this[kValues] = options.values !== false } [kHandleOne] (err, key, value) { const cb = this[kFinishWork]() if (err) return cb(err) try { key = this[kKeys] && key !== undefined ? this[kKeyEncoding].decode(key) : undefined value = this[kValues] && value !== undefined ? this[kValueEncoding].decode(value) : undefined } catch (err) { return cb(new IteratorDecodeError('entry', err)) } if (!(key === undefined && value === undefined)) { this[kCount]++ } cb(null, key, value) } [kHandleMany] (err, entries) { const cb = this[kFinishWork]() if (err) return this[kReturnMany](cb, err) try { for (const entry of entries) { const key = entry[0] const value = entry[1] entry[0] = this[kKeys] && key !== undefined ? this[kKeyEncoding].decode(key) : undefined entry[1] = this[kValues] && value !== undefined ? this[kValueEncoding].decode(value) : undefined } } catch (err) { return this[kReturnMany](cb, new IteratorDecodeError('entries', err)) } this[kCount] += entries.length this[kReturnMany](cb, null, entries) } end (callback) { if (!warnedEnd && typeof console !== 'undefined') { warnedEnd = true console.warn(new ModuleError( 'The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version', { code: 'LEVEL_LEGACY' } )) } return this.close(callback) } } class AbstractKeyIterator extends CommonIterator { constructor (db, options) { super(db, options, false) } [kHandleOne] (err, key) { const cb = this[kFinishWork]() if (err) return cb(err) try { key = key !== undefined ? this[kKeyEncoding].decode(key) : undefined } catch (err) { return cb(new IteratorDecodeError('key', err)) } if (key !== undefined) this[kCount]++ cb(null, key) } [kHandleMany] (err, keys) { const cb = this[kFinishWork]() if (err) return this[kReturnMany](cb, err) try { for (let i = 0; i < keys.length; i++) { const key = keys[i] keys[i] = key !== undefined ? this[kKeyEncoding].decode(key) : undefined } } catch (err) { return this[kReturnMany](cb, new IteratorDecodeError('keys', err)) } this[kCount] += keys.length this[kReturnMany](cb, null, keys) } } class AbstractValueIterator extends CommonIterator { constructor (db, options) { super(db, options, false) } [kHandleOne] (err, value) { const cb = this[kFinishWork]() if (err) return cb(err) try { value = value !== undefined ? this[kValueEncoding].decode(value) : undefined } catch (err) { return cb(new IteratorDecodeError('value', err)) } if (value !== undefined) this[kCount]++ cb(null, value) } [kHandleMany] (err, values) { const cb = this[kFinishWork]() if (err) return this[kReturnMany](cb, err) try { for (let i = 0; i < values.length; i++) { const value = values[i] values[i] = value !== undefined ? this[kValueEncoding].decode(value) : undefined } } catch (err) { return this[kReturnMany](cb, new IteratorDecodeError('values', err)) } this[kCount] += values.length this[kReturnMany](cb, null, values) } } // Internal utility, not typed or exported class IteratorDecodeError extends ModuleError { constructor (subject, cause) { super(`Iterator could not decode ${subject}`, { code: 'LEVEL_DECODE_ERROR', cause }) } } // To help migrating to abstract-level for (const k of ['_ended property', '_nexting property', '_end method']) { Object.defineProperty(AbstractIterator.prototype, k.split(' ')[0], { get () { throw new ModuleError(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) }, set () { throw new ModuleError(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) } }) } // Exposed so that AbstractLevel can set these options AbstractIterator.keyEncoding = kKeyEncoding AbstractIterator.valueEncoding = kValueEncoding exports.AbstractIterator = AbstractIterator exports.AbstractKeyIterator = AbstractKeyIterator exports.AbstractValueIterator = AbstractValueIterator /***/ }), /***/ 9071: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const { supports } = __webpack_require__(1675) const { Transcoder } = __webpack_require__(8499) const { EventEmitter } = __webpack_require__(7187) const { fromCallback } = __webpack_require__(6957) const ModuleError = __webpack_require__(4473) const { AbstractIterator } = __webpack_require__(3961) const { DefaultKeyIterator, DefaultValueIterator } = __webpack_require__(5429) const { DeferredIterator, DeferredKeyIterator, DeferredValueIterator } = __webpack_require__(593) const { DefaultChainedBatch } = __webpack_require__(4765) const { getCallback, getOptions } = __webpack_require__(2520) const rangeOptions = __webpack_require__(56) const kPromise = Symbol('promise') const kLanded = Symbol('landed') const kResources = Symbol('resources') const kCloseResources = Symbol('closeResources') const kOperations = Symbol('operations') const kUndefer = Symbol('undefer') const kDeferOpen = Symbol('deferOpen') const kOptions = Symbol('options') const kStatus = Symbol('status') const kDefaultOptions = Symbol('defaultOptions') const kTranscoder = Symbol('transcoder') const kKeyEncoding = Symbol('keyEncoding') const kValueEncoding = Symbol('valueEncoding') const noop = () => {} class AbstractLevel extends EventEmitter { constructor (manifest, options) { super() if (typeof manifest !== 'object' || manifest === null) { throw new TypeError("The first argument 'manifest' must be an object") } options = getOptions(options) const { keyEncoding, valueEncoding, passive, ...forward } = options this[kResources] = new Set() this[kOperations] = [] this[kDeferOpen] = true this[kOptions] = forward this[kStatus] = 'opening' this.supports = supports(manifest, { status: true, promises: true, clear: true, getMany: true, deferredOpen: true, // TODO (next major): add seek snapshots: manifest.snapshots !== false, permanence: manifest.permanence !== false, // TODO: remove from level-supports because it's always supported keyIterator: true, valueIterator: true, iteratorNextv: true, iteratorAll: true, encodings: manifest.encodings || {}, events: Object.assign({}, manifest.events, { opening: true, open: true, closing: true, closed: true, put: true, del: true, batch: true, clear: true }) }) this[kTranscoder] = new Transcoder(formats(this)) this[kKeyEncoding] = this[kTranscoder].encoding(keyEncoding || 'utf8') this[kValueEncoding] = this[kTranscoder].encoding(valueEncoding || 'utf8') // Add custom and transcoder encodings to manifest for (const encoding of this[kTranscoder].encodings()) { if (!this.supports.encodings[encoding.commonName]) { this.supports.encodings[encoding.commonName] = true } } this[kDefaultOptions] = { empty: Object.freeze({}), entry: Object.freeze({ keyEncoding: this[kKeyEncoding].commonName, valueEncoding: this[kValueEncoding].commonName }), key: Object.freeze({ keyEncoding: this[kKeyEncoding].commonName }) } // Let subclass finish its constructor this.nextTick(() => { if (this[kDeferOpen]) { this.open({ passive: false }, noop) } }) } get status () { return this[kStatus] } keyEncoding (encoding) { return this[kTranscoder].encoding(encoding != null ? encoding : this[kKeyEncoding]) } valueEncoding (encoding) { return this[kTranscoder].encoding(encoding != null ? encoding : this[kValueEncoding]) } open (options, callback) { callback = getCallback(options, callback) callback = fromCallback(callback, kPromise) options = { ...this[kOptions], ...getOptions(options) } options.createIfMissing = options.createIfMissing !== false options.errorIfExists = !!options.errorIfExists const maybeOpened = (err) => { if (this[kStatus] === 'closing' || this[kStatus] === 'opening') { // Wait until pending state changes are done this.once(kLanded, err ? () => maybeOpened(err) : maybeOpened) } else if (this[kStatus] !== 'open') { callback(new ModuleError('Database is not open', { code: 'LEVEL_DATABASE_NOT_OPEN', cause: err })) } else { callback() } } if (options.passive) { if (this[kStatus] === 'opening') { this.once(kLanded, maybeOpened) } else { this.nextTick(maybeOpened) } } else if (this[kStatus] === 'closed' || this[kDeferOpen]) { this[kDeferOpen] = false this[kStatus] = 'opening' this.emit('opening') this._open(options, (err) => { if (err) { this[kStatus] = 'closed' // Resources must be safe to close in any db state this[kCloseResources](() => { this.emit(kLanded) maybeOpened(err) }) this[kUndefer]() return } this[kStatus] = 'open' this[kUndefer]() this.emit(kLanded) // Only emit public event if pending state changes are done if (this[kStatus] === 'open') this.emit('open') // TODO (next major): remove this alias if (this[kStatus] === 'open') this.emit('ready') maybeOpened() }) } else if (this[kStatus] === 'open') { this.nextTick(maybeOpened) } else { this.once(kLanded, () => this.open(options, callback)) } return callback[kPromise] } _open (options, callback) { this.nextTick(callback) } close (callback) { callback = fromCallback(callback, kPromise) const maybeClosed = (err) => { if (this[kStatus] === 'opening' || this[kStatus] === 'closing') { // Wait until pending state changes are done this.once(kLanded, err ? maybeClosed(err) : maybeClosed) } else if (this[kStatus] !== 'closed') { callback(new ModuleError('Database is not closed', { code: 'LEVEL_DATABASE_NOT_CLOSED', cause: err })) } else { callback() } } if (this[kStatus] === 'open') { this[kStatus] = 'closing' this.emit('closing') const cancel = (err) => { this[kStatus] = 'open' this[kUndefer]() this.emit(kLanded) maybeClosed(err) } this[kCloseResources](() => { this._close((err) => { if (err) return cancel(err) this[kStatus] = 'closed' this[kUndefer]() this.emit(kLanded) // Only emit public event if pending state changes are done if (this[kStatus] === 'closed') this.emit('closed') maybeClosed() }) }) } else if (this[kStatus] === 'closed') { this.nextTick(maybeClosed) } else { this.once(kLanded, () => this.close(callback)) } return callback[kPromise] } [kCloseResources] (callback) { if (this[kResources].size === 0) { return this.nextTick(callback) } let pending = this[kResources].size let sync = true const next = () => { if (--pending === 0) { // We don't have tests for generic resources, so dezalgo if (sync) this.nextTick(callback) else callback() } } // In parallel so that all resources know they are closed for (const resource of this[kResources]) { resource.close(next) } sync = false this[kResources].clear() } _close (callback) { this.nextTick(callback) } get (key, options, callback) { callback = getCallback(options, callback) callback = fromCallback(callback, kPromise) options = getOptions(options, this[kDefaultOptions].entry) if (this[kStatus] === 'opening') { this.defer(() => this.get(key, options, callback)) return callback[kPromise] } if (maybeError(this, callback)) { return callback[kPromise] } const err = this._checkKey(key) if (err) { this.nextTick(callback, err) return callback[kPromise] } const keyEncoding = this.keyEncoding(options.keyEncoding) const valueEncoding = this.valueEncoding(options.valueEncoding) const keyFormat = keyEncoding.format const valueFormat = valueEncoding.format // Forward encoding options to the underlying store if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) { // Avoid spread operator because of https://bugs.chromium.org/p/chromium/issues/detail?id=1204540 options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat }) } this._get(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err, value) => { if (err) { // Normalize not found error for backwards compatibility with abstract-leveldown and level(up) if (err.code === 'LEVEL_NOT_FOUND' || err.notFound || /NotFound/i.test(err)) { if (!err.code) err.code = 'LEVEL_NOT_FOUND' // Preferred way going forward if (!err.notFound) err.notFound = true // Same as level-errors if (!err.status) err.status = 404 // Same as level-errors } return callback(err) } try { value = valueEncoding.decode(value) } catch (err) { return callback(new ModuleError('Could not decode value', { code: 'LEVEL_DECODE_ERROR', cause: err })) } callback(null, value) }) return callback[kPromise] } _get (key, options, callback) { this.nextTick(callback, new Error('NotFound')) } getMany (keys, options, callback) { callback = getCallback(options, callback) callback = fromCallback(callback, kPromise) options = getOptions(options, this[kDefaultOptions].entry) if (this[kStatus] === 'opening') { this.defer(() => this.getMany(keys, options, callback)) return callback[kPromise] } if (maybeError(this, callback)) { return callback[kPromise] } if (!Array.isArray(keys)) { this.nextTick(callback, new TypeError("The first argument 'keys' must be an array")) return callback[kPromise] } if (keys.length === 0) { this.nextTick(callback, null, []) return callback[kPromise] } const keyEncoding = this.keyEncoding(options.keyEncoding) const valueEncoding = this.valueEncoding(options.valueEncoding) const keyFormat = keyEncoding.format const valueFormat = valueEncoding.format // Forward encoding options if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) { options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat }) } const mappedKeys = new Array(keys.length) for (let i = 0; i < keys.length; i++) { const key = keys[i] const err = this._checkKey(key) if (err) { this.nextTick(callback, err) return callback[kPromise] } mappedKeys[i] = this.prefixKey(keyEncoding.encode(key), keyFormat) } this._getMany(mappedKeys, options, (err, values) => { if (err) return callback(err) try { for (let i = 0; i < values.length; i++) { if (values[i] !== undefined) { values[i] = valueEncoding.decode(values[i]) } } } catch (err) { return callback(new ModuleError(`Could not decode one or more of ${values.length} value(s)`, { code: 'LEVEL_DECODE_ERROR', cause: err })) } callback(null, values) }) return callback[kPromise] } _getMany (keys, options, callback) { this.nextTick(callback, null, new Array(keys.length).fill(undefined)) } put (key, value, options, callback) { callback = getCallback(options, callback) callback = fromCallback(callback, kPromise) options = getOptions(options, this[kDefaultOptions].entry) if (this[kStatus] === 'opening') { this.defer(() => this.put(key, value, options, callback)) return callback[kPromise] } if (maybeError(this, callback)) { return callback[kPromise] } const err = this._checkKey(key) || this._checkValue(value) if (err) { this.nextTick(callback, err) return callback[kPromise] } const keyEncoding = this.keyEncoding(options.keyEncoding) const valueEncoding = this.valueEncoding(options.valueEncoding) const keyFormat = keyEncoding.format const valueFormat = valueEncoding.format // Forward encoding options if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) { options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat }) } const mappedKey = this.prefixKey(keyEncoding.encode(key), keyFormat) const mappedValue = valueEncoding.encode(value) this._put(mappedKey, mappedValue, options, (err) => { if (err) return callback(err) this.emit('put', key, value) callback() }) return callback[kPromise] } _put (key, value, options, callback) { this.nextTick(callback) } del (key, options, callback) { callback = getCallback(options, callback) callback = fromCallback(callback, kPromise) options = getOptions(options, this[kDefaultOptions].key) if (this[kStatus] === 'opening') { this.defer(() => this.del(key, options, callback)) return callback[kPromise] } if (maybeError(this, callback)) { return callback[kPromise] } const err = this._checkKey(key) if (err) { this.nextTick(callback, err) return callback[kPromise] } const keyEncoding = this.keyEncoding(options.keyEncoding) const keyFormat = keyEncoding.format // Forward encoding options if (options.keyEncoding !== keyFormat) { options = Object.assign({}, options, { keyEncoding: keyFormat }) } this._del(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err) => { if (err) return callback(err) this.emit('del', key) callback() }) return callback[kPromise] } _del (key, options, callback) { this.nextTick(callback) } batch (operations, options, callback) { if (!arguments.length) { if (this[kStatus] === 'opening') return new DefaultChainedBatch(this) if (this[kStatus] !== 'open') { throw new ModuleError('Database is not open', { code: 'LEVEL_DATABASE_NOT_OPEN' }) } return this._chainedBatch() } if (typeof operations === 'function') callback = operations else callback = getCallback(options, callback) callback = fromCallback(callback, kPromise) options = getOptions(options, this[kDefaultOptions].empty) if (this[kStatus] === 'opening') { this.defer(() => this.batch(operations, options, callback)) return callback[kPromise] } if (maybeError(this, callback)) { return callback[kPromise] } if (!Array.isArray(operations)) { this.nextTick(callback, new TypeError("The first argument 'operations' must be an array")) return callback[kPromise] } if (operations.length === 0) { this.nextTick(callback) return callback[kPromise] } const mapped = new Array(operations.length) const { keyEncoding: ke, valueEncoding: ve, ...forward } = options for (let i = 0; i < operations.length; i++) { if (typeof operations[i] !== 'object' || operations[i] === null) { this.nextTick(callback, new TypeError('A batch operation must be an object')) return callback[kPromise] } const op = Object.assign({}, operations[i]) if (op.type !== 'put' && op.type !== 'del') { this.nextTick(callback, new TypeError("A batch operation must have a type property that is 'put' or 'del'")) return callback[kPromise] } const err = this._checkKey(op.key) if (err) { this.nextTick(callback, err) return callback[kPromise] } const db = op.sublevel != null ? op.sublevel : this const keyEncoding = db.keyEncoding(op.keyEncoding || ke) const keyFormat = keyEncoding.format op.key = db.prefixKey(keyEncoding.encode(op.key), keyFormat) op.keyEncoding = keyFormat if (op.type === 'put') { const valueErr = this._checkValue(op.value) if (valueErr) { this.nextTick(callback, valueErr) return callback[kPromise] } const valueEncoding = db.valueEncoding(op.valueEncoding || ve) op.value = valueEncoding.encode(op.value) op.valueEncoding = valueEncoding.format } // Prevent double prefixing if (db !== this) { op.sublevel = null } mapped[i] = op } this._batch(mapped, forward, (err) => { if (err) return callback(err) this.emit('batch', operations) callback() }) return callback[kPromise] } _batch (operations, options, callback) { this.nextTick(callback) } sublevel (name, options) { return this._sublevel(name, AbstractSublevel.defaults(options)) } _sublevel (name, options) { return new AbstractSublevel(this, name, options) } prefixKey (key, keyFormat) { return key } clear (options, callback) { callback = getCallback(options, callback) callback = fromCallback(callback, kPromise) options = getOptions(options, this[kDefaultOptions].empty) if (this[kStatus] === 'opening') { this.defer(() => this.clear(options, callback)) return callback[kPromise] } if (maybeError(this, callback)) { return callback[kPromise] } const original = options const keyEncoding = this.keyEncoding(options.keyEncoding) options = rangeOptions(options, keyEncoding) options.keyEncoding = keyEncoding.format if (options.limit === 0) { this.nextTick(callback) } else { this._clear(options, (err) => { if (err) return callback(err) this.emit('clear', original) callback() }) } return callback[kPromise] } _clear (options, callback) { this.nextTick(callback) } iterator (options) { const keyEncoding = this.keyEncoding(options && options.keyEncoding) const valueEncoding = this.valueEncoding(options && options.valueEncoding) options = rangeOptions(options, keyEncoding) options.keys = options.keys !== false options.values = options.values !== false // We need the original encoding options in AbstractIterator in order to decode data options[AbstractIterator.keyEncoding] = keyEncoding options[AbstractIterator.valueEncoding] = valueEncoding // Forward encoding options to private API options.keyEncoding = keyEncoding.format options.valueEncoding = valueEncoding.format if (this[kStatus] === 'opening') { return new DeferredIterator(this, options) } else if (this[kStatus] !== 'open') { throw new ModuleError('Database is not open', { code: 'LEVEL_DATABASE_NOT_OPEN' }) } return this._iterator(options) } _iterator (options) { return new AbstractIterator(this, options) } keys (options) { // Also include valueEncoding (though unused) because we may fallback to _iterator() const keyEncoding = this.keyEncoding(options && options.keyEncoding) const valueEncoding = this.valueEncoding(options && options.valueEncoding) options = rangeOptions(options, keyEncoding) // We need the original encoding options in AbstractKeyIterator in order to decode data options[AbstractIterator.keyEncoding] = keyEncoding options[AbstractIterator.valueEncoding] = valueEncoding // Forward encoding options to private API options.keyEncoding = keyEncoding.format options.valueEncoding = valueEncoding.format if (this[kStatus] === 'opening') { return new DeferredKeyIterator(this, options) } else if (this[kStatus] !== 'open') { throw new ModuleError('Database is not open', { code: 'LEVEL_DATABASE_NOT_OPEN' }) } return this._keys(options) } _keys (options) { return new DefaultKeyIterator(this, options) } values (options) { const keyEncoding = this.keyEncoding(options && options.keyEncoding) const valueEncoding = this.valueEncoding(options && options.valueEncoding) options = rangeOptions(options, keyEncoding) // We need the original encoding options in AbstractValueIterator in order to decode data options[AbstractIterator.keyEncoding] = keyEncoding options[AbstractIterator.valueEncoding] = valueEncoding // Forward encoding options to private API options.keyEncoding = keyEncoding.format options.valueEncoding = valueEncoding.format if (this[kStatus] === 'opening') { return new DeferredValueIterator(this, options) } else if (this[kStatus] !== 'open') { throw new ModuleError('Database is not open', { code: 'LEVEL_DATABASE_NOT_OPEN' }) } return this._values(options) } _values (options) { return new DefaultValueIterator(this, options) } defer (fn) { if (typeof fn !== 'function') { throw new TypeError('The first argument must be a function') } this[kOperations].push(fn) } [kUndefer] () { if (this[kOperations].length === 0) { return } const operations = this[kOperations] this[kOperations] = [] for (const op of operations) { op() } } // TODO: docs and types attachResource (resource) { if (typeof resource !== 'object' || resource === null || typeof resource.close !== 'function') { throw new TypeError('The first argument must be a resource object') } this[kResources].add(resource) } // TODO: docs and types detachResource (resource) { this[kResources].delete(resource) } _chainedBatch () { return new DefaultChainedBatch(this) } _checkKey (key) { if (key === null || key === undefined) { return new ModuleError('Key cannot be null or undefined', { code: 'LEVEL_INVALID_KEY' }) } } _checkValue (value) { if (value === null || value === undefined) { return new ModuleError('Value cannot be null or undefined', { code: 'LEVEL_INVALID_VALUE' }) } } } // Expose browser-compatible nextTick for dependents // TODO: after we drop node 10, also use queueMicrotask in node AbstractLevel.prototype.nextTick = __webpack_require__(6909) const { AbstractSublevel } = __webpack_require__(9650)({ AbstractLevel }) exports.AbstractLevel = AbstractLevel exports.AbstractSublevel = AbstractSublevel const maybeError = function (db, callback) { if (db[kStatus] !== 'open') { db.nextTick(callback, new ModuleError('Database is not open', { code: 'LEVEL_DATABASE_NOT_OPEN' })) return true } return false } const formats = function (db) { return Object.keys(db.supports.encodings) .filter(k => !!db.supports.encodings[k]) } /***/ }), /***/ 875: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; exports.AbstractLevel = __webpack_require__(9071).AbstractLevel exports.AbstractSublevel = __webpack_require__(9071).AbstractSublevel exports.AbstractIterator = __webpack_require__(3961).AbstractIterator exports.AbstractKeyIterator = __webpack_require__(3961).AbstractKeyIterator exports.AbstractValueIterator = __webpack_require__(3961).AbstractValueIterator exports.AbstractChainedBatch = __webpack_require__(9464).AbstractChainedBatch /***/ }), /***/ 2970: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = __webpack_require__(3961) const kUnfix = Symbol('unfix') const kIterator = Symbol('iterator') const kHandleOne = Symbol('handleOne') const kHandleMany = Symbol('handleMany') const kCallback = Symbol('callback') // TODO: unfix natively if db supports it class AbstractSublevelIterator extends AbstractIterator { constructor (db, options, iterator, unfix) { super(db, options) this[kIterator] = iterator this[kUnfix] = unfix this[kHandleOne] = this[kHandleOne].bind(this) this[kHandleMany] = this[kHandleMany].bind(this) this[kCallback] = null } [kHandleOne] (err, key, value) { const callback = this[kCallback] if (err) return callback(err) if (key !== undefined) key = this[kUnfix](key) callback(err, key, value) } [kHandleMany] (err, entries) { const callback = this[kCallback] if (err) return callback(err) for (const entry of entries) { const key = entry[0] if (key !== undefined) entry[0] = this[kUnfix](key) } callback(err, entries) } } class AbstractSublevelKeyIterator extends AbstractKeyIterator { constructor (db, options, iterator, unfix) { super(db, options) this[kIterator] = iterator this[kUnfix] = unfix this[kHandleOne] = this[kHandleOne].bind(this) this[kHandleMany] = this[kHandleMany].bind(this) this[kCallback] = null } [kHandleOne] (err, key) { const callback = this[kCallback] if (err) return callback(err) if (key !== undefined) key = this[kUnfix](key) callback(err, key) } [kHandleMany] (err, keys) { const callback = this[kCallback] if (err) return callback(err) for (let i = 0; i < keys.length; i++) { const key = keys[i] if (key !== undefined) keys[i] = this[kUnfix](key) } callback(err, keys) } } class AbstractSublevelValueIterator extends AbstractValueIterator { constructor (db, options, iterator) { super(db, options) this[kIterator] = iterator } } for (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator]) { Iterator.prototype._next = function (callback) { this[kCallback] = callback this[kIterator].next(this[kHandleOne]) } Iterator.prototype._nextv = function (size, options, callback) { this[kCallback] = callback this[kIterator].nextv(size, options, this[kHandleMany]) } Iterator.prototype._all = function (options, callback) { this[kCallback] = callback this[kIterator].all(options, this[kHandleMany]) } } for (const Iterator of [AbstractSublevelValueIterator]) { Iterator.prototype._next = function (callback) { this[kIterator].next(callback) } Iterator.prototype._nextv = function (size, options, callback) { this[kIterator].nextv(size, options, callback) } Iterator.prototype._all = function (options, callback) { this[kIterator].all(options, callback) } } for (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator, AbstractSublevelValueIterator]) { Iterator.prototype._seek = function (target, options) { this[kIterator].seek(target, options) } Iterator.prototype._close = function (callback) { this[kIterator].close(callback) } } exports.AbstractSublevelIterator = AbstractSublevelIterator exports.AbstractSublevelKeyIterator = AbstractSublevelKeyIterator exports.AbstractSublevelValueIterator = AbstractSublevelValueIterator /***/ }), /***/ 9650: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; const ModuleError = __webpack_require__(4473) const { Buffer } = __webpack_require__(8764) || {} const { AbstractSublevelIterator, AbstractSublevelKeyIterator, AbstractSublevelValueIterator } = __webpack_require__(2970) const kPrefix = Symbol('prefix') const kUpperBound = Symbol('upperBound') const kPrefixRange = Symbol('prefixRange') const kParent = Symbol('parent') const kUnfix = Symbol('unfix') const textEncoder = new TextEncoder() const defaults = { separator: '!' } // Wrapped to avoid circular dependency module.exports = function ({ AbstractLevel }) { class AbstractSublevel extends AbstractLevel { static defaults (options) { // To help migrating from subleveldown to abstract-level if (typeof options === 'string') { throw new ModuleError('The subleveldown string shorthand for { separator } has been removed', { code: 'LEVEL_LEGACY' }) } else if (options && options.open) { throw new ModuleError('The subleveldown open option has been removed', { code: 'LEVEL_LEGACY' }) } if (options == null) { return defaults } else if (!options.separator) { return { ...options, separator: '!' } } else { return options } } // TODO: add autoClose option, which if true, does parent.attachResource(this) constructor (db, name, options) { // Don't forward AbstractSublevel options to AbstractLevel const { separator, manifest, ...forward } = AbstractSublevel.defaults(options) name = trim(name, separator) // Reserve one character between separator and name to give us an upper bound const reserved = separator.charCodeAt(0) + 1 const parent = db[kParent] || db // Keys should sort like ['!a!', '!a!!a!', '!a"', '!aa!', '!b!']. // Use ASCII for consistent length between string, Buffer and Uint8Array if (!textEncoder.encode(name).every(x => x > reserved && x < 127)) { throw new ModuleError(`Prefix must use bytes > ${reserved} < ${127}`, { code: 'LEVEL_INVALID_PREFIX' }) } super(mergeManifests(parent, manifest), forward) const prefix = (db.prefix || '') + separator + name + separator const upperBound = prefix.slice(0, -1) + String.fromCharCode(reserved) this[kParent] = parent this[kPrefix] = new MultiFormat(prefix) this[kUpperBound] = new MultiFormat(upperBound) this[kUnfix] = new Unfixer() this.nextTick = parent.nextTick } prefixKey (key, keyFormat) { if (keyFormat === 'utf8') { return this[kPrefix].utf8 + key } else if (key.byteLength === 0) { // Fast path for empty key (no copy) return this[kPrefix][keyFormat] } else if (keyFormat === 'view') { const view = this[kPrefix].view const result = new Uint8Array(view.byteLength + key.byteLength) result.set(view, 0) result.set(key, view.byteLength) return result } else { const buffer = this[kPrefix].buffer return Buffer.concat([buffer, key], buffer.byteLength + key.byteLength) } } // Not exposed for now. [kPrefixRange] (range, keyFormat) { if (range.gte !== undefined) { range.gte = this.prefixKey(range.gte, keyFormat) } else if (range.gt !== undefined) { range.gt = this.prefixKey(range.gt, keyFormat) } else { range.gte = this[kPrefix][keyFormat] } if (range.lte !== undefined) { range.lte = this.prefixKey(range.lte, keyFormat) } else if (range.lt !== undefined) { range.lt = this.prefixKey(range.lt, keyFormat) } else { range.lte = this[kUpperBound][keyFormat] } } get prefix () { return this[kPrefix].utf8 } get db () { return this[kParent] } _open (options, callback) { // The parent db must open itself or be (re)opened by the user because // a sublevel should not initiate state changes on the rest of the db. this[kParent].open({ passive: true }, callback) } _put (key, value, options, callback) { this[kParent].put(key, value, options, callback) } _get (key, options, callback) { this[kParent].get(key, options, callback) } _getMany (keys, options, callback) { this[kParent].getMany(keys, options, callback) } _del (key, options, callback) { this[kParent].del(key, options, callback) } _batch (operations, options, callback) { this[kParent].batch(operations, options, callback) } _clear (options, callback) { // TODO (refactor): move to AbstractLevel this[kPrefixRange](options, options.keyEncoding) this[kParent].clear(options, callback) } _iterator (options) { // TODO (refactor): move to AbstractLevel this[kPrefixRange](options, options.keyEncoding) const iterator = this[kParent].iterator(options) const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding) return new AbstractSublevelIterator(this, options, iterator, unfix) } _keys (options) { this[kPrefixRange](options, options.keyEncoding) const iterator = this[kParent].keys(options) const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding) return new AbstractSublevelKeyIterator(this, options, iterator, unfix) } _values (options) { this[kPrefixRange](options, options.keyEncoding) const iterator = this[kParent].values(options) return new AbstractSublevelValueIterator(this, options, iterator) } } return { AbstractSublevel } } const mergeManifests = function (parent, manifest) { return { // Inherit manifest of parent db ...parent.supports, // Disable unsupported features createIfMissing: false, errorIfExists: false, // Unset additional events because we're not forwarding them events: {}, // Unset additional methods (like approximateSize) which we can't support here unless // the AbstractSublevel class is overridden by an implementation of `abstract-level`. additionalMethods: {}, // Inherit manifest of custom AbstractSublevel subclass. Such a class is not // allowed to override encodings. ...manifest, encodings: { utf8: supportsEncoding(parent, 'utf8'), buffer: supportsEncoding(parent, 'buffer'), view: supportsEncoding(parent, 'view') } } } const supportsEncoding = function (parent, encoding) { // Prefer a non-transcoded encoding for optimal performance return parent.supports.encodings[encoding] ? parent.keyEncoding(encoding).name === encoding : false } class MultiFormat { constructor (key) { this.utf8 = key this.view = textEncoder.encode(key) this.buffer = Buffer ? Buffer.from(this.view.buffer, 0, this.view.byteLength) : {} } } class Unfixer { constructor () { this.cache = new Map() } get (prefixLength, keyFormat) { let unfix = this.cache.get(keyFormat) if (unfix === undefined) { if (keyFormat === 'view') { unfix = function (prefixLength, key) { // Avoid Uint8Array#slice() because it copies return key.subarray(prefixLength) }.bind(null, prefixLength) } else { unfix = function (prefixLength, key) { // Avoid Buffer#subarray() because it's slow return key.slice(prefixLength) }.bind(null, prefixLength) } this.cache.set(keyFormat, unfix) } return unfix } } const trim = function (str, char) { let start = 0 let end = str.length while (start < end && str[start] === char) start++ while (end > start && str[end - 1] === char) end-- return str.slice(start, end) } /***/ }), /***/ 2520: /***/ (function(__unused_webpack_module, exports) { "use strict"; exports.getCallback = function (options, callback) { return typeof options === 'function' ? options : callback } exports.getOptions = function (options, def) { if (typeof options === 'object' && options !== null) { return options } if (def !== undefined) { return def } return {} } /***/ }), /***/ 4765: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const { AbstractChainedBatch } = __webpack_require__(9464) const ModuleError = __webpack_require__(4473) const kEncoded = Symbol('encoded') // Functional default for chained batch, with support of deferred open class DefaultChainedBatch extends AbstractChainedBatch { constructor (db) { super(db) this[kEncoded] = [] } _put (key, value, options) { this[kEncoded].push({ ...options, type: 'put', key, value }) } _del (key, options) { this[kEncoded].push({ ...options, type: 'del', key }) } _clear () { this[kEncoded] = [] } // Assumes this[kEncoded] cannot change after write() _write (options, callback) { if (this.db.status === 'opening') { this.db.defer(() => this._write(options, callback)) } else if (this.db.status === 'open') { if (this[kEncoded].length === 0) this.nextTick(callback) else this.db._batch(this[kEncoded], options, callback) } else { this.nextTick(callback, new ModuleError('Batch is not open: cannot call write() after write() or close()', { code: 'LEVEL_BATCH_NOT_OPEN' })) } } } exports.DefaultChainedBatch = DefaultChainedBatch /***/ }), /***/ 5429: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const { AbstractKeyIterator, AbstractValueIterator } = __webpack_require__(3961) const kIterator = Symbol('iterator') const kCallback = Symbol('callback') const kHandleOne = Symbol('handleOne') const kHandleMany = Symbol('handleMany') class DefaultKeyIterator extends AbstractKeyIterator { constructor (db, options) { super(db, options) this[kIterator] = db.iterator({ ...options, keys: true, values: false }) this[kHandleOne] = this[kHandleOne].bind(this) this[kHandleMany] = this[kHandleMany].bind(this) } } class DefaultValueIterator extends AbstractValueIterator { constructor (db, options) { super(db, options) this[kIterator] = db.iterator({ ...options, keys: false, values: true }) this[kHandleOne] = this[kHandleOne].bind(this) this[kHandleMany] = this[kHandleMany].bind(this) } } for (const Iterator of [DefaultKeyIterator, DefaultValueIterator]) { const keys = Iterator === DefaultKeyIterator const mapEntry = keys ? (entry) => entry[0] : (entry) => entry[1] Iterator.prototype._next = function (callback) { this[kCallback] = callback this[kIterator].next(this[kHandleOne]) } Iterator.prototype[kHandleOne] = function (err, key, value) { const callback = this[kCallback] if (err) callback(err) else callback(null, keys ? key : value) } Iterator.prototype._nextv = function (size, options, callback) { this[kCallback] = callback this[kIterator].nextv(size, options, this[kHandleMany]) } Iterator.prototype._all = function (options, callback) { this[kCallback] = callback this[kIterator].all(options, this[kHandleMany]) } Iterator.prototype[kHandleMany] = function (err, entries) { const callback = this[kCallback] if (err) callback(err) else callback(null, entries.map(mapEntry)) } Iterator.prototype._seek = function (target, options) { this[kIterator].seek(target, options) } Iterator.prototype._close = function (callback) { this[kIterator].close(callback) } } // Internal utilities, should be typed as AbstractKeyIterator and AbstractValueIterator exports.DefaultKeyIterator = DefaultKeyIterator exports.DefaultValueIterator = DefaultValueIterator /***/ }), /***/ 593: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = __webpack_require__(3961) const ModuleError = __webpack_require__(4473) const kNut = Symbol('nut') const kUndefer = Symbol('undefer') const kFactory = Symbol('factory') class DeferredIterator extends AbstractIterator { constructor (db, options) { super(db, options) this[kNut] = null this[kFactory] = () => db.iterator(options) this.db.defer(() => this[kUndefer]()) } } class DeferredKeyIterator extends AbstractKeyIterator { constructor (db, options) { super(db, options) this[kNut] = null this[kFactory] = () => db.keys(options) this.db.defer(() => this[kUndefer]()) } } class DeferredValueIterator extends AbstractValueIterator { constructor (db, options) { super(db, options) this[kNut] = null this[kFactory] = () => db.values(options) this.db.defer(() => this[kUndefer]()) } } for (const Iterator of [DeferredIterator, DeferredKeyIterator, DeferredValueIterator]) { Iterator.prototype[kUndefer] = function () { if (this.db.status === 'open') { this[kNut] = this[kFactory]() } } Iterator.prototype._next = function (callback) { if (this[kNut] !== null) { this[kNut].next(callback) } else if (this.db.status === 'opening') { this.db.defer(() => this._next(callback)) } else { this.nextTick(callback, new ModuleError('Iterator is not open: cannot call next() after close()', { code: 'LEVEL_ITERATOR_NOT_OPEN' })) } } Iterator.prototype._nextv = function (size, options, callback) { if (this[kNut] !== null) { this[kNut].nextv(size, options, callback) } else if (this.db.status === 'opening') { this.db.defer(() => this._nextv(size, options, callback)) } else { this.nextTick(callback, new ModuleError('Iterator is not open: cannot call nextv() after close()', { code: 'LEVEL_ITERATOR_NOT_OPEN' })) } } Iterator.prototype._all = function (options, callback) { if (this[kNut] !== null) { this[kNut].all(callback) } else if (this.db.status === 'opening') { this.db.defer(() => this._all(options, callback)) } else { this.nextTick(callback, new ModuleError('Iterator is not open: cannot call all() after close()', { code: 'LEVEL_ITERATOR_NOT_OPEN' })) } } Iterator.prototype._seek = function (target, options) { if (this[kNut] !== null) { // TODO: explain why we need _seek() rather than seek() here this[kNut]._seek(target, options) } else if (this.db.status === 'opening') { this.db.defer(() => this._seek(target, options)) } } Iterator.prototype._close = function (callback) { if (this[kNut] !== null) { this[kNut].close(callback) } else if (this.db.status === 'opening') { this.db.defer(() => this._close(callback)) } else { this.nextTick(callback) } } } exports.DeferredIterator = DeferredIterator exports.DeferredKeyIterator = DeferredKeyIterator exports.DeferredValueIterator = DeferredValueIterator /***/ }), /***/ 6909: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; const queueMicrotask = __webpack_require__(4375) module.exports = function (fn, ...args) { if (args.length === 0) { queueMicrotask(fn) } else { queueMicrotask(() => fn(...args)) } } /***/ }), /***/ 56: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; const ModuleError = __webpack_require__(4473) const hasOwnProperty = Object.prototype.hasOwnProperty const rangeOptions = new Set(['lt', 'lte', 'gt', 'gte']) module.exports = function (options, keyEncoding) { const result = {} for (const k in options) { if (!hasOwnProperty.call(options, k)) continue if (k === 'keyEncoding' || k === 'valueEncoding') continue if (k === 'start' || k === 'end') { throw new ModuleError(`The legacy range option '${k}' has been removed`, { code: 'LEVEL_LEGACY' }) } else if (k === 'encoding') { // To help migrating to abstract-level throw new ModuleError("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead", { code: 'LEVEL_LEGACY' }) } if (rangeOptions.has(k)) { // Note that we don't reject nullish and empty options here. While // those types are invalid as keys, they are valid as range options. result[k] = keyEncoding.encode(options[k]) } else { result[k] = options[k] } } result.reverse = !!result.reverse result.limit = Number.isInteger(result.limit) && result.limit >= 0 ? result.limit : -1 return result } /***/ }), /***/ 1317: /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony default export */ __webpack_exports__["default"] = ({}); /***/ }), /***/ 3883: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const bignumber_js_1 = __webpack_require__(4431); class Ar { constructor() { // Configure and assign the constructor function for the bignumber library. this.BigNum = (value, decimals) => { let instance = bignumber_js_1.BigNumber.clone({ DECIMAL_PLACES: decimals }); return new instance(value); }; } winstonToAr(winstonString, { formatted = false, decimals = 12, trim = true } = {}) { let number = this.stringToBigNum(winstonString, decimals).shiftedBy(-12); return formatted ? number.toFormat(decimals) : number.toFixed(decimals); } arToWinston(arString, { formatted = false } = {}) { let number = this.stringToBigNum(arString).shiftedBy(12); return formatted ? number.toFormat() : number.toFixed(0); } compare(winstonStringA, winstonStringB) { let a = this.stringToBigNum(winstonStringA); let b = this.stringToBigNum(winstonStringB); return a.comparedTo(b); } isEqual(winstonStringA, winstonStringB) { return this.compare(winstonStringA, winstonStringB) === 0; } isLessThan(winstonStringA, winstonStringB) { let a = this.stringToBigNum(winstonStringA); let b = this.stringToBigNum(winstonStringB); return a.isLessThan(b); } isGreaterThan(winstonStringA, winstonStringB) { let a = this.stringToBigNum(winstonStringA); let b = this.stringToBigNum(winstonStringB); return a.isGreaterThan(b); } add(winstonStringA, winstonStringB) { let a = this.stringToBigNum(winstonStringA); let b = this.stringToBigNum(winstonStringB); return a.plus(winstonStringB).toFixed(0); } sub(winstonStringA, winstonStringB) { let a = this.stringToBigNum(winstonStringA); let b = this.stringToBigNum(winstonStringB); return a.minus(winstonStringB).toFixed(0); } stringToBigNum(stringValue, decimalPlaces = 12) { return this.BigNum(stringValue, decimalPlaces); } } exports["default"] = Ar; //# sourceMappingURL=ar.js.map /***/ }), /***/ 1286: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const error_1 = __importDefault(__webpack_require__(2990)); __webpack_require__(1317); class Blocks { constructor(api, network) { this.api = api; this.network = network; } /** * Gets a block by its "indep_hash" */ async get(indepHash) { const response = await this.api.get(`${Blocks.ENDPOINT}${indepHash}`); if (response.status === 200) { return response.data; } else { if (response.status === 404) { throw new error_1.default("BLOCK_NOT_FOUND" /* ArweaveErrorType.BLOCK_NOT_FOUND */); } else { throw new Error(`Error while loading block data: ${response}`); } } } /** * Gets current block data (ie. block with indep_hash = Network.getInfo().current) */ async getCurrent() { const { current } = await this.network.getInfo(); return await this.get(current); } } exports["default"] = Blocks; Blocks.ENDPOINT = "block/hash/"; //# sourceMappingURL=blocks.js.map /***/ }), /***/ 1070: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; 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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const error_1 = __webpack_require__(2990); const ArweaveUtils = __importStar(__webpack_require__(5160)); class Chunks { constructor(api) { this.api = api; } async getTransactionOffset(id) { const resp = await this.api.get(`tx/${id}/offset`); if (resp.status === 200) { return resp.data; } throw new Error(`Unable to get transaction offset: ${(0, error_1.getError)(resp)}`); } async getChunk(offset) { const resp = await this.api.get(`chunk/${offset}`); if (resp.status === 200) { return resp.data; } throw new Error(`Unable to get chunk: ${(0, error_1.getError)(resp)}`); } async getChunkData(offset) { const chunk = await this.getChunk(offset); const buf = ArweaveUtils.b64UrlToBuffer(chunk.chunk); return buf; } firstChunkOffset(offsetResponse) { return parseInt(offsetResponse.offset) - parseInt(offsetResponse.size) + 1; } async downloadChunkedData(id) { const offsetResponse = await this.getTransactionOffset(id); const size = parseInt(offsetResponse.size); const endOffset = parseInt(offsetResponse.offset); const startOffset = endOffset - size + 1; const data = new Uint8Array(size); let byte = 0; while (byte < size) { if (this.api.config.logging) { console.log(`[chunk] ${byte}/${size}`); } let chunkData; try { chunkData = await this.getChunkData(startOffset + byte); } catch (error) { console.error(`[chunk] Failed to fetch chunk at offset ${startOffset + byte}`); console.error(`[chunk] This could indicate that the chunk wasn't uploaded or hasn't yet seeded properly to a particular gateway/node`); } if (chunkData) { data.set(chunkData, byte); byte += chunkData.length; } else { throw new Error(`Couldn't complete data download at ${byte}/${size}`); } } return data; } } exports["default"] = Chunks; //# sourceMappingURL=chunks.js.map /***/ }), /***/ 9499: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; 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 })); const ar_1 = __importDefault(__webpack_require__(3883)); const api_1 = __importDefault(__webpack_require__(7468)); const node_driver_1 = __importDefault(__webpack_require__(602)); const network_1 = __importDefault(__webpack_require__(5764)); const transactions_1 = __importDefault(__webpack_require__(5385)); const wallets_1 = __importDefault(__webpack_require__(8379)); const transaction_1 = __importDefault(__webpack_require__(7241)); const ArweaveUtils = __importStar(__webpack_require__(5160)); const silo_1 = __importDefault(__webpack_require__(4486)); const chunks_1 = __importDefault(__webpack_require__(1070)); const blocks_1 = __importDefault(__webpack_require__(1286)); class Arweave { constructor(apiConfig) { this.api = new api_1.default(apiConfig); this.wallets = new wallets_1.default(this.api, Arweave.crypto); this.chunks = new chunks_1.default(this.api); this.transactions = new transactions_1.default(this.api, Arweave.crypto, this.chunks); this.silo = new silo_1.default(this.api, this.crypto, this.transactions); this.network = new network_1.default(this.api); this.blocks = new blocks_1.default(this.api, this.network); this.ar = new ar_1.default(); } /** @deprecated */ get crypto() { return Arweave.crypto; } /** @deprecated */ get utils() { return Arweave.utils; } getConfig() { return { api: this.api.getConfig(), crypto: null, }; } async createTransaction(attributes, jwk) { const transaction = {}; Object.assign(transaction, attributes); if (!attributes.data && !(attributes.target && attributes.quantity)) { throw new Error(`A new Arweave transaction must have a 'data' value, or 'target' and 'quantity' values.`); } if (attributes.owner == undefined) { if (jwk && jwk !== "use_wallet") { transaction.owner = jwk.n; } } if (attributes.last_tx == undefined) { transaction.last_tx = await this.transactions.getTransactionAnchor(); } if (typeof attributes.data === "string") { attributes.data = ArweaveUtils.stringToBuffer(attributes.data); } if (attributes.data instanceof ArrayBuffer) { attributes.data = new Uint8Array(attributes.data); } if (attributes.data && !(attributes.data instanceof Uint8Array)) { throw new Error("Expected data to be a string, Uint8Array or ArrayBuffer"); } if (attributes.reward == undefined) { const length = attributes.data ? attributes.data.byteLength : 0; transaction.reward = await this.transactions.getPrice(length, transaction.target); } // here we should call prepare chunk transaction.data_root = ""; transaction.data_size = attributes.data ? attributes.data.byteLength.toString() : "0"; transaction.data = attributes.data || new Uint8Array(0); const createdTransaction = new transaction_1.default(transaction); await createdTransaction.getSignatureData(); return createdTransaction; } async createSiloTransaction(attributes, jwk, siloUri) { const transaction = {}; Object.assign(transaction, attributes); if (!attributes.data) { throw new Error(`Silo transactions must have a 'data' value`); } if (!siloUri) { throw new Error(`No Silo URI specified.`); } if (attributes.target || attributes.quantity) { throw new Error(`Silo transactions can only be used for storing data, sending AR to other wallets isn't supported.`); } if (attributes.owner == undefined) { if (!jwk || !jwk.n) { throw new Error(`A new Arweave transaction must either have an 'owner' attribute, or you must provide the jwk parameter.`); } transaction.owner = jwk.n; } if (attributes.last_tx == undefined) { transaction.last_tx = await this.transactions.getTransactionAnchor(); } const siloResource = await this.silo.parseUri(siloUri); if (typeof attributes.data == "string") { const encrypted = await this.crypto.encrypt(ArweaveUtils.stringToBuffer(attributes.data), siloResource.getEncryptionKey()); transaction.reward = await this.transactions.getPrice(encrypted.byteLength); transaction.data = ArweaveUtils.bufferTob64Url(encrypted); } if (attributes.data instanceof Uint8Array) { const encrypted = await this.crypto.encrypt(attributes.data, siloResource.getEncryptionKey()); transaction.reward = await this.transactions.getPrice(encrypted.byteLength); transaction.data = ArweaveUtils.bufferTob64Url(encrypted); } const siloTransaction = new transaction_1.default(transaction); siloTransaction.addTag("Silo-Name", siloResource.getAccessKey()); siloTransaction.addTag("Silo-Version", `0.1.0`); return siloTransaction; } arql(query) { return this.api .post("/arql", query) .then((response) => response.data || []); } } exports["default"] = Arweave; Arweave.crypto = new node_driver_1.default(); Arweave.utils = ArweaveUtils; //# sourceMappingURL=common.js.map /***/ }), /***/ 7468: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const axios_1 = __importDefault(__webpack_require__(9669)); class Api { constructor(config) { this.METHOD_GET = "GET"; this.METHOD_POST = "POST"; this.applyConfig(config); } applyConfig(config) { this.config = this.mergeDefaults(config); } getConfig() { return this.config; } mergeDefaults(config) { const protocol = config.protocol || "http"; const port = config.port || (protocol === "https" ? 443 : 80); return { host: config.host || "127.0.0.1", protocol, port, timeout: config.timeout || 20000, logging: config.logging || false, logger: config.logger || console.log, network: config.network, }; } async get(endpoint, config) { try { return await this.request().get(endpoint, config); } catch (error) { if (error.response && error.response.status) { return error.response; } throw error; } } async post(endpoint, body, config) { try { return await this.request().post(endpoint, body, config); } catch (error) { if (error.response && error.response.status) { return error.response; } throw error; } } /** * Get an AxiosInstance with the base configuration setup to fire off * a request to the network. */ request() { const headers = {}; if (this.config.network) { headers["x-network"] = this.config.network; } let instance = axios_1.default.create({ baseURL: `${this.config.protocol}://${this.config.host}:${this.config.port}`, timeout: this.config.timeout, maxContentLength: 1024 * 1024 * 512, headers, }); if (this.config.logging) { instance.interceptors.request.use((request) => { this.config.logger(`Requesting: ${request.baseURL}/${request.url}`); return request; }); instance.interceptors.response.use((response) => { this.config.logger(`Response: ${response.config.url} - ${response.status}`); return response; }); } return instance; } } exports["default"] = Api; //# sourceMappingURL=api.js.map /***/ }), /***/ 602: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(8764)["Buffer"]; 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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const pem_1 = __webpack_require__(3068); const crypto = __importStar(__webpack_require__(2474)); const constants = __importStar(__webpack_require__(2454)); class NodeCryptoDriver { constructor() { this.keyLength = 4096; this.publicExponent = 0x10001; this.hashAlgorithm = "sha256"; this.encryptionAlgorithm = "aes-256-cbc"; } generateJWK() { if (typeof crypto.generateKeyPair != "function") { throw new Error("Keypair generation not supported in this version of Node, only supported in versions 10+"); } return new Promise((resolve, reject) => { crypto.generateKeyPair("rsa", { modulusLength: this.keyLength, publicExponent: this.publicExponent, privateKeyEncoding: { type: "pkcs1", format: "pem", }, publicKeyEncoding: { type: "pkcs1", format: "pem" }, }, (err, publicKey, privateKey) => { if (err) { reject(err); } resolve(this.pemToJWK(privateKey)); }); }); } sign(jwk, data, { saltLength } = {}) { return new Promise((resolve, reject) => { resolve(crypto .createSign(this.hashAlgorithm) .update(data) .sign({ key: this.jwkToPem(jwk), padding: constants.RSA_PKCS1_PSS_PADDING, saltLength, })); }); } verify(publicModulus, data, signature) { return new Promise((resolve, reject) => { const publicKey = { kty: "RSA", e: "AQAB", n: publicModulus, }; const pem = this.jwkToPem(publicKey); resolve(crypto.createVerify(this.hashAlgorithm).update(data).verify({ key: pem, padding: constants.RSA_PKCS1_PSS_PADDING, }, signature)); }); } hash(data, algorithm = "SHA-256") { return new Promise((resolve, reject) => { resolve(crypto .createHash(this.parseHashAlgorithm(algorithm)) .update(data) .digest()); }); } /** * If a key is passed as a buffer it *must* be exactly 32 bytes. * If a key is passed as a string then any length may be used. * * @param {Buffer} data * @param {(string | Buffer)} key * @returns {Promise} */ async encrypt(data, key, salt) { // create a random string for deriving the key // const salt = crypto.randomBytes(16); // console.log(salt); // As we're using CBC with a randomised IV per cypher we don't really need // an additional random salt per passphrase. const derivedKey = crypto.pbkdf2Sync(key, (salt = salt ? salt : "salt"), 100000, 32, this.hashAlgorithm); const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv(this.encryptionAlgorithm, derivedKey, iv); const encrypted = Buffer.concat([iv, cipher.update(data), cipher.final()]); return encrypted; } /** * If a key is passed as a buffer it *must* be exactly 32 bytes. * If a key is passed as a string then any length may be used. * * @param {Buffer} encrypted * @param {(string | Buffer)} key * @returns {Promise} */ async decrypt(encrypted, key, salt) { try { // create a random string for deriving the key // const salt = crypto.randomBytes(16).toString('hex'); // As we're using CBC with a randomised IV per cypher we don't really need // an additional random salt per passphrase. const derivedKey = crypto.pbkdf2Sync(key, (salt = salt ? salt : "salt"), 100000, 32, this.hashAlgorithm); const iv = encrypted.slice(0, 16); const data = encrypted.slice(16); const decipher = crypto.createDecipheriv(this.encryptionAlgorithm, derivedKey, iv); const decrypted = Buffer.concat([ decipher.update(data), decipher.final(), ]); return decrypted; } catch (error) { throw new Error("Failed to decrypt"); } } jwkToPem(jwk) { return (0, pem_1.jwkTopem)(jwk); } pemToJWK(pem) { let jwk = (0, pem_1.pemTojwk)(pem); return jwk; } parseHashAlgorithm(algorithm) { switch (algorithm) { case "SHA-256": return "sha256"; case "SHA-384": return "sha384"; default: throw new Error(`Algorithm not supported: ${algorithm}`); } } } exports["default"] = NodeCryptoDriver; //# sourceMappingURL=node-driver.js.map /***/ }), /***/ 3068: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(8764)["Buffer"]; 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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.jwkTopem = exports.pemTojwk = void 0; // @ts-ignore const asn = __importStar(__webpack_require__(9809)); function urlize(base64) { return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); } function hex2b64url(str) { return urlize(Buffer.from(str, "hex").toString("base64")); } var RSAPublicKey = asn.define("RSAPublicKey", function () { this.seq().obj(this.key("n").int(), this.key("e").int()); }); var AlgorithmIdentifier = asn.define("AlgorithmIdentifier", function () { this.seq().obj(this.key("algorithm").objid(), this.key("parameters").optional().any()); }); var PublicKeyInfo = asn.define("PublicKeyInfo", function () { this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier), this.key("publicKey").bitstr()); }); var Version = asn.define("Version", function () { this.int({ 0: "two-prime", 1: "multi", }); }); var OtherPrimeInfos = asn.define("OtherPrimeInfos", function () { this.seq().obj(this.key("ri").int(), this.key("di").int(), this.key("ti").int()); }); var RSAPrivateKey = asn.define("RSAPrivateKey", function () { this.seq().obj(this.key("version").use(Version), this.key("n").int(), this.key("e").int(), this.key("d").int(), this.key("p").int(), this.key("q").int(), this.key("dp").int(), this.key("dq").int(), this.key("qi").int(), this.key("other").optional().use(OtherPrimeInfos)); }); var PrivateKeyInfo = asn.define("PrivateKeyInfo", function () { this.seq().obj(this.key("version").use(Version), this.key("algorithm").use(AlgorithmIdentifier), this.key("privateKey").bitstr()); }); const RSA_OID = "1.2.840.113549.1.1.1"; function addExtras(obj, extras) { extras = extras || {}; Object.keys(extras).forEach(function (key) { obj[key] = extras[key]; }); return obj; } function pad(hex) { return hex.length % 2 === 1 ? "0" + hex : hex; } function decodeRsaPublic(buffer, extras) { var key = RSAPublicKey.decode(buffer, "der"); var e = pad(key.e.toString(16)); var jwk = { kty: "RSA", n: bn2base64url(key.n), e: hex2b64url(e), }; return addExtras(jwk, extras); } function decodeRsaPrivate(buffer, extras) { var key = RSAPrivateKey.decode(buffer, "der"); var e = pad(key.e.toString(16)); var jwk = { kty: "RSA", n: bn2base64url(key.n), e: hex2b64url(e), d: bn2base64url(key.d), p: bn2base64url(key.p), q: bn2base64url(key.q), dp: bn2base64url(key.dp), dq: bn2base64url(key.dq), qi: bn2base64url(key.qi), }; return addExtras(jwk, extras); } function decodePublic(buffer, extras) { var info = PublicKeyInfo.decode(buffer, "der"); return decodeRsaPublic(info.publicKey.data, extras); } function decodePrivate(buffer, extras) { var info = PrivateKeyInfo.decode(buffer, "der"); return decodeRsaPrivate(info.privateKey.data, extras); } function getDecoder(header) { var match = /^-----BEGIN (RSA )?(PUBLIC|PRIVATE) KEY-----$/.exec(header); if (!match) { return null; } var isRSA = !!match[1]; var isPrivate = match[2] === "PRIVATE"; if (isPrivate) { return isRSA ? decodeRsaPrivate : decodePrivate; } else { return isRSA ? decodeRsaPublic : decodePublic; } } function parse(jwk) { return { n: string2bn(jwk.n), e: string2bn(jwk.e), d: jwk.d && string2bn(jwk.d), p: jwk.p && string2bn(jwk.p), q: jwk.q && string2bn(jwk.q), dp: jwk.dp && string2bn(jwk.dp), dq: jwk.dq && string2bn(jwk.dq), qi: jwk.qi && string2bn(jwk.qi), }; } function bn2base64url(bn) { return hex2b64url(pad(bn.toString(16))); } function base64url2bn(str) { return new asn.bignum(Buffer.from(str, "base64")); } function string2bn(str) { if (/^[0-9]+$/.test(str)) { return new asn.bignum(str, 10); } return base64url2bn(str); } function pemTojwk(pem, extras) { var text = pem.toString().split(/(\r\n|\r|\n)+/g); text = text.filter(function (line) { return line.trim().length !== 0; }); var decoder = getDecoder(text[0]); text = text.slice(1, -1).join(""); return decoder(Buffer.from(text.replace(/[^\w\d\+\/=]+/g, ""), "base64"), extras); } exports.pemTojwk = pemTojwk; function jwkTopem(json) { var jwk = parse(json); var isPrivate = !!jwk.d; var t = isPrivate ? "PRIVATE" : "PUBLIC"; var header = "-----BEGIN RSA " + t + " KEY-----\n"; var footer = "\n-----END RSA " + t + " KEY-----\n"; var data = Buffer.alloc(0); if (isPrivate) { jwk.version = "two-prime"; data = RSAPrivateKey.encode(jwk, "der"); } else { data = RSAPublicKey.encode(jwk, "der"); } var body = data .toString("base64") .match(/.{1,64}/g) .join("\n"); return header + body + footer; } exports.jwkTopem = jwkTopem; //# sourceMappingURL=pem.js.map /***/ }), /***/ 7439: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const common_1 = __importDefault(__webpack_require__(9499)); async function deepHash(data) { if (Array.isArray(data)) { const tag = common_1.default.utils.concatBuffers([ common_1.default.utils.stringToBuffer("list"), common_1.default.utils.stringToBuffer(data.length.toString()), ]); return await deepHashChunks(data, await common_1.default.crypto.hash(tag, "SHA-384")); } const tag = common_1.default.utils.concatBuffers([ common_1.default.utils.stringToBuffer("blob"), common_1.default.utils.stringToBuffer(data.byteLength.toString()), ]); const taggedHash = common_1.default.utils.concatBuffers([ await common_1.default.crypto.hash(tag, "SHA-384"), await common_1.default.crypto.hash(data, "SHA-384"), ]); return await common_1.default.crypto.hash(taggedHash, "SHA-384"); } exports["default"] = deepHash; async function deepHashChunks(chunks, acc) { if (chunks.length < 1) { return acc; } const hashPair = common_1.default.utils.concatBuffers([ acc, await deepHash(chunks[0]), ]); const newAcc = await common_1.default.crypto.hash(hashPair, "SHA-384"); return await deepHashChunks(chunks.slice(1), newAcc); } //# sourceMappingURL=deepHash.js.map /***/ }), /***/ 2990: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getError = void 0; class ArweaveError extends Error { constructor(type, optional = {}) { if (optional.message) { super(optional.message); } else { super(); } this.type = type; this.response = optional.response; } getType() { return this.type; } } exports["default"] = ArweaveError; // Safely get error string // from an axios response, falling back to // resp.data, statusText or 'unknown'. // Note: a wrongly set content-type can // cause what is a json response to be interepted // as a string or Buffer, so we handle that too. function getError(resp) { let data = resp.data; if (typeof resp.data === "string") { try { data = JSON.parse(resp.data); } catch (e) { } } if (resp.data instanceof ArrayBuffer || resp.data instanceof Uint8Array) { try { data = JSON.parse(data.toString()); } catch (e) { } } return data ? data.error || data : resp.statusText || "unknown"; } exports.getError = getError; //# sourceMappingURL=error.js.map /***/ }), /***/ 1612: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(8764)["Buffer"]; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.debug = exports.validatePath = exports.arrayCompare = exports.bufferToInt = exports.intToBuffer = exports.arrayFlatten = exports.generateProofs = exports.buildLayers = exports.generateTransactionChunks = exports.generateTree = exports.computeRootHash = exports.generateLeaves = exports.chunkData = exports.MIN_CHUNK_SIZE = exports.MAX_CHUNK_SIZE = void 0; /** * @see {@link https://github.com/ArweaveTeam/arweave/blob/fbc381e0e36efffa45d13f2faa6199d3766edaa2/apps/arweave/src/ar_merkle.erl} */ const common_1 = __importDefault(__webpack_require__(9499)); const utils_1 = __webpack_require__(5160); exports.MAX_CHUNK_SIZE = 256 * 1024; exports.MIN_CHUNK_SIZE = 32 * 1024; const NOTE_SIZE = 32; const HASH_SIZE = 32; /** * Takes the input data and chunks it into (mostly) equal sized chunks. * The last chunk will be a bit smaller as it contains the remainder * from the chunking process. */ async function chunkData(data) { let chunks = []; let rest = data; let cursor = 0; while (rest.byteLength >= exports.MAX_CHUNK_SIZE) { let chunkSize = exports.MAX_CHUNK_SIZE; // If the total bytes left will produce a chunk < MIN_CHUNK_SIZE, // then adjust the amount we put in this 2nd last chunk. let nextChunkSize = rest.byteLength - exports.MAX_CHUNK_SIZE; if (nextChunkSize > 0 && nextChunkSize < exports.MIN_CHUNK_SIZE) { chunkSize = Math.ceil(rest.byteLength / 2); // console.log(`Last chunk will be: ${nextChunkSize} which is below ${MIN_CHUNK_SIZE}, adjusting current to ${chunkSize} with ${rest.byteLength} left.`) } const chunk = rest.slice(0, chunkSize); const dataHash = await common_1.default.crypto.hash(chunk); cursor += chunk.byteLength; chunks.push({ dataHash, minByteRange: cursor - chunk.byteLength, maxByteRange: cursor, }); rest = rest.slice(chunkSize); } chunks.push({ dataHash: await common_1.default.crypto.hash(rest), minByteRange: cursor, maxByteRange: cursor + rest.byteLength, }); return chunks; } exports.chunkData = chunkData; async function generateLeaves(chunks) { return Promise.all(chunks.map(async ({ dataHash, minByteRange, maxByteRange }) => { return { type: "leaf", id: await hash(await Promise.all([hash(dataHash), hash(intToBuffer(maxByteRange))])), dataHash: dataHash, minByteRange, maxByteRange, }; })); } exports.generateLeaves = generateLeaves; /** * Builds an arweave merkle tree and gets the root hash for the given input. */ async function computeRootHash(data) { const rootNode = await generateTree(data); return rootNode.id; } exports.computeRootHash = computeRootHash; async function generateTree(data) { const rootNode = await buildLayers(await generateLeaves(await chunkData(data))); return rootNode; } exports.generateTree = generateTree; /** * Generates the data_root, chunks & proofs * needed for a transaction. * * This also checks if the last chunk is a zero-length * chunk and discards that chunk and proof if so. * (we do not need to upload this zero length chunk) * * @param data */ async function generateTransactionChunks(data) { const chunks = await chunkData(data); const leaves = await generateLeaves(chunks); const root = await buildLayers(leaves); const proofs = await generateProofs(root); // Discard the last chunk & proof if it's zero length. const lastChunk = chunks.slice(-1)[0]; if (lastChunk.maxByteRange - lastChunk.minByteRange === 0) { chunks.splice(chunks.length - 1, 1); proofs.splice(proofs.length - 1, 1); } return { data_root: root.id, chunks, proofs, }; } exports.generateTransactionChunks = generateTransactionChunks; /** * Starting with the bottom layer of leaf nodes, hash every second pair * into a new branch node, push those branch nodes onto a new layer, * and then recurse, building up the tree to it's root, where the * layer only consists of two items. */ async function buildLayers(nodes, level = 0) { // If there is only 1 node left, this is going to be the root node if (nodes.length < 2) { const root = nodes[0]; // console.log("Root layer", root); return root; } const nextLayer = []; for (let i = 0; i < nodes.length; i += 2) { nextLayer.push(await hashBranch(nodes[i], nodes[i + 1])); } // console.log("Layer", nextLayer); return buildLayers(nextLayer, level + 1); } exports.buildLayers = buildLayers; /** * Recursively search through all branches of the tree, * and generate a proof for each leaf node. */ function generateProofs(root) { const proofs = resolveBranchProofs(root); if (!Array.isArray(proofs)) { return [proofs]; } return arrayFlatten(proofs); } exports.generateProofs = generateProofs; function resolveBranchProofs(node, proof = new Uint8Array(), depth = 0) { if (node.type == "leaf") { return { offset: node.maxByteRange - 1, proof: (0, utils_1.concatBuffers)([ proof, node.dataHash, intToBuffer(node.maxByteRange), ]), }; } if (node.type == "branch") { const partialProof = (0, utils_1.concatBuffers)([ proof, node.leftChild.id, node.rightChild.id, intToBuffer(node.byteRange), ]); return [ resolveBranchProofs(node.leftChild, partialProof, depth + 1), resolveBranchProofs(node.rightChild, partialProof, depth + 1), ]; } throw new Error(`Unexpected node type`); } function arrayFlatten(input) { const flat = []; input.forEach((item) => { if (Array.isArray(item)) { flat.push(...arrayFlatten(item)); } else { flat.push(item); } }); return flat; } exports.arrayFlatten = arrayFlatten; async function hashBranch(left, right) { if (!right) { return left; } let branch = { type: "branch", id: await hash([ await hash(left.id), await hash(right.id), await hash(intToBuffer(left.maxByteRange)), ]), byteRange: left.maxByteRange, maxByteRange: right.maxByteRange, leftChild: left, rightChild: right, }; return branch; } async function hash(data) { if (Array.isArray(data)) { data = common_1.default.utils.concatBuffers(data); } return new Uint8Array(await common_1.default.crypto.hash(data)); } function intToBuffer(note) { const buffer = new Uint8Array(NOTE_SIZE); for (var i = buffer.length - 1; i >= 0; i--) { var byte = note % 256; buffer[i] = byte; note = (note - byte) / 256; } return buffer; } exports.intToBuffer = intToBuffer; function bufferToInt(buffer) { let value = 0; for (var i = 0; i < buffer.length; i++) { value *= 256; value += buffer[i]; } return value; } exports.bufferToInt = bufferToInt; const arrayCompare = (a, b) => a.every((value, index) => b[index] === value); exports.arrayCompare = arrayCompare; async function validatePath(id, dest, leftBound, rightBound, path) { if (rightBound <= 0) { return false; } if (dest >= rightBound) { return validatePath(id, 0, rightBound - 1, rightBound, path); } if (dest < 0) { return validatePath(id, 0, 0, rightBound, path); } if (path.length == HASH_SIZE + NOTE_SIZE) { const pathData = path.slice(0, HASH_SIZE); const endOffsetBuffer = path.slice(pathData.length, pathData.length + NOTE_SIZE); const pathDataHash = await hash([ await hash(pathData), await hash(endOffsetBuffer), ]); let result = (0, exports.arrayCompare)(id, pathDataHash); if (result) { return { offset: rightBound - 1, leftBound: leftBound, rightBound: rightBound, chunkSize: rightBound - leftBound, }; } return false; } const left = path.slice(0, HASH_SIZE); const right = path.slice(left.length, left.length + HASH_SIZE); const offsetBuffer = path.slice(left.length + right.length, left.length + right.length + NOTE_SIZE); const offset = bufferToInt(offsetBuffer); const remainder = path.slice(left.length + right.length + offsetBuffer.length); const pathHash = await hash([ await hash(left), await hash(right), await hash(offsetBuffer), ]); if ((0, exports.arrayCompare)(id, pathHash)) { if (dest < offset) { return await validatePath(left, dest, leftBound, Math.min(rightBound, offset), remainder); } return await validatePath(right, dest, Math.max(leftBound, offset), rightBound, remainder); } return false; } exports.validatePath = validatePath; /** * Inspect an arweave chunk proof. * Takes proof, parses, reads and displays the values for console logging. * One proof section per line * Format: left,right,offset => hash */ async function debug(proof, output = "") { if (proof.byteLength < 1) { return output; } const left = proof.slice(0, HASH_SIZE); const right = proof.slice(left.length, left.length + HASH_SIZE); const offsetBuffer = proof.slice(left.length + right.length, left.length + right.length + NOTE_SIZE); const offset = bufferToInt(offsetBuffer); const remainder = proof.slice(left.length + right.length + offsetBuffer.length); const pathHash = await hash([ await hash(left), await hash(right), await hash(offsetBuffer), ]); const updatedOutput = `${output}\n${JSON.stringify(Buffer.from(left))},${JSON.stringify(Buffer.from(right))},${offset} => ${JSON.stringify(pathHash)}`; return debug(remainder, updatedOutput); } exports.debug = debug; //# sourceMappingURL=merkle.js.map /***/ }), /***/ 4107: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; 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.TransactionUploader = void 0; const transaction_1 = __importDefault(__webpack_require__(7241)); const ArweaveUtils = __importStar(__webpack_require__(5160)); const error_1 = __webpack_require__(2990); const merkle_1 = __webpack_require__(1612); // Maximum amount of chunks we will upload in the body. const MAX_CHUNKS_IN_BODY = 1; // We assume these errors are intermitment and we can try again after a delay: // - not_joined // - timeout // - data_root_not_found (we may have hit a node that just hasn't seen it yet) // - exceeds_disk_pool_size_limit // We also try again after any kind of unexpected network errors // Errors from /chunk we should never try and continue on. const FATAL_CHUNK_UPLOAD_ERRORS = [ "invalid_json", "chunk_too_big", "data_path_too_big", "offset_too_big", "data_size_too_big", "chunk_proof_ratio_not_attractive", "invalid_proof", ]; // Amount we will delay on receiving an error response but do want to continue. const ERROR_DELAY = 1000 * 40; class TransactionUploader { constructor(api, transaction) { this.api = api; this.chunkIndex = 0; this.txPosted = false; this.lastRequestTimeEnd = 0; this.totalErrors = 0; // Not serialized. this.lastResponseStatus = 0; this.lastResponseError = ""; if (!transaction.id) { throw new Error(`Transaction is not signed`); } if (!transaction.chunks) { throw new Error(`Transaction chunks not prepared`); } // Make a copy of transaction, zeroing the data so we can serialize. this.data = transaction.data; this.transaction = new transaction_1.default(Object.assign({}, transaction, { data: new Uint8Array(0) })); } get isComplete() { return (this.txPosted && this.chunkIndex === this.transaction.chunks.chunks.length); } get totalChunks() { return this.transaction.chunks.chunks.length; } get uploadedChunks() { return this.chunkIndex; } get pctComplete() { return Math.trunc((this.uploadedChunks / this.totalChunks) * 100); } /** * Uploads the next part of the transaction. * On the first call this posts the transaction * itself and on any subsequent calls uploads the * next chunk until it completes. */ async uploadChunk(chunkIndex_) { if (this.isComplete) { throw new Error(`Upload is already complete`); } if (this.lastResponseError !== "") { this.totalErrors++; } else { this.totalErrors = 0; } // We have been trying for about an hour receiving an // error every time, so eventually bail. if (this.totalErrors === 100) { throw new Error(`Unable to complete upload: ${this.lastResponseStatus}: ${this.lastResponseError}`); } let delay = this.lastResponseError === "" ? 0 : Math.max(this.lastRequestTimeEnd + ERROR_DELAY - Date.now(), ERROR_DELAY); if (delay > 0) { // Jitter delay bcoz networks, subtract up to 30% from 40 seconds delay = delay - delay * Math.random() * 0.3; await new Promise((res) => setTimeout(res, delay)); } this.lastResponseError = ""; if (!this.txPosted) { await this.postTransaction(); return; } if (chunkIndex_) { this.chunkIndex = chunkIndex_; } const chunk = this.transaction.getChunk(chunkIndex_ || this.chunkIndex, this.data); const chunkOk = await (0, merkle_1.validatePath)(this.transaction.chunks.data_root, parseInt(chunk.offset), 0, parseInt(chunk.data_size), ArweaveUtils.b64UrlToBuffer(chunk.data_path)); if (!chunkOk) { throw new Error(`Unable to validate chunk ${this.chunkIndex}`); } // Catch network errors and turn them into objects with status -1 and an error message. const resp = await this.api .post(`chunk`, this.transaction.getChunk(this.chunkIndex, this.data)) .catch((e) => { console.error(e.message); return { status: -1, data: { error: e.message } }; }); this.lastRequestTimeEnd = Date.now(); this.lastResponseStatus = resp.status; if (this.lastResponseStatus == 200) { this.chunkIndex++; } else { this.lastResponseError = (0, error_1.getError)(resp); if (FATAL_CHUNK_UPLOAD_ERRORS.includes(this.lastResponseError)) { throw new Error(`Fatal error uploading chunk ${this.chunkIndex}: ${this.lastResponseError}`); } } } /** * Reconstructs an upload from its serialized state and data. * Checks if data matches the expected data_root. * * @param serialized * @param data */ static async fromSerialized(api, serialized, data) { if (!serialized || typeof serialized.chunkIndex !== "number" || typeof serialized.transaction !== "object") { throw new Error(`Serialized object does not match expected format.`); } // Everything looks ok, reconstruct the TransactionUpload, // prepare the chunks again and verify the data_root matches var transaction = new transaction_1.default(serialized.transaction); if (!transaction.chunks) { await transaction.prepareChunks(data); } const upload = new TransactionUploader(api, transaction); // Copy the serialized upload information, and data passed in. upload.chunkIndex = serialized.chunkIndex; upload.lastRequestTimeEnd = serialized.lastRequestTimeEnd; upload.lastResponseError = serialized.lastResponseError; upload.lastResponseStatus = serialized.lastResponseStatus; upload.txPosted = serialized.txPosted; upload.data = data; if (upload.transaction.data_root !== serialized.transaction.data_root) { throw new Error(`Data mismatch: Uploader doesn't match provided data.`); } return upload; } /** * Reconstruct an upload from the tx metadata, ie /tx/. * * @param api * @param id * @param data */ static async fromTransactionId(api, id) { const resp = await api.get(`tx/${id}`); if (resp.status !== 200) { throw new Error(`Tx ${id} not found: ${resp.status}`); } const transaction = resp.data; transaction.data = new Uint8Array(0); const serialized = { txPosted: true, chunkIndex: 0, lastResponseError: "", lastRequestTimeEnd: 0, lastResponseStatus: 0, transaction, }; return serialized; } toJSON() { return { chunkIndex: this.chunkIndex, transaction: this.transaction, lastRequestTimeEnd: this.lastRequestTimeEnd, lastResponseStatus: this.lastResponseStatus, lastResponseError: this.lastResponseError, txPosted: this.txPosted, }; } // POST to /tx async postTransaction() { const uploadInBody = this.totalChunks <= MAX_CHUNKS_IN_BODY; if (uploadInBody) { // Post the transaction with data. this.transaction.data = this.data; const resp = await this.api.post(`tx`, this.transaction).catch((e) => { console.error(e); return { status: -1, data: { error: e.message } }; }); this.lastRequestTimeEnd = Date.now(); this.lastResponseStatus = resp.status; this.transaction.data = new Uint8Array(0); if (resp.status >= 200 && resp.status < 300) { // We are complete. this.txPosted = true; this.chunkIndex = MAX_CHUNKS_IN_BODY; return; } this.lastResponseError = (0, error_1.getError)(resp); throw new Error(`Unable to upload transaction: ${resp.status}, ${this.lastResponseError}`); } // Post the transaction with no data. const resp = await this.api.post(`tx`, this.transaction); this.lastRequestTimeEnd = Date.now(); this.lastResponseStatus = resp.status; if (!(resp.status >= 200 && resp.status < 300)) { this.lastResponseError = (0, error_1.getError)(resp); throw new Error(`Unable to upload transaction: ${resp.status}, ${this.lastResponseError}`); } this.txPosted = true; } } exports.TransactionUploader = TransactionUploader; //# sourceMappingURL=transaction-uploader.js.map /***/ }), /***/ 7241: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; 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.Tag = void 0; const ArweaveUtils = __importStar(__webpack_require__(5160)); const deepHash_1 = __importDefault(__webpack_require__(7439)); const merkle_1 = __webpack_require__(1612); class BaseObject { get(field, options) { if (!Object.getOwnPropertyNames(this).includes(field)) { throw new Error(`Field "${field}" is not a property of the Arweave Transaction class.`); } // Handle fields that are Uint8Arrays. // To maintain compat we encode them to b64url // if decode option is not specificed. if (this[field] instanceof Uint8Array) { if (options && options.decode && options.string) { return ArweaveUtils.bufferToString(this[field]); } if (options && options.decode && !options.string) { return this[field]; } return ArweaveUtils.bufferTob64Url(this[field]); } if (options && options.decode == true) { if (options && options.string) { return ArweaveUtils.b64UrlToString(this[field]); } return ArweaveUtils.b64UrlToBuffer(this[field]); } return this[field]; } } class Tag extends BaseObject { constructor(name, value, decode = false) { super(); this.name = name; this.value = value; } } exports.Tag = Tag; class Transaction extends BaseObject { constructor(attributes = {}) { super(); this.format = 2; this.id = ""; this.last_tx = ""; this.owner = ""; this.tags = []; this.target = ""; this.quantity = "0"; this.data_size = "0"; this.data = new Uint8Array(); this.data_root = ""; this.reward = "0"; this.signature = ""; Object.assign(this, attributes); // If something passes in a Tx that has been toJSON'ed and back, // or where the data was filled in from /tx/data endpoint. // data will be b64url encoded, so decode it. if (typeof this.data === "string") { this.data = ArweaveUtils.b64UrlToBuffer(this.data); } if (attributes.tags) { this.tags = attributes.tags.map((tag) => { return new Tag(tag.name, tag.value); }); } } addTag(name, value) { this.tags.push(new Tag(ArweaveUtils.stringToB64Url(name), ArweaveUtils.stringToB64Url(value))); } toJSON() { return { format: this.format, id: this.id, last_tx: this.last_tx, owner: this.owner, tags: this.tags, target: this.target, quantity: this.quantity, data: ArweaveUtils.bufferTob64Url(this.data), data_size: this.data_size, data_root: this.data_root, data_tree: this.data_tree, reward: this.reward, signature: this.signature, }; } setOwner(owner) { this.owner = owner; } setSignature({ id, owner, reward, tags, signature, }) { this.id = id; this.owner = owner; if (reward) this.reward = reward; if (tags) this.tags = tags; this.signature = signature; } async prepareChunks(data) { // Note: we *do not* use `this.data`, the caller may be // operating on a transaction with an zero length data field. // This function computes the chunks for the data passed in and // assigns the result to this transaction. It should not read the // data *from* this transaction. if (!this.chunks && data.byteLength > 0) { this.chunks = await (0, merkle_1.generateTransactionChunks)(data); this.data_root = ArweaveUtils.bufferTob64Url(this.chunks.data_root); } if (!this.chunks && data.byteLength === 0) { this.chunks = { chunks: [], data_root: new Uint8Array(), proofs: [], }; this.data_root = ""; } } // Returns a chunk in a format suitable for posting to /chunk. // Similar to `prepareChunks()` this does not operate `this.data`, // instead using the data passed in. getChunk(idx, data) { if (!this.chunks) { throw new Error(`Chunks have not been prepared`); } const proof = this.chunks.proofs[idx]; const chunk = this.chunks.chunks[idx]; return { data_root: this.data_root, data_size: this.data_size, data_path: ArweaveUtils.bufferTob64Url(proof.proof), offset: proof.offset.toString(), chunk: ArweaveUtils.bufferTob64Url(data.slice(chunk.minByteRange, chunk.maxByteRange)), }; } async getSignatureData() { switch (this.format) { case 1: let tags = this.tags.reduce((accumulator, tag) => { return ArweaveUtils.concatBuffers([ accumulator, tag.get("name", { decode: true, string: false }), tag.get("value", { decode: true, string: false }), ]); }, new Uint8Array()); return ArweaveUtils.concatBuffers([ this.get("owner", { decode: true, string: false }), this.get("target", { decode: true, string: false }), this.get("data", { decode: true, string: false }), ArweaveUtils.stringToBuffer(this.quantity), ArweaveUtils.stringToBuffer(this.reward), this.get("last_tx", { decode: true, string: false }), tags, ]); case 2: if (!this.data_root) { await this.prepareChunks(this.data); } const tagList = this.tags.map((tag) => [ tag.get("name", { decode: true, string: false }), tag.get("value", { decode: true, string: false }), ]); return await (0, deepHash_1.default)([ ArweaveUtils.stringToBuffer(this.format.toString()), this.get("owner", { decode: true, string: false }), this.get("target", { decode: true, string: false }), ArweaveUtils.stringToBuffer(this.quantity), ArweaveUtils.stringToBuffer(this.reward), this.get("last_tx", { decode: true, string: false }), tagList, ArweaveUtils.stringToBuffer(this.data_size), this.get("data_root", { decode: true, string: false }), ]); default: throw new Error(`Unexpected transaction format: ${this.format}`); } } } exports["default"] = Transaction; //# sourceMappingURL=transaction.js.map /***/ }), /***/ 5160: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; 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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.b64UrlDecode = exports.b64UrlEncode = exports.bufferTob64Url = exports.bufferTob64 = exports.b64UrlToBuffer = exports.stringToB64Url = exports.stringToBuffer = exports.bufferToString = exports.b64UrlToString = exports.concatBuffers = void 0; const B64js = __importStar(__webpack_require__(9742)); function concatBuffers(buffers) { let total_length = 0; for (let i = 0; i < buffers.length; i++) { total_length += buffers[i].byteLength; } let temp = new Uint8Array(total_length); let offset = 0; temp.set(new Uint8Array(buffers[0]), offset); offset += buffers[0].byteLength; for (let i = 1; i < buffers.length; i++) { temp.set(new Uint8Array(buffers[i]), offset); offset += buffers[i].byteLength; } return temp; } exports.concatBuffers = concatBuffers; function b64UrlToString(b64UrlString) { let buffer = b64UrlToBuffer(b64UrlString); // TextEncoder will be available in browsers, but not in node if (typeof TextDecoder == "undefined") { const TextDecoder = (__webpack_require__(9539).TextDecoder); return new TextDecoder("utf-8", { fatal: true }).decode(buffer); } return new TextDecoder("utf-8", { fatal: true }).decode(buffer); } exports.b64UrlToString = b64UrlToString; function bufferToString(buffer) { // TextEncoder will be available in browsers, but not in node if (typeof TextDecoder == "undefined") { const TextDecoder = (__webpack_require__(9539).TextDecoder); return new TextDecoder("utf-8", { fatal: true }).decode(buffer); } return new TextDecoder("utf-8", { fatal: true }).decode(buffer); } exports.bufferToString = bufferToString; function stringToBuffer(string) { // TextEncoder will be available in browsers, but not in node if (typeof TextEncoder == "undefined") { const TextEncoder = (__webpack_require__(9539).TextEncoder); return new TextEncoder().encode(string); } return new TextEncoder().encode(string); } exports.stringToBuffer = stringToBuffer; function stringToB64Url(string) { return bufferTob64Url(stringToBuffer(string)); } exports.stringToB64Url = stringToB64Url; function b64UrlToBuffer(b64UrlString) { return new Uint8Array(B64js.toByteArray(b64UrlDecode(b64UrlString))); } exports.b64UrlToBuffer = b64UrlToBuffer; function bufferTob64(buffer) { return B64js.fromByteArray(new Uint8Array(buffer)); } exports.bufferTob64 = bufferTob64; function bufferTob64Url(buffer) { return b64UrlEncode(bufferTob64(buffer)); } exports.bufferTob64Url = bufferTob64Url; function b64UrlEncode(b64UrlString) { return b64UrlString .replace(/\+/g, "-") .replace(/\//g, "_") .replace(/\=/g, ""); } exports.b64UrlEncode = b64UrlEncode; function b64UrlDecode(b64UrlString) { b64UrlString = b64UrlString.replace(/\-/g, "+").replace(/\_/g, "/"); let padding; b64UrlString.length % 4 == 0 ? (padding = 0) : (padding = 4 - (b64UrlString.length % 4)); return b64UrlString.concat("=".repeat(padding)); } exports.b64UrlDecode = b64UrlDecode; //# sourceMappingURL=utils.js.map /***/ }), /***/ 5764: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class Network { constructor(api) { this.api = api; } getInfo() { return this.api.get(`info`).then((response) => { return response.data; }); } getPeers() { return this.api.get(`peers`).then((response) => { return response.data; }); } } exports["default"] = Network; //# sourceMappingURL=network.js.map /***/ }), /***/ 4486: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; 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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SiloResource = void 0; const ArweaveUtils = __importStar(__webpack_require__(5160)); class Silo { constructor(api, crypto, transactions) { this.api = api; this.crypto = crypto; this.transactions = transactions; } async get(siloURI) { if (!siloURI) { throw new Error(`No Silo URI specified`); } const resource = await this.parseUri(siloURI); const ids = await this.transactions.search("Silo-Name", resource.getAccessKey()); if (ids.length == 0) { throw new Error(`No data could be found for the Silo URI: ${siloURI}`); } const transaction = await this.transactions.get(ids[0]); if (!transaction) { throw new Error(`No data could be found for the Silo URI: ${siloURI}`); } const encrypted = transaction.get("data", { decode: true, string: false }); return this.crypto.decrypt(encrypted, resource.getEncryptionKey()); } async readTransactionData(transaction, siloURI) { if (!siloURI) { throw new Error(`No Silo URI specified`); } const resource = await this.parseUri(siloURI); const encrypted = transaction.get("data", { decode: true, string: false }); return this.crypto.decrypt(encrypted, resource.getEncryptionKey()); } async parseUri(siloURI) { const parsed = siloURI.match(/^([a-z0-9-_]+)\.([0-9]+)/i); if (!parsed) { throw new Error(`Invalid Silo name, must be a name in the format of [a-z0-9]+.[0-9]+, e.g. 'bubble.7'`); } const siloName = parsed[1]; const hashIterations = Math.pow(2, parseInt(parsed[2])); const digest = await this.hash(ArweaveUtils.stringToBuffer(siloName), hashIterations); const accessKey = ArweaveUtils.bufferTob64(digest.slice(0, 15)); const encryptionkey = await this.hash(digest.slice(16, 31), 1); return new SiloResource(siloURI, accessKey, encryptionkey); } async hash(input, iterations) { let digest = await this.crypto.hash(input); for (let count = 0; count < iterations - 1; count++) { digest = await this.crypto.hash(digest); } return digest; } } exports["default"] = Silo; class SiloResource { constructor(uri, accessKey, encryptionKey) { this.uri = uri; this.accessKey = accessKey; this.encryptionKey = encryptionKey; } getUri() { return this.uri; } getAccessKey() { return this.accessKey; } getEncryptionKey() { return this.encryptionKey; } } exports.SiloResource = SiloResource; //# sourceMappingURL=silo.js.map /***/ }), /***/ 5385: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; 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 __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const error_1 = __importDefault(__webpack_require__(2990)); const transaction_1 = __importDefault(__webpack_require__(7241)); const ArweaveUtils = __importStar(__webpack_require__(5160)); const transaction_uploader_1 = __webpack_require__(4107); __webpack_require__(1317); class Transactions { constructor(api, crypto, chunks) { this.api = api; this.crypto = crypto; this.chunks = chunks; } getTransactionAnchor() { /** * Maintain compatibility with erdjs which sets a global axios.defaults.transformResponse * in order to overcome some other issue in: https://github.com/axios/axios/issues/983 * * However, this introduces a problem with ardrive-js, so we will enforce * config = {transformResponse: []} where we do not require a transform */ return this.api .get(`tx_anchor`, { transformResponse: [] }) .then((response) => { return response.data; }); } getPrice(byteSize, targetAddress) { let endpoint = targetAddress ? `price/${byteSize}/${targetAddress}` : `price/${byteSize}`; return this.api .get(endpoint, { transformResponse: [ /** * We need to specify a response transformer to override * the default JSON.parse behavior, as this causes * winston to be converted to a number and we want to * return it as a winston string. * @param data */ function (data) { return data; }, ], }) .then((response) => { return response.data; }); } async get(id) { const response = await this.api.get(`tx/${id}`); if (response.status == 200) { const data_size = parseInt(response.data.data_size); if (response.data.format >= 2 && data_size > 0 && data_size <= 1024 * 1024 * 12) { const data = await this.getData(id); return new transaction_1.default(Object.assign(Object.assign({}, response.data), { data })); } return new transaction_1.default(Object.assign(Object.assign({}, response.data), { format: response.data.format || 1 })); } if (response.status == 404) { throw new error_1.default("TX_NOT_FOUND" /* ArweaveErrorType.TX_NOT_FOUND */); } if (response.status == 410) { throw new error_1.default("TX_FAILED" /* ArweaveErrorType.TX_FAILED */); } throw new error_1.default("TX_INVALID" /* ArweaveErrorType.TX_INVALID */); } fromRaw(attributes) { return new transaction_1.default(attributes); } async search(tagName, tagValue) { return this.api .post(`arql`, { op: "equals", expr1: tagName, expr2: tagValue, }) .then((response) => { if (!response.data) { return []; } return response.data; }); } getStatus(id) { return this.api.get(`tx/${id}/status`).then((response) => { if (response.status == 200) { return { status: 200, confirmed: response.data, }; } return { status: response.status, confirmed: null, }; }); } async getData(id, options) { let data = undefined; try { data = await this.chunks.downloadChunkedData(id); } catch (error) { console.error(`Error while trying to download chunked data for ${id}`); console.error(error); } if (!data) { console.warn(`Falling back to gateway cache for ${id}`); try { data = (await this.api.get(`/${id}`)).data; } catch (error) { console.error(`Error while trying to download contiguous data from gateway cache for ${id}`); console.error(error); } } if (!data) { throw new Error(`${id} was not found!`); } if (options && options.decode && !options.string) { return data; } if (options && options.decode && options.string) { return ArweaveUtils.bufferToString(data); } // Since decode wasn't requested, caller expects b64url encoded data. return ArweaveUtils.bufferTob64Url(data); } async sign(transaction, jwk, options) { if (!jwk && (typeof window === "undefined" || !window.arweaveWallet)) { throw new Error(`A new Arweave transaction must provide the jwk parameter.`); } else if (!jwk || jwk === "use_wallet") { try { const existingPermissions = await window.arweaveWallet.getPermissions(); if (!existingPermissions.includes("SIGN_TRANSACTION")) await window.arweaveWallet.connect(["SIGN_TRANSACTION"]); } catch (_a) { // Permission is already granted } const signedTransaction = await window.arweaveWallet.sign(transaction, options); transaction.setSignature({ id: signedTransaction.id, owner: signedTransaction.owner, reward: signedTransaction.reward, tags: signedTransaction.tags, signature: signedTransaction.signature, }); } else { transaction.setOwner(jwk.n); let dataToSign = await transaction.getSignatureData(); let rawSignature = await this.crypto.sign(jwk, dataToSign, options); let id = await this.crypto.hash(rawSignature); transaction.setSignature({ id: ArweaveUtils.bufferTob64Url(id), owner: jwk.n, signature: ArweaveUtils.bufferTob64Url(rawSignature), }); } } async verify(transaction) { const signaturePayload = await transaction.getSignatureData(); /** * The transaction ID should be a SHA-256 hash of the raw signature bytes, so this needs * to be recalculated from the signature and checked against the transaction ID. */ const rawSignature = transaction.get("signature", { decode: true, string: false, }); const expectedId = ArweaveUtils.bufferTob64Url(await this.crypto.hash(rawSignature)); if (transaction.id !== expectedId) { throw new Error(`Invalid transaction signature or ID! The transaction ID doesn't match the expected SHA-256 hash of the signature.`); } /** * Now verify the signature is valid and signed by the owner wallet (owner field = originating wallet public key). */ return this.crypto.verify(transaction.owner, signaturePayload, rawSignature); } async post(transaction) { if (typeof transaction === "string") { transaction = new transaction_1.default(JSON.parse(transaction)); } else if (typeof transaction.readInt32BE === "function") { transaction = new transaction_1.default(JSON.parse(transaction.toString())); } else if (typeof transaction === "object" && !(transaction instanceof transaction_1.default)) { transaction = new transaction_1.default(transaction); } if (!(transaction instanceof transaction_1.default)) { throw new Error(`Must be Transaction object`); } if (!transaction.chunks) { await transaction.prepareChunks(transaction.data); } const uploader = await this.getUploader(transaction, transaction.data); // Emulate existing error & return value behavior. try { while (!uploader.isComplete) { await uploader.uploadChunk(); } } catch (e) { if (uploader.lastResponseStatus > 0) { return { status: uploader.lastResponseStatus, statusText: uploader.lastResponseError, data: { error: uploader.lastResponseError, }, }; } throw e; } return { status: 200, statusText: "OK", data: {}, }; } /** * Gets an uploader than can be used to upload a transaction chunk by chunk, giving progress * and the ability to resume. * * Usage example: * * ``` * const uploader = arweave.transactions.getUploader(transaction); * while (!uploader.isComplete) { * await uploader.uploadChunk(); * console.log(`${uploader.pctComplete}%`); * } * ``` * * @param upload a Transaction object, a previously save progress object, or a transaction id. * @param data the data of the transaction. Required when resuming an upload. */ async getUploader(upload, data) { let uploader; if (data instanceof ArrayBuffer) { data = new Uint8Array(data); } if (upload instanceof transaction_1.default) { if (!data) { data = upload.data; } if (!(data instanceof Uint8Array)) { throw new Error("Data format is invalid"); } if (!upload.chunks) { await upload.prepareChunks(data); } uploader = new transaction_uploader_1.TransactionUploader(this.api, upload); if (!uploader.data || uploader.data.length === 0) { uploader.data = data; } } else { if (typeof upload === "string") { upload = await transaction_uploader_1.TransactionUploader.fromTransactionId(this.api, upload); } if (!data || !(data instanceof Uint8Array)) { throw new Error(`Must provide data when resuming upload`); } // upload should be a serialized upload. uploader = await transaction_uploader_1.TransactionUploader.fromSerialized(this.api, upload, data); } return uploader; } /** * Async generator version of uploader * * Usage example: * * ``` * for await (const uploader of arweave.transactions.upload(tx)) { * console.log(`${uploader.pctComplete}%`); * } * ``` * * @param upload a Transaction object, a previously save uploader, or a transaction id. * @param data the data of the transaction. Required when resuming an upload. */ upload(upload, data) { return __asyncGenerator(this, arguments, function* upload_1() { const uploader = yield __await(this.getUploader(upload, data)); while (!uploader.isComplete) { yield __await(uploader.uploadChunk()); yield yield __await(uploader); } return yield __await(uploader); }); } } exports["default"] = Transactions; //# sourceMappingURL=transactions.js.map /***/ }), /***/ 8379: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; 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; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const ArweaveUtils = __importStar(__webpack_require__(5160)); __webpack_require__(1317); class Wallets { constructor(api, crypto) { this.api = api; this.crypto = crypto; } /** * Get the wallet balance for the given address. * * @param {string} address - The arweave address to get the balance for. * * @returns {Promise} - Promise which resolves with a winston string balance. */ getBalance(address) { return this.api .get(`wallet/${address}/balance`, { transformResponse: [ /** * We need to specify a response transformer to override * the default JSON.parse behaviour, as this causes * balances to be converted to a number and we want to * return it as a winston string. * @param data */ function (data) { return data; }, ], }) .then((response) => { return response.data; }); } /** * Get the last transaction ID for the given wallet address. * * @param {string} address - The arweave address to get the transaction for. * * @returns {Promise} - Promise which resolves with a transaction ID. */ getLastTransactionID(address) { return this.api.get(`wallet/${address}/last_tx`).then((response) => { return response.data; }); } generate() { return this.crypto.generateJWK(); } async jwkToAddress(jwk) { if (!jwk || jwk === "use_wallet") { return this.getAddress(); } else { return this.getAddress(jwk); } } async getAddress(jwk) { if (!jwk || jwk === "use_wallet") { try { // @ts-ignore await window.arweaveWallet.connect(["ACCESS_ADDRESS"]); } catch (_a) { // Permission is already granted } // @ts-ignore return window.arweaveWallet.getActiveAddress(); } else { return this.ownerToAddress(jwk.n); } } async ownerToAddress(owner) { return ArweaveUtils.bufferTob64Url(await this.crypto.hash(ArweaveUtils.b64UrlToBuffer(owner))); } } exports["default"] = Wallets; //# sourceMappingURL=wallets.js.map /***/ }), /***/ 4586: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const bignumber_js_1 = __webpack_require__(4431); class Ar { constructor() { // Configure and assign the constructor function for the bignumber library. this.BigNum = (value, decimals) => { let instance = bignumber_js_1.BigNumber.clone({ DECIMAL_PLACES: decimals }); return new instance(value); }; } winstonToAr(winstonString, { formatted = false, decimals = 12, trim = true } = {}) { let number = this.stringToBigNum(winstonString, decimals).shiftedBy(-12); return formatted ? number.toFormat(decimals) : number.toFixed(decimals); } arToWinston(arString, { formatted = false } = {}) { let number = this.stringToBigNum(arString).shiftedBy(12); return formatted ? number.toFormat() : number.toFixed(0); } compare(winstonStringA, winstonStringB) { let a = this.stringToBigNum(winstonStringA); let b = this.stringToBigNum(winstonStringB); return a.comparedTo(b); } isEqual(winstonStringA, winstonStringB) { return this.compare(winstonStringA, winstonStringB) === 0; } isLessThan(winstonStringA, winstonStringB) { let a = this.stringToBigNum(winstonStringA); let b = this.stringToBigNum(winstonStringB); return a.isLessThan(b); } isGreaterThan(winstonStringA, winstonStringB) { let a = this.stringToBigNum(winstonStringA); let b = this.stringToBigNum(winstonStringB); return a.isGreaterThan(b); } add(winstonStringA, winstonStringB) { let a = this.stringToBigNum(winstonStringA); let b = this.stringToBigNum(winstonStringB); return a.plus(winstonStringB).toFixed(0); } sub(winstonStringA, winstonStringB) { let a = this.stringToBigNum(winstonStringA); let b = this.stringToBigNum(winstonStringB); return a.minus(winstonStringB).toFixed(0); } stringToBigNum(stringValue, decimalPlaces = 12) { return this.BigNum(stringValue, decimalPlaces); } } exports["default"] = Ar; //# sourceMappingURL=ar.js.map /***/ }), /***/ 3759: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const error_1 = __webpack_require__(5498); __webpack_require__(1317); class Blocks { constructor(api, network) { this.api = api; this.network = network; } /** * Gets a block by its "indep_hash" */ async get(indepHash) { const response = await this.api.get(`${Blocks.ENDPOINT}${indepHash}`); if (response.status === 200) { return response.data; } else { if (response.status === 404) { throw new error_1.default("BLOCK_NOT_FOUND" /* ArweaveErrorType.BLOCK_NOT_FOUND */); } else { throw new Error(`Error while loading block data: ${response}`); } } } /** * Gets current block data (ie. block with indep_hash = Network.getInfo().current) */ async getCurrent() { const { current } = await this.network.getInfo(); return await this.get(current); } } exports["default"] = Blocks; Blocks.ENDPOINT = "block/hash/"; //# sourceMappingURL=blocks.js.map /***/ }), /***/ 6879: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const error_1 = __webpack_require__(5498); const ArweaveUtils = __webpack_require__(8244); class Chunks { constructor(api) { this.api = api; } async getTransactionOffset(id) { const resp = await this.api.get(`tx/${id}/offset`); if (resp.status === 200) { return resp.data; } throw new Error(`Unable to get transaction offset: ${(0, error_1.getError)(resp)}`); } async getChunk(offset) { const resp = await this.api.get(`chunk/${offset}`); if (resp.status === 200) { return resp.data; } throw new Error(`Unable to get chunk: ${(0, error_1.getError)(resp)}`); } async getChunkData(offset) { const chunk = await this.getChunk(offset); const buf = ArweaveUtils.b64UrlToBuffer(chunk.chunk); return buf; } firstChunkOffset(offsetResponse) { return parseInt(offsetResponse.offset) - parseInt(offsetResponse.size) + 1; } async downloadChunkedData(id) { const offsetResponse = await this.getTransactionOffset(id); const size = parseInt(offsetResponse.size); const endOffset = parseInt(offsetResponse.offset); const startOffset = endOffset - size + 1; const data = new Uint8Array(size); let byte = 0; while (byte < size) { if (this.api.config.logging) { console.log(`[chunk] ${byte}/${size}`); } let chunkData; try { chunkData = await this.getChunkData(startOffset + byte); } catch (error) { console.error(`[chunk] Failed to fetch chunk at offset ${startOffset + byte}`); console.error(`[chunk] This could indicate that the chunk wasn't uploaded or hasn't yet seeded properly to a particular gateway/node`); } if (chunkData) { data.set(chunkData, byte); byte += chunkData.length; } else { throw new Error(`Couldn't complete data download at ${byte}/${size}`); } } return data; } } exports["default"] = Chunks; //# sourceMappingURL=chunks.js.map /***/ }), /***/ 536: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const ar_1 = __webpack_require__(4586); const api_1 = __webpack_require__(6874); const node_driver_1 = __webpack_require__(9363); const network_1 = __webpack_require__(2248); const transactions_1 = __webpack_require__(6935); const wallets_1 = __webpack_require__(7927); const transaction_1 = __webpack_require__(7825); const ArweaveUtils = __webpack_require__(8244); const silo_1 = __webpack_require__(1243); const chunks_1 = __webpack_require__(6879); const blocks_1 = __webpack_require__(3759); class Arweave { constructor(apiConfig) { this.api = new api_1.default(apiConfig); this.wallets = new wallets_1.default(this.api, Arweave.crypto); this.chunks = new chunks_1.default(this.api); this.transactions = new transactions_1.default(this.api, Arweave.crypto, this.chunks); this.silo = new silo_1.default(this.api, this.crypto, this.transactions); this.network = new network_1.default(this.api); this.blocks = new blocks_1.default(this.api, this.network); this.ar = new ar_1.default(); } /** @deprecated */ get crypto() { return Arweave.crypto; } /** @deprecated */ get utils() { return Arweave.utils; } getConfig() { return { api: this.api.getConfig(), crypto: null, }; } async createTransaction(attributes, jwk) { const transaction = {}; Object.assign(transaction, attributes); if (!attributes.data && !(attributes.target && attributes.quantity)) { throw new Error(`A new Arweave transaction must have a 'data' value, or 'target' and 'quantity' values.`); } if (attributes.owner == undefined) { if (jwk && jwk !== "use_wallet") { transaction.owner = jwk.n; } } if (attributes.last_tx == undefined) { transaction.last_tx = await this.transactions.getTransactionAnchor(); } if (typeof attributes.data === "string") { attributes.data = ArweaveUtils.stringToBuffer(attributes.data); } if (attributes.data instanceof ArrayBuffer) { attributes.data = new Uint8Array(attributes.data); } if (attributes.data && !(attributes.data instanceof Uint8Array)) { throw new Error("Expected data to be a string, Uint8Array or ArrayBuffer"); } if (attributes.reward == undefined) { const length = attributes.data ? attributes.data.byteLength : 0; transaction.reward = await this.transactions.getPrice(length, transaction.target); } // here we should call prepare chunk transaction.data_root = ""; transaction.data_size = attributes.data ? attributes.data.byteLength.toString() : "0"; transaction.data = attributes.data || new Uint8Array(0); const createdTransaction = new transaction_1.default(transaction); await createdTransaction.getSignatureData(); return createdTransaction; } async createSiloTransaction(attributes, jwk, siloUri) { const transaction = {}; Object.assign(transaction, attributes); if (!attributes.data) { throw new Error(`Silo transactions must have a 'data' value`); } if (!siloUri) { throw new Error(`No Silo URI specified.`); } if (attributes.target || attributes.quantity) { throw new Error(`Silo transactions can only be used for storing data, sending AR to other wallets isn't supported.`); } if (attributes.owner == undefined) { if (!jwk || !jwk.n) { throw new Error(`A new Arweave transaction must either have an 'owner' attribute, or you must provide the jwk parameter.`); } transaction.owner = jwk.n; } if (attributes.last_tx == undefined) { transaction.last_tx = await this.transactions.getTransactionAnchor(); } const siloResource = await this.silo.parseUri(siloUri); if (typeof attributes.data == "string") { const encrypted = await this.crypto.encrypt(ArweaveUtils.stringToBuffer(attributes.data), siloResource.getEncryptionKey()); transaction.reward = await this.transactions.getPrice(encrypted.byteLength); transaction.data = ArweaveUtils.bufferTob64Url(encrypted); } if (attributes.data instanceof Uint8Array) { const encrypted = await this.crypto.encrypt(attributes.data, siloResource.getEncryptionKey()); transaction.reward = await this.transactions.getPrice(encrypted.byteLength); transaction.data = ArweaveUtils.bufferTob64Url(encrypted); } const siloTransaction = new transaction_1.default(transaction); siloTransaction.addTag("Silo-Name", siloResource.getAccessKey()); siloTransaction.addTag("Silo-Version", `0.1.0`); return siloTransaction; } arql(query) { return this.api .post("/arql", query) .then((response) => response.data || []); } } exports["default"] = Arweave; Arweave.crypto = new node_driver_1.default(); Arweave.utils = ArweaveUtils; //# sourceMappingURL=common.js.map /***/ }), /***/ 7386: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; 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 __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const common_1 = __webpack_require__(536); common_1.default.init = function (apiConfig = {}) { function getDefaultConfig() { const defaults = { host: "arweave.net", port: 443, protocol: "https", }; if (!window || !window.location || !window.location.protocol || !window.location.hostname) { return defaults; } // window.location.protocol has a trailing colon (http:, https:, file: etc) const currentProtocol = window.location.protocol.replace(":", ""); const currentHost = window.location.hostname; const currentPort = window.location.port ? parseInt(window.location.port) : currentProtocol == "https" ? 443 : 80; const isLocal = ["localhost", "127.0.0.1"].includes(currentHost) || currentProtocol == "file"; // If we're running in what looks like a local dev environment // then default to using arweave.net if (isLocal) { return defaults; } return { host: currentHost, port: currentPort, protocol: currentProtocol, }; } const defaultConfig = getDefaultConfig(); const protocol = apiConfig.protocol || defaultConfig.protocol; const host = apiConfig.host || defaultConfig.host; const port = apiConfig.port || defaultConfig.port; return new common_1.default(Object.assign(Object.assign({}, apiConfig), { host, protocol, port })); }; window.Arweave = common_1.default; __exportStar(__webpack_require__(536), exports); exports["default"] = common_1.default; //# sourceMappingURL=index.js.map /***/ }), /***/ 6874: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const axios_1 = __webpack_require__(9669); class Api { constructor(config) { this.METHOD_GET = "GET"; this.METHOD_POST = "POST"; this.applyConfig(config); } applyConfig(config) { this.config = this.mergeDefaults(config); } getConfig() { return this.config; } mergeDefaults(config) { const protocol = config.protocol || "http"; const port = config.port || (protocol === "https" ? 443 : 80); return { host: config.host || "127.0.0.1", protocol, port, timeout: config.timeout || 20000, logging: config.logging || false, logger: config.logger || console.log, network: config.network, }; } async get(endpoint, config) { try { return await this.request().get(endpoint, config); } catch (error) { if (error.response && error.response.status) { return error.response; } throw error; } } async post(endpoint, body, config) { try { return await this.request().post(endpoint, body, config); } catch (error) { if (error.response && error.response.status) { return error.response; } throw error; } } /** * Get an AxiosInstance with the base configuration setup to fire off * a request to the network. */ request() { const headers = {}; if (this.config.network) { headers["x-network"] = this.config.network; } let instance = axios_1.default.create({ baseURL: `${this.config.protocol}://${this.config.host}:${this.config.port}`, timeout: this.config.timeout, maxContentLength: 1024 * 1024 * 512, headers, }); if (this.config.logging) { instance.interceptors.request.use((request) => { this.config.logger(`Requesting: ${request.baseURL}/${request.url}`); return request; }); instance.interceptors.response.use((response) => { this.config.logger(`Response: ${response.config.url} - ${response.status}`); return response; }); } return instance; } } exports["default"] = Api; //# sourceMappingURL=api.js.map /***/ }), /***/ 9363: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const ArweaveUtils = __webpack_require__(8244); class WebCryptoDriver { constructor() { this.keyLength = 4096; this.publicExponent = 0x10001; this.hashAlgorithm = "sha256"; if (!this.detectWebCrypto()) { throw new Error("SubtleCrypto not available!"); } this.driver = crypto.subtle; } async generateJWK() { let cryptoKey = await this.driver.generateKey({ name: "RSA-PSS", modulusLength: 4096, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), hash: { name: "SHA-256", }, }, true, ["sign"]); let jwk = await this.driver.exportKey("jwk", cryptoKey.privateKey); return { kty: jwk.kty, e: jwk.e, n: jwk.n, d: jwk.d, p: jwk.p, q: jwk.q, dp: jwk.dp, dq: jwk.dq, qi: jwk.qi, }; } async sign(jwk, data, { saltLength } = {}) { let signature = await this.driver.sign({ name: "RSA-PSS", saltLength: 32, }, await this.jwkToCryptoKey(jwk), data); return new Uint8Array(signature); } async hash(data, algorithm = "SHA-256") { let digest = await this.driver.digest(algorithm, data); return new Uint8Array(digest); } async verify(publicModulus, data, signature) { const publicKey = { kty: "RSA", e: "AQAB", n: publicModulus, }; const key = await this.jwkToPublicCryptoKey(publicKey); const verifyWith32 = this.driver.verify({ name: "RSA-PSS", saltLength: 32, }, key, signature, data); const verifyWith0 = this.driver.verify({ name: "RSA-PSS", saltLength: 0, }, key, signature, data); return verifyWith32 || verifyWith0; } async jwkToCryptoKey(jwk) { return this.driver.importKey("jwk", jwk, { name: "RSA-PSS", hash: { name: "SHA-256", }, }, false, ["sign"]); } async jwkToPublicCryptoKey(publicJwk) { return this.driver.importKey("jwk", publicJwk, { name: "RSA-PSS", hash: { name: "SHA-256", }, }, false, ["verify"]); } detectWebCrypto() { if (typeof crypto === "undefined") { return false; } const subtle = crypto === null || crypto === void 0 ? void 0 : crypto.subtle; if (subtle === undefined) { return false; } const names = [ "generateKey", "importKey", "exportKey", "digest", "sign", ]; return names.every((name) => typeof subtle[name] === "function"); } async encrypt(data, key, salt) { const initialKey = await this.driver.importKey("raw", typeof key == "string" ? ArweaveUtils.stringToBuffer(key) : key, { name: "PBKDF2", length: 32, }, false, ["deriveKey"]); // const salt = ArweaveUtils.stringToBuffer("salt"); // create a random string for deriving the key // const salt = this.driver.randomBytes(16).toString('hex'); const derivedkey = await this.driver.deriveKey({ name: "PBKDF2", salt: salt ? ArweaveUtils.stringToBuffer(salt) : ArweaveUtils.stringToBuffer("salt"), iterations: 100000, hash: "SHA-256", }, initialKey, { name: "AES-CBC", length: 256, }, false, ["encrypt", "decrypt"]); const iv = new Uint8Array(16); crypto.getRandomValues(iv); const encryptedData = await this.driver.encrypt({ name: "AES-CBC", iv: iv, }, derivedkey, data); return ArweaveUtils.concatBuffers([iv, encryptedData]); } async decrypt(encrypted, key, salt) { const initialKey = await this.driver.importKey("raw", typeof key == "string" ? ArweaveUtils.stringToBuffer(key) : key, { name: "PBKDF2", length: 32, }, false, ["deriveKey"]); // const salt = ArweaveUtils.stringToBuffer("pepper"); const derivedkey = await this.driver.deriveKey({ name: "PBKDF2", salt: salt ? ArweaveUtils.stringToBuffer(salt) : ArweaveUtils.stringToBuffer("salt"), iterations: 100000, hash: "SHA-256", }, initialKey, { name: "AES-CBC", length: 256, }, false, ["encrypt", "decrypt"]); const iv = encrypted.slice(0, 16); const data = await this.driver.decrypt({ name: "AES-CBC", iv: iv, }, derivedkey, encrypted.slice(16)); // We're just using concat to convert from an array buffer to uint8array return ArweaveUtils.concatBuffers([data]); } } exports["default"] = WebCryptoDriver; //# sourceMappingURL=webcrypto-driver.js.map /***/ }), /***/ 921: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const common_1 = __webpack_require__(536); async function deepHash(data) { if (Array.isArray(data)) { const tag = common_1.default.utils.concatBuffers([ common_1.default.utils.stringToBuffer("list"), common_1.default.utils.stringToBuffer(data.length.toString()), ]); return await deepHashChunks(data, await common_1.default.crypto.hash(tag, "SHA-384")); } const tag = common_1.default.utils.concatBuffers([ common_1.default.utils.stringToBuffer("blob"), common_1.default.utils.stringToBuffer(data.byteLength.toString()), ]); const taggedHash = common_1.default.utils.concatBuffers([ await common_1.default.crypto.hash(tag, "SHA-384"), await common_1.default.crypto.hash(data, "SHA-384"), ]); return await common_1.default.crypto.hash(taggedHash, "SHA-384"); } exports["default"] = deepHash; async function deepHashChunks(chunks, acc) { if (chunks.length < 1) { return acc; } const hashPair = common_1.default.utils.concatBuffers([ acc, await deepHash(chunks[0]), ]); const newAcc = await common_1.default.crypto.hash(hashPair, "SHA-384"); return await deepHashChunks(chunks.slice(1), newAcc); } //# sourceMappingURL=deepHash.js.map /***/ }), /***/ 5498: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getError = void 0; class ArweaveError extends Error { constructor(type, optional = {}) { if (optional.message) { super(optional.message); } else { super(); } this.type = type; this.response = optional.response; } getType() { return this.type; } } exports["default"] = ArweaveError; // Safely get error string // from an axios response, falling back to // resp.data, statusText or 'unknown'. // Note: a wrongly set content-type can // cause what is a json response to be interepted // as a string or Buffer, so we handle that too. function getError(resp) { let data = resp.data; if (typeof resp.data === "string") { try { data = JSON.parse(resp.data); } catch (e) { } } if (resp.data instanceof ArrayBuffer || resp.data instanceof Uint8Array) { try { data = JSON.parse(data.toString()); } catch (e) { } } return data ? data.error || data : resp.statusText || "unknown"; } exports.getError = getError; //# sourceMappingURL=error.js.map /***/ }), /***/ 8224: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(8764)["Buffer"]; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.debug = exports.validatePath = exports.arrayCompare = exports.bufferToInt = exports.intToBuffer = exports.arrayFlatten = exports.generateProofs = exports.buildLayers = exports.generateTransactionChunks = exports.generateTree = exports.computeRootHash = exports.generateLeaves = exports.chunkData = exports.MIN_CHUNK_SIZE = exports.MAX_CHUNK_SIZE = void 0; /** * @see {@link https://github.com/ArweaveTeam/arweave/blob/fbc381e0e36efffa45d13f2faa6199d3766edaa2/apps/arweave/src/ar_merkle.erl} */ const common_1 = __webpack_require__(536); const utils_1 = __webpack_require__(8244); exports.MAX_CHUNK_SIZE = 256 * 1024; exports.MIN_CHUNK_SIZE = 32 * 1024; const NOTE_SIZE = 32; const HASH_SIZE = 32; /** * Takes the input data and chunks it into (mostly) equal sized chunks. * The last chunk will be a bit smaller as it contains the remainder * from the chunking process. */ async function chunkData(data) { let chunks = []; let rest = data; let cursor = 0; while (rest.byteLength >= exports.MAX_CHUNK_SIZE) { let chunkSize = exports.MAX_CHUNK_SIZE; // If the total bytes left will produce a chunk < MIN_CHUNK_SIZE, // then adjust the amount we put in this 2nd last chunk. let nextChunkSize = rest.byteLength - exports.MAX_CHUNK_SIZE; if (nextChunkSize > 0 && nextChunkSize < exports.MIN_CHUNK_SIZE) { chunkSize = Math.ceil(rest.byteLength / 2); // console.log(`Last chunk will be: ${nextChunkSize} which is below ${MIN_CHUNK_SIZE}, adjusting current to ${chunkSize} with ${rest.byteLength} left.`) } const chunk = rest.slice(0, chunkSize); const dataHash = await common_1.default.crypto.hash(chunk); cursor += chunk.byteLength; chunks.push({ dataHash, minByteRange: cursor - chunk.byteLength, maxByteRange: cursor, }); rest = rest.slice(chunkSize); } chunks.push({ dataHash: await common_1.default.crypto.hash(rest), minByteRange: cursor, maxByteRange: cursor + rest.byteLength, }); return chunks; } exports.chunkData = chunkData; async function generateLeaves(chunks) { return Promise.all(chunks.map(async ({ dataHash, minByteRange, maxByteRange }) => { return { type: "leaf", id: await hash(await Promise.all([hash(dataHash), hash(intToBuffer(maxByteRange))])), dataHash: dataHash, minByteRange, maxByteRange, }; })); } exports.generateLeaves = generateLeaves; /** * Builds an arweave merkle tree and gets the root hash for the given input. */ async function computeRootHash(data) { const rootNode = await generateTree(data); return rootNode.id; } exports.computeRootHash = computeRootHash; async function generateTree(data) { const rootNode = await buildLayers(await generateLeaves(await chunkData(data))); return rootNode; } exports.generateTree = generateTree; /** * Generates the data_root, chunks & proofs * needed for a transaction. * * This also checks if the last chunk is a zero-length * chunk and discards that chunk and proof if so. * (we do not need to upload this zero length chunk) * * @param data */ async function generateTransactionChunks(data) { const chunks = await chunkData(data); const leaves = await generateLeaves(chunks); const root = await buildLayers(leaves); const proofs = await generateProofs(root); // Discard the last chunk & proof if it's zero length. const lastChunk = chunks.slice(-1)[0]; if (lastChunk.maxByteRange - lastChunk.minByteRange === 0) { chunks.splice(chunks.length - 1, 1); proofs.splice(proofs.length - 1, 1); } return { data_root: root.id, chunks, proofs, }; } exports.generateTransactionChunks = generateTransactionChunks; /** * Starting with the bottom layer of leaf nodes, hash every second pair * into a new branch node, push those branch nodes onto a new layer, * and then recurse, building up the tree to it's root, where the * layer only consists of two items. */ async function buildLayers(nodes, level = 0) { // If there is only 1 node left, this is going to be the root node if (nodes.length < 2) { const root = nodes[0]; // console.log("Root layer", root); return root; } const nextLayer = []; for (let i = 0; i < nodes.length; i += 2) { nextLayer.push(await hashBranch(nodes[i], nodes[i + 1])); } // console.log("Layer", nextLayer); return buildLayers(nextLayer, level + 1); } exports.buildLayers = buildLayers; /** * Recursively search through all branches of the tree, * and generate a proof for each leaf node. */ function generateProofs(root) { const proofs = resolveBranchProofs(root); if (!Array.isArray(proofs)) { return [proofs]; } return arrayFlatten(proofs); } exports.generateProofs = generateProofs; function resolveBranchProofs(node, proof = new Uint8Array(), depth = 0) { if (node.type == "leaf") { return { offset: node.maxByteRange - 1, proof: (0, utils_1.concatBuffers)([ proof, node.dataHash, intToBuffer(node.maxByteRange), ]), }; } if (node.type == "branch") { const partialProof = (0, utils_1.concatBuffers)([ proof, node.leftChild.id, node.rightChild.id, intToBuffer(node.byteRange), ]); return [ resolveBranchProofs(node.leftChild, partialProof, depth + 1), resolveBranchProofs(node.rightChild, partialProof, depth + 1), ]; } throw new Error(`Unexpected node type`); } function arrayFlatten(input) { const flat = []; input.forEach((item) => { if (Array.isArray(item)) { flat.push(...arrayFlatten(item)); } else { flat.push(item); } }); return flat; } exports.arrayFlatten = arrayFlatten; async function hashBranch(left, right) { if (!right) { return left; } let branch = { type: "branch", id: await hash([ await hash(left.id), await hash(right.id), await hash(intToBuffer(left.maxByteRange)), ]), byteRange: left.maxByteRange, maxByteRange: right.maxByteRange, leftChild: left, rightChild: right, }; return branch; } async function hash(data) { if (Array.isArray(data)) { data = common_1.default.utils.concatBuffers(data); } return new Uint8Array(await common_1.default.crypto.hash(data)); } function intToBuffer(note) { const buffer = new Uint8Array(NOTE_SIZE); for (var i = buffer.length - 1; i >= 0; i--) { var byte = note % 256; buffer[i] = byte; note = (note - byte) / 256; } return buffer; } exports.intToBuffer = intToBuffer; function bufferToInt(buffer) { let value = 0; for (var i = 0; i < buffer.length; i++) { value *= 256; value += buffer[i]; } return value; } exports.bufferToInt = bufferToInt; const arrayCompare = (a, b) => a.every((value, index) => b[index] === value); exports.arrayCompare = arrayCompare; async function validatePath(id, dest, leftBound, rightBound, path) { if (rightBound <= 0) { return false; } if (dest >= rightBound) { return validatePath(id, 0, rightBound - 1, rightBound, path); } if (dest < 0) { return validatePath(id, 0, 0, rightBound, path); } if (path.length == HASH_SIZE + NOTE_SIZE) { const pathData = path.slice(0, HASH_SIZE); const endOffsetBuffer = path.slice(pathData.length, pathData.length + NOTE_SIZE); const pathDataHash = await hash([ await hash(pathData), await hash(endOffsetBuffer), ]); let result = (0, exports.arrayCompare)(id, pathDataHash); if (result) { return { offset: rightBound - 1, leftBound: leftBound, rightBound: rightBound, chunkSize: rightBound - leftBound, }; } return false; } const left = path.slice(0, HASH_SIZE); const right = path.slice(left.length, left.length + HASH_SIZE); const offsetBuffer = path.slice(left.length + right.length, left.length + right.length + NOTE_SIZE); const offset = bufferToInt(offsetBuffer); const remainder = path.slice(left.length + right.length + offsetBuffer.length); const pathHash = await hash([ await hash(left), await hash(right), await hash(offsetBuffer), ]); if ((0, exports.arrayCompare)(id, pathHash)) { if (dest < offset) { return await validatePath(left, dest, leftBound, Math.min(rightBound, offset), remainder); } return await validatePath(right, dest, Math.max(leftBound, offset), rightBound, remainder); } return false; } exports.validatePath = validatePath; /** * Inspect an arweave chunk proof. * Takes proof, parses, reads and displays the values for console logging. * One proof section per line * Format: left,right,offset => hash */ async function debug(proof, output = "") { if (proof.byteLength < 1) { return output; } const left = proof.slice(0, HASH_SIZE); const right = proof.slice(left.length, left.length + HASH_SIZE); const offsetBuffer = proof.slice(left.length + right.length, left.length + right.length + NOTE_SIZE); const offset = bufferToInt(offsetBuffer); const remainder = proof.slice(left.length + right.length + offsetBuffer.length); const pathHash = await hash([ await hash(left), await hash(right), await hash(offsetBuffer), ]); const updatedOutput = `${output}\n${JSON.stringify(Buffer.from(left))},${JSON.stringify(Buffer.from(right))},${offset} => ${JSON.stringify(pathHash)}`; return debug(remainder, updatedOutput); } exports.debug = debug; //# sourceMappingURL=merkle.js.map /***/ }), /***/ 1246: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TransactionUploader = void 0; const transaction_1 = __webpack_require__(7825); const ArweaveUtils = __webpack_require__(8244); const error_1 = __webpack_require__(5498); const merkle_1 = __webpack_require__(8224); // Maximum amount of chunks we will upload in the body. const MAX_CHUNKS_IN_BODY = 1; // We assume these errors are intermitment and we can try again after a delay: // - not_joined // - timeout // - data_root_not_found (we may have hit a node that just hasn't seen it yet) // - exceeds_disk_pool_size_limit // We also try again after any kind of unexpected network errors // Errors from /chunk we should never try and continue on. const FATAL_CHUNK_UPLOAD_ERRORS = [ "invalid_json", "chunk_too_big", "data_path_too_big", "offset_too_big", "data_size_too_big", "chunk_proof_ratio_not_attractive", "invalid_proof", ]; // Amount we will delay on receiving an error response but do want to continue. const ERROR_DELAY = 1000 * 40; class TransactionUploader { constructor(api, transaction) { this.api = api; this.chunkIndex = 0; this.txPosted = false; this.lastRequestTimeEnd = 0; this.totalErrors = 0; // Not serialized. this.lastResponseStatus = 0; this.lastResponseError = ""; if (!transaction.id) { throw new Error(`Transaction is not signed`); } if (!transaction.chunks) { throw new Error(`Transaction chunks not prepared`); } // Make a copy of transaction, zeroing the data so we can serialize. this.data = transaction.data; this.transaction = new transaction_1.default(Object.assign({}, transaction, { data: new Uint8Array(0) })); } get isComplete() { return (this.txPosted && this.chunkIndex === this.transaction.chunks.chunks.length); } get totalChunks() { return this.transaction.chunks.chunks.length; } get uploadedChunks() { return this.chunkIndex; } get pctComplete() { return Math.trunc((this.uploadedChunks / this.totalChunks) * 100); } /** * Uploads the next part of the transaction. * On the first call this posts the transaction * itself and on any subsequent calls uploads the * next chunk until it completes. */ async uploadChunk(chunkIndex_) { if (this.isComplete) { throw new Error(`Upload is already complete`); } if (this.lastResponseError !== "") { this.totalErrors++; } else { this.totalErrors = 0; } // We have been trying for about an hour receiving an // error every time, so eventually bail. if (this.totalErrors === 100) { throw new Error(`Unable to complete upload: ${this.lastResponseStatus}: ${this.lastResponseError}`); } let delay = this.lastResponseError === "" ? 0 : Math.max(this.lastRequestTimeEnd + ERROR_DELAY - Date.now(), ERROR_DELAY); if (delay > 0) { // Jitter delay bcoz networks, subtract up to 30% from 40 seconds delay = delay - delay * Math.random() * 0.3; await new Promise((res) => setTimeout(res, delay)); } this.lastResponseError = ""; if (!this.txPosted) { await this.postTransaction(); return; } if (chunkIndex_) { this.chunkIndex = chunkIndex_; } const chunk = this.transaction.getChunk(chunkIndex_ || this.chunkIndex, this.data); const chunkOk = await (0, merkle_1.validatePath)(this.transaction.chunks.data_root, parseInt(chunk.offset), 0, parseInt(chunk.data_size), ArweaveUtils.b64UrlToBuffer(chunk.data_path)); if (!chunkOk) { throw new Error(`Unable to validate chunk ${this.chunkIndex}`); } // Catch network errors and turn them into objects with status -1 and an error message. const resp = await this.api .post(`chunk`, this.transaction.getChunk(this.chunkIndex, this.data)) .catch((e) => { console.error(e.message); return { status: -1, data: { error: e.message } }; }); this.lastRequestTimeEnd = Date.now(); this.lastResponseStatus = resp.status; if (this.lastResponseStatus == 200) { this.chunkIndex++; } else { this.lastResponseError = (0, error_1.getError)(resp); if (FATAL_CHUNK_UPLOAD_ERRORS.includes(this.lastResponseError)) { throw new Error(`Fatal error uploading chunk ${this.chunkIndex}: ${this.lastResponseError}`); } } } /** * Reconstructs an upload from its serialized state and data. * Checks if data matches the expected data_root. * * @param serialized * @param data */ static async fromSerialized(api, serialized, data) { if (!serialized || typeof serialized.chunkIndex !== "number" || typeof serialized.transaction !== "object") { throw new Error(`Serialized object does not match expected format.`); } // Everything looks ok, reconstruct the TransactionUpload, // prepare the chunks again and verify the data_root matches var transaction = new transaction_1.default(serialized.transaction); if (!transaction.chunks) { await transaction.prepareChunks(data); } const upload = new TransactionUploader(api, transaction); // Copy the serialized upload information, and data passed in. upload.chunkIndex = serialized.chunkIndex; upload.lastRequestTimeEnd = serialized.lastRequestTimeEnd; upload.lastResponseError = serialized.lastResponseError; upload.lastResponseStatus = serialized.lastResponseStatus; upload.txPosted = serialized.txPosted; upload.data = data; if (upload.transaction.data_root !== serialized.transaction.data_root) { throw new Error(`Data mismatch: Uploader doesn't match provided data.`); } return upload; } /** * Reconstruct an upload from the tx metadata, ie /tx/. * * @param api * @param id * @param data */ static async fromTransactionId(api, id) { const resp = await api.get(`tx/${id}`); if (resp.status !== 200) { throw new Error(`Tx ${id} not found: ${resp.status}`); } const transaction = resp.data; transaction.data = new Uint8Array(0); const serialized = { txPosted: true, chunkIndex: 0, lastResponseError: "", lastRequestTimeEnd: 0, lastResponseStatus: 0, transaction, }; return serialized; } toJSON() { return { chunkIndex: this.chunkIndex, transaction: this.transaction, lastRequestTimeEnd: this.lastRequestTimeEnd, lastResponseStatus: this.lastResponseStatus, lastResponseError: this.lastResponseError, txPosted: this.txPosted, }; } // POST to /tx async postTransaction() { const uploadInBody = this.totalChunks <= MAX_CHUNKS_IN_BODY; if (uploadInBody) { // Post the transaction with data. this.transaction.data = this.data; const resp = await this.api.post(`tx`, this.transaction).catch((e) => { console.error(e); return { status: -1, data: { error: e.message } }; }); this.lastRequestTimeEnd = Date.now(); this.lastResponseStatus = resp.status; this.transaction.data = new Uint8Array(0); if (resp.status >= 200 && resp.status < 300) { // We are complete. this.txPosted = true; this.chunkIndex = MAX_CHUNKS_IN_BODY; return; } this.lastResponseError = (0, error_1.getError)(resp); throw new Error(`Unable to upload transaction: ${resp.status}, ${this.lastResponseError}`); } // Post the transaction with no data. const resp = await this.api.post(`tx`, this.transaction); this.lastRequestTimeEnd = Date.now(); this.lastResponseStatus = resp.status; if (!(resp.status >= 200 && resp.status < 300)) { this.lastResponseError = (0, error_1.getError)(resp); throw new Error(`Unable to upload transaction: ${resp.status}, ${this.lastResponseError}`); } this.txPosted = true; } } exports.TransactionUploader = TransactionUploader; //# sourceMappingURL=transaction-uploader.js.map /***/ }), /***/ 7825: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Tag = void 0; const ArweaveUtils = __webpack_require__(8244); const deepHash_1 = __webpack_require__(921); const merkle_1 = __webpack_require__(8224); class BaseObject { get(field, options) { if (!Object.getOwnPropertyNames(this).includes(field)) { throw new Error(`Field "${field}" is not a property of the Arweave Transaction class.`); } // Handle fields that are Uint8Arrays. // To maintain compat we encode them to b64url // if decode option is not specificed. if (this[field] instanceof Uint8Array) { if (options && options.decode && options.string) { return ArweaveUtils.bufferToString(this[field]); } if (options && options.decode && !options.string) { return this[field]; } return ArweaveUtils.bufferTob64Url(this[field]); } if (options && options.decode == true) { if (options && options.string) { return ArweaveUtils.b64UrlToString(this[field]); } return ArweaveUtils.b64UrlToBuffer(this[field]); } return this[field]; } } class Tag extends BaseObject { constructor(name, value, decode = false) { super(); this.name = name; this.value = value; } } exports.Tag = Tag; class Transaction extends BaseObject { constructor(attributes = {}) { super(); this.format = 2; this.id = ""; this.last_tx = ""; this.owner = ""; this.tags = []; this.target = ""; this.quantity = "0"; this.data_size = "0"; this.data = new Uint8Array(); this.data_root = ""; this.reward = "0"; this.signature = ""; Object.assign(this, attributes); // If something passes in a Tx that has been toJSON'ed and back, // or where the data was filled in from /tx/data endpoint. // data will be b64url encoded, so decode it. if (typeof this.data === "string") { this.data = ArweaveUtils.b64UrlToBuffer(this.data); } if (attributes.tags) { this.tags = attributes.tags.map((tag) => { return new Tag(tag.name, tag.value); }); } } addTag(name, value) { this.tags.push(new Tag(ArweaveUtils.stringToB64Url(name), ArweaveUtils.stringToB64Url(value))); } toJSON() { return { format: this.format, id: this.id, last_tx: this.last_tx, owner: this.owner, tags: this.tags, target: this.target, quantity: this.quantity, data: ArweaveUtils.bufferTob64Url(this.data), data_size: this.data_size, data_root: this.data_root, data_tree: this.data_tree, reward: this.reward, signature: this.signature, }; } setOwner(owner) { this.owner = owner; } setSignature({ id, owner, reward, tags, signature, }) { this.id = id; this.owner = owner; if (reward) this.reward = reward; if (tags) this.tags = tags; this.signature = signature; } async prepareChunks(data) { // Note: we *do not* use `this.data`, the caller may be // operating on a transaction with an zero length data field. // This function computes the chunks for the data passed in and // assigns the result to this transaction. It should not read the // data *from* this transaction. if (!this.chunks && data.byteLength > 0) { this.chunks = await (0, merkle_1.generateTransactionChunks)(data); this.data_root = ArweaveUtils.bufferTob64Url(this.chunks.data_root); } if (!this.chunks && data.byteLength === 0) { this.chunks = { chunks: [], data_root: new Uint8Array(), proofs: [], }; this.data_root = ""; } } // Returns a chunk in a format suitable for posting to /chunk. // Similar to `prepareChunks()` this does not operate `this.data`, // instead using the data passed in. getChunk(idx, data) { if (!this.chunks) { throw new Error(`Chunks have not been prepared`); } const proof = this.chunks.proofs[idx]; const chunk = this.chunks.chunks[idx]; return { data_root: this.data_root, data_size: this.data_size, data_path: ArweaveUtils.bufferTob64Url(proof.proof), offset: proof.offset.toString(), chunk: ArweaveUtils.bufferTob64Url(data.slice(chunk.minByteRange, chunk.maxByteRange)), }; } async getSignatureData() { switch (this.format) { case 1: let tags = this.tags.reduce((accumulator, tag) => { return ArweaveUtils.concatBuffers([ accumulator, tag.get("name", { decode: true, string: false }), tag.get("value", { decode: true, string: false }), ]); }, new Uint8Array()); return ArweaveUtils.concatBuffers([ this.get("owner", { decode: true, string: false }), this.get("target", { decode: true, string: false }), this.get("data", { decode: true, string: false }), ArweaveUtils.stringToBuffer(this.quantity), ArweaveUtils.stringToBuffer(this.reward), this.get("last_tx", { decode: true, string: false }), tags, ]); case 2: if (!this.data_root) { await this.prepareChunks(this.data); } const tagList = this.tags.map((tag) => [ tag.get("name", { decode: true, string: false }), tag.get("value", { decode: true, string: false }), ]); return await (0, deepHash_1.default)([ ArweaveUtils.stringToBuffer(this.format.toString()), this.get("owner", { decode: true, string: false }), this.get("target", { decode: true, string: false }), ArweaveUtils.stringToBuffer(this.quantity), ArweaveUtils.stringToBuffer(this.reward), this.get("last_tx", { decode: true, string: false }), tagList, ArweaveUtils.stringToBuffer(this.data_size), this.get("data_root", { decode: true, string: false }), ]); default: throw new Error(`Unexpected transaction format: ${this.format}`); } } } exports["default"] = Transaction; //# sourceMappingURL=transaction.js.map /***/ }), /***/ 8244: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.b64UrlDecode = exports.b64UrlEncode = exports.bufferTob64Url = exports.bufferTob64 = exports.b64UrlToBuffer = exports.stringToB64Url = exports.stringToBuffer = exports.bufferToString = exports.b64UrlToString = exports.concatBuffers = void 0; const B64js = __webpack_require__(9742); function concatBuffers(buffers) { let total_length = 0; for (let i = 0; i < buffers.length; i++) { total_length += buffers[i].byteLength; } let temp = new Uint8Array(total_length); let offset = 0; temp.set(new Uint8Array(buffers[0]), offset); offset += buffers[0].byteLength; for (let i = 1; i < buffers.length; i++) { temp.set(new Uint8Array(buffers[i]), offset); offset += buffers[i].byteLength; } return temp; } exports.concatBuffers = concatBuffers; function b64UrlToString(b64UrlString) { let buffer = b64UrlToBuffer(b64UrlString); // TextEncoder will be available in browsers, but not in node if (typeof TextDecoder == "undefined") { const TextDecoder = (__webpack_require__(9539).TextDecoder); return new TextDecoder("utf-8", { fatal: true }).decode(buffer); } return new TextDecoder("utf-8", { fatal: true }).decode(buffer); } exports.b64UrlToString = b64UrlToString; function bufferToString(buffer) { // TextEncoder will be available in browsers, but not in node if (typeof TextDecoder == "undefined") { const TextDecoder = (__webpack_require__(9539).TextDecoder); return new TextDecoder("utf-8", { fatal: true }).decode(buffer); } return new TextDecoder("utf-8", { fatal: true }).decode(buffer); } exports.bufferToString = bufferToString; function stringToBuffer(string) { // TextEncoder will be available in browsers, but not in node if (typeof TextEncoder == "undefined") { const TextEncoder = (__webpack_require__(9539).TextEncoder); return new TextEncoder().encode(string); } return new TextEncoder().encode(string); } exports.stringToBuffer = stringToBuffer; function stringToB64Url(string) { return bufferTob64Url(stringToBuffer(string)); } exports.stringToB64Url = stringToB64Url; function b64UrlToBuffer(b64UrlString) { return new Uint8Array(B64js.toByteArray(b64UrlDecode(b64UrlString))); } exports.b64UrlToBuffer = b64UrlToBuffer; function bufferTob64(buffer) { return B64js.fromByteArray(new Uint8Array(buffer)); } exports.bufferTob64 = bufferTob64; function bufferTob64Url(buffer) { return b64UrlEncode(bufferTob64(buffer)); } exports.bufferTob64Url = bufferTob64Url; function b64UrlEncode(b64UrlString) { return b64UrlString .replace(/\+/g, "-") .replace(/\//g, "_") .replace(/\=/g, ""); } exports.b64UrlEncode = b64UrlEncode; function b64UrlDecode(b64UrlString) { b64UrlString = b64UrlString.replace(/\-/g, "+").replace(/\_/g, "/"); let padding; b64UrlString.length % 4 == 0 ? (padding = 0) : (padding = 4 - (b64UrlString.length % 4)); return b64UrlString.concat("=".repeat(padding)); } exports.b64UrlDecode = b64UrlDecode; //# sourceMappingURL=utils.js.map /***/ }), /***/ 2248: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class Network { constructor(api) { this.api = api; } getInfo() { return this.api.get(`info`).then((response) => { return response.data; }); } getPeers() { return this.api.get(`peers`).then((response) => { return response.data; }); } } exports["default"] = Network; //# sourceMappingURL=network.js.map /***/ }), /***/ 1243: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SiloResource = void 0; const ArweaveUtils = __webpack_require__(8244); class Silo { constructor(api, crypto, transactions) { this.api = api; this.crypto = crypto; this.transactions = transactions; } async get(siloURI) { if (!siloURI) { throw new Error(`No Silo URI specified`); } const resource = await this.parseUri(siloURI); const ids = await this.transactions.search("Silo-Name", resource.getAccessKey()); if (ids.length == 0) { throw new Error(`No data could be found for the Silo URI: ${siloURI}`); } const transaction = await this.transactions.get(ids[0]); if (!transaction) { throw new Error(`No data could be found for the Silo URI: ${siloURI}`); } const encrypted = transaction.get("data", { decode: true, string: false }); return this.crypto.decrypt(encrypted, resource.getEncryptionKey()); } async readTransactionData(transaction, siloURI) { if (!siloURI) { throw new Error(`No Silo URI specified`); } const resource = await this.parseUri(siloURI); const encrypted = transaction.get("data", { decode: true, string: false }); return this.crypto.decrypt(encrypted, resource.getEncryptionKey()); } async parseUri(siloURI) { const parsed = siloURI.match(/^([a-z0-9-_]+)\.([0-9]+)/i); if (!parsed) { throw new Error(`Invalid Silo name, must be a name in the format of [a-z0-9]+.[0-9]+, e.g. 'bubble.7'`); } const siloName = parsed[1]; const hashIterations = Math.pow(2, parseInt(parsed[2])); const digest = await this.hash(ArweaveUtils.stringToBuffer(siloName), hashIterations); const accessKey = ArweaveUtils.bufferTob64(digest.slice(0, 15)); const encryptionkey = await this.hash(digest.slice(16, 31), 1); return new SiloResource(siloURI, accessKey, encryptionkey); } async hash(input, iterations) { let digest = await this.crypto.hash(input); for (let count = 0; count < iterations - 1; count++) { digest = await this.crypto.hash(digest); } return digest; } } exports["default"] = Silo; class SiloResource { constructor(uri, accessKey, encryptionKey) { this.uri = uri; this.accessKey = accessKey; this.encryptionKey = encryptionKey; } getUri() { return this.uri; } getAccessKey() { return this.accessKey; } getEncryptionKey() { return this.encryptionKey; } } exports.SiloResource = SiloResource; //# sourceMappingURL=silo.js.map /***/ }), /***/ 6935: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); const error_1 = __webpack_require__(5498); const transaction_1 = __webpack_require__(7825); const ArweaveUtils = __webpack_require__(8244); const transaction_uploader_1 = __webpack_require__(1246); __webpack_require__(1317); class Transactions { constructor(api, crypto, chunks) { this.api = api; this.crypto = crypto; this.chunks = chunks; } getTransactionAnchor() { /** * Maintain compatibility with erdjs which sets a global axios.defaults.transformResponse * in order to overcome some other issue in: https://github.com/axios/axios/issues/983 * * However, this introduces a problem with ardrive-js, so we will enforce * config = {transformResponse: []} where we do not require a transform */ return this.api .get(`tx_anchor`, { transformResponse: [] }) .then((response) => { return response.data; }); } getPrice(byteSize, targetAddress) { let endpoint = targetAddress ? `price/${byteSize}/${targetAddress}` : `price/${byteSize}`; return this.api .get(endpoint, { transformResponse: [ /** * We need to specify a response transformer to override * the default JSON.parse behavior, as this causes * winston to be converted to a number and we want to * return it as a winston string. * @param data */ function (data) { return data; }, ], }) .then((response) => { return response.data; }); } async get(id) { const response = await this.api.get(`tx/${id}`); if (response.status == 200) { const data_size = parseInt(response.data.data_size); if (response.data.format >= 2 && data_size > 0 && data_size <= 1024 * 1024 * 12) { const data = await this.getData(id); return new transaction_1.default(Object.assign(Object.assign({}, response.data), { data })); } return new transaction_1.default(Object.assign(Object.assign({}, response.data), { format: response.data.format || 1 })); } if (response.status == 404) { throw new error_1.default("TX_NOT_FOUND" /* ArweaveErrorType.TX_NOT_FOUND */); } if (response.status == 410) { throw new error_1.default("TX_FAILED" /* ArweaveErrorType.TX_FAILED */); } throw new error_1.default("TX_INVALID" /* ArweaveErrorType.TX_INVALID */); } fromRaw(attributes) { return new transaction_1.default(attributes); } async search(tagName, tagValue) { return this.api .post(`arql`, { op: "equals", expr1: tagName, expr2: tagValue, }) .then((response) => { if (!response.data) { return []; } return response.data; }); } getStatus(id) { return this.api.get(`tx/${id}/status`).then((response) => { if (response.status == 200) { return { status: 200, confirmed: response.data, }; } return { status: response.status, confirmed: null, }; }); } async getData(id, options) { let data = undefined; try { data = await this.chunks.downloadChunkedData(id); } catch (error) { console.error(`Error while trying to download chunked data for ${id}`); console.error(error); } if (!data) { console.warn(`Falling back to gateway cache for ${id}`); try { data = (await this.api.get(`/${id}`)).data; } catch (error) { console.error(`Error while trying to download contiguous data from gateway cache for ${id}`); console.error(error); } } if (!data) { throw new Error(`${id} was not found!`); } if (options && options.decode && !options.string) { return data; } if (options && options.decode && options.string) { return ArweaveUtils.bufferToString(data); } // Since decode wasn't requested, caller expects b64url encoded data. return ArweaveUtils.bufferTob64Url(data); } async sign(transaction, jwk, options) { if (!jwk && (typeof window === "undefined" || !window.arweaveWallet)) { throw new Error(`A new Arweave transaction must provide the jwk parameter.`); } else if (!jwk || jwk === "use_wallet") { try { const existingPermissions = await window.arweaveWallet.getPermissions(); if (!existingPermissions.includes("SIGN_TRANSACTION")) await window.arweaveWallet.connect(["SIGN_TRANSACTION"]); } catch (_a) { // Permission is already granted } const signedTransaction = await window.arweaveWallet.sign(transaction, options); transaction.setSignature({ id: signedTransaction.id, owner: signedTransaction.owner, reward: signedTransaction.reward, tags: signedTransaction.tags, signature: signedTransaction.signature, }); } else { transaction.setOwner(jwk.n); let dataToSign = await transaction.getSignatureData(); let rawSignature = await this.crypto.sign(jwk, dataToSign, options); let id = await this.crypto.hash(rawSignature); transaction.setSignature({ id: ArweaveUtils.bufferTob64Url(id), owner: jwk.n, signature: ArweaveUtils.bufferTob64Url(rawSignature), }); } } async verify(transaction) { const signaturePayload = await transaction.getSignatureData(); /** * The transaction ID should be a SHA-256 hash of the raw signature bytes, so this needs * to be recalculated from the signature and checked against the transaction ID. */ const rawSignature = transaction.get("signature", { decode: true, string: false, }); const expectedId = ArweaveUtils.bufferTob64Url(await this.crypto.hash(rawSignature)); if (transaction.id !== expectedId) { throw new Error(`Invalid transaction signature or ID! The transaction ID doesn't match the expected SHA-256 hash of the signature.`); } /** * Now verify the signature is valid and signed by the owner wallet (owner field = originating wallet public key). */ return this.crypto.verify(transaction.owner, signaturePayload, rawSignature); } async post(transaction) { if (typeof transaction === "string") { transaction = new transaction_1.default(JSON.parse(transaction)); } else if (typeof transaction.readInt32BE === "function") { transaction = new transaction_1.default(JSON.parse(transaction.toString())); } else if (typeof transaction === "object" && !(transaction instanceof transaction_1.default)) { transaction = new transaction_1.default(transaction); } if (!(transaction instanceof transaction_1.default)) { throw new Error(`Must be Transaction object`); } if (!transaction.chunks) { await transaction.prepareChunks(transaction.data); } const uploader = await this.getUploader(transaction, transaction.data); // Emulate existing error & return value behavior. try { while (!uploader.isComplete) { await uploader.uploadChunk(); } } catch (e) { if (uploader.lastResponseStatus > 0) { return { status: uploader.lastResponseStatus, statusText: uploader.lastResponseError, data: { error: uploader.lastResponseError, }, }; } throw e; } return { status: 200, statusText: "OK", data: {}, }; } /** * Gets an uploader than can be used to upload a transaction chunk by chunk, giving progress * and the ability to resume. * * Usage example: * * ``` * const uploader = arweave.transactions.getUploader(transaction); * while (!uploader.isComplete) { * await uploader.uploadChunk(); * console.log(`${uploader.pctComplete}%`); * } * ``` * * @param upload a Transaction object, a previously save progress object, or a transaction id. * @param data the data of the transaction. Required when resuming an upload. */ async getUploader(upload, data) { let uploader; if (data instanceof ArrayBuffer) { data = new Uint8Array(data); } if (upload instanceof transaction_1.default) { if (!data) { data = upload.data; } if (!(data instanceof Uint8Array)) { throw new Error("Data format is invalid"); } if (!upload.chunks) { await upload.prepareChunks(data); } uploader = new transaction_uploader_1.TransactionUploader(this.api, upload); if (!uploader.data || uploader.data.length === 0) { uploader.data = data; } } else { if (typeof upload === "string") { upload = await transaction_uploader_1.TransactionUploader.fromTransactionId(this.api, upload); } if (!data || !(data instanceof Uint8Array)) { throw new Error(`Must provide data when resuming upload`); } // upload should be a serialized upload. uploader = await transaction_uploader_1.TransactionUploader.fromSerialized(this.api, upload, data); } return uploader; } /** * Async generator version of uploader * * Usage example: * * ``` * for await (const uploader of arweave.transactions.upload(tx)) { * console.log(`${uploader.pctComplete}%`); * } * ``` * * @param upload a Transaction object, a previously save uploader, or a transaction id. * @param data the data of the transaction. Required when resuming an upload. */ upload(upload, data) { return __asyncGenerator(this, arguments, function* upload_1() { const uploader = yield __await(this.getUploader(upload, data)); while (!uploader.isComplete) { yield __await(uploader.uploadChunk()); yield yield __await(uploader); } return yield __await(uploader); }); } } exports["default"] = Transactions; //# sourceMappingURL=transactions.js.map /***/ }), /***/ 7927: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const ArweaveUtils = __webpack_require__(8244); __webpack_require__(1317); class Wallets { constructor(api, crypto) { this.api = api; this.crypto = crypto; } /** * Get the wallet balance for the given address. * * @param {string} address - The arweave address to get the balance for. * * @returns {Promise} - Promise which resolves with a winston string balance. */ getBalance(address) { return this.api .get(`wallet/${address}/balance`, { transformResponse: [ /** * We need to specify a response transformer to override * the default JSON.parse behaviour, as this causes * balances to be converted to a number and we want to * return it as a winston string. * @param data */ function (data) { return data; }, ], }) .then((response) => { return response.data; }); } /** * Get the last transaction ID for the given wallet address. * * @param {string} address - The arweave address to get the transaction for. * * @returns {Promise} - Promise which resolves with a transaction ID. */ getLastTransactionID(address) { return this.api.get(`wallet/${address}/last_tx`).then((response) => { return response.data; }); } generate() { return this.crypto.generateJWK(); } async jwkToAddress(jwk) { if (!jwk || jwk === "use_wallet") { return this.getAddress(); } else { return this.getAddress(jwk); } } async getAddress(jwk) { if (!jwk || jwk === "use_wallet") { try { // @ts-ignore await window.arweaveWallet.connect(["ACCESS_ADDRESS"]); } catch (_a) { // Permission is already granted } // @ts-ignore return window.arweaveWallet.getActiveAddress(); } else { return this.ownerToAddress(jwk.n); } } async ownerToAddress(owner) { return ArweaveUtils.bufferTob64Url(await this.crypto.hash(ArweaveUtils.b64UrlToBuffer(owner))); } } exports["default"] = Wallets; //# sourceMappingURL=wallets.js.map /***/ }), /***/ 9809: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const asn1 = exports; asn1.bignum = __webpack_require__(3550); asn1.define = (__webpack_require__(2500).define); asn1.base = __webpack_require__(1979); asn1.constants = __webpack_require__(6826); asn1.decoders = __webpack_require__(8307); asn1.encoders = __webpack_require__(6579); /***/ }), /***/ 2500: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const encoders = __webpack_require__(6579); const decoders = __webpack_require__(8307); const inherits = __webpack_require__(5717); const api = exports; api.define = function define(name, body) { return new Entity(name, body); }; function Entity(name, body) { this.name = name; this.body = body; this.decoders = {}; this.encoders = {}; } Entity.prototype._createNamed = function createNamed(Base) { const name = this.name; function Generated(entity) { this._initNamed(entity, name); } inherits(Generated, Base); Generated.prototype._initNamed = function _initNamed(entity, name) { Base.call(this, entity, name); }; return new Generated(this); }; Entity.prototype._getDecoder = function _getDecoder(enc) { enc = enc || 'der'; // Lazily create decoder if (!this.decoders.hasOwnProperty(enc)) this.decoders[enc] = this._createNamed(decoders[enc]); return this.decoders[enc]; }; Entity.prototype.decode = function decode(data, enc, options) { return this._getDecoder(enc).decode(data, options); }; Entity.prototype._getEncoder = function _getEncoder(enc) { enc = enc || 'der'; // Lazily create encoder if (!this.encoders.hasOwnProperty(enc)) this.encoders[enc] = this._createNamed(encoders[enc]); return this.encoders[enc]; }; Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { return this._getEncoder(enc).encode(data, reporter); }; /***/ }), /***/ 6625: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const inherits = __webpack_require__(5717); const Reporter = (__webpack_require__(8465)/* .Reporter */ .b); const Buffer = (__webpack_require__(2399).Buffer); function DecoderBuffer(base, options) { Reporter.call(this, options); if (!Buffer.isBuffer(base)) { this.error('Input not Buffer'); return; } this.base = base; this.offset = 0; this.length = base.length; } inherits(DecoderBuffer, Reporter); exports.C = DecoderBuffer; DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) { if (data instanceof DecoderBuffer) { return true; } // Or accept compatible API const isCompatible = typeof data === 'object' && Buffer.isBuffer(data.base) && data.constructor.name === 'DecoderBuffer' && typeof data.offset === 'number' && typeof data.length === 'number' && typeof data.save === 'function' && typeof data.restore === 'function' && typeof data.isEmpty === 'function' && typeof data.readUInt8 === 'function' && typeof data.skip === 'function' && typeof data.raw === 'function'; return isCompatible; }; DecoderBuffer.prototype.save = function save() { return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; }; DecoderBuffer.prototype.restore = function restore(save) { // Return skipped data const res = new DecoderBuffer(this.base); res.offset = save.offset; res.length = this.offset; this.offset = save.offset; Reporter.prototype.restore.call(this, save.reporter); return res; }; DecoderBuffer.prototype.isEmpty = function isEmpty() { return this.offset === this.length; }; DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { if (this.offset + 1 <= this.length) return this.base.readUInt8(this.offset++, true); else return this.error(fail || 'DecoderBuffer overrun'); }; DecoderBuffer.prototype.skip = function skip(bytes, fail) { if (!(this.offset + bytes <= this.length)) return this.error(fail || 'DecoderBuffer overrun'); const res = new DecoderBuffer(this.base); // Share reporter state res._reporterState = this._reporterState; res.offset = this.offset; res.length = this.offset + bytes; this.offset += bytes; return res; }; DecoderBuffer.prototype.raw = function raw(save) { return this.base.slice(save ? save.offset : this.offset, this.length); }; function EncoderBuffer(value, reporter) { if (Array.isArray(value)) { this.length = 0; this.value = value.map(function(item) { if (!EncoderBuffer.isEncoderBuffer(item)) item = new EncoderBuffer(item, reporter); this.length += item.length; return item; }, this); } else if (typeof value === 'number') { if (!(0 <= value && value <= 0xff)) return reporter.error('non-byte EncoderBuffer value'); this.value = value; this.length = 1; } else if (typeof value === 'string') { this.value = value; this.length = Buffer.byteLength(value); } else if (Buffer.isBuffer(value)) { this.value = value; this.length = value.length; } else { return reporter.error('Unsupported type: ' + typeof value); } } exports.R = EncoderBuffer; EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) { if (data instanceof EncoderBuffer) { return true; } // Or accept compatible API const isCompatible = typeof data === 'object' && data.constructor.name === 'EncoderBuffer' && typeof data.length === 'number' && typeof data.join === 'function'; return isCompatible; }; EncoderBuffer.prototype.join = function join(out, offset) { if (!out) out = Buffer.alloc(this.length); if (!offset) offset = 0; if (this.length === 0) return out; if (Array.isArray(this.value)) { this.value.forEach(function(item) { item.join(out, offset); offset += item.length; }); } else { if (typeof this.value === 'number') out[offset] = this.value; else if (typeof this.value === 'string') out.write(this.value, offset); else if (Buffer.isBuffer(this.value)) this.value.copy(out, offset); offset += this.length; } return out; }; /***/ }), /***/ 1979: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const base = exports; base.Reporter = (__webpack_require__(8465)/* .Reporter */ .b); base.DecoderBuffer = (__webpack_require__(6625)/* .DecoderBuffer */ .C); base.EncoderBuffer = (__webpack_require__(6625)/* .EncoderBuffer */ .R); base.Node = __webpack_require__(1949); /***/ }), /***/ 1949: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; const Reporter = (__webpack_require__(8465)/* .Reporter */ .b); const EncoderBuffer = (__webpack_require__(6625)/* .EncoderBuffer */ .R); const DecoderBuffer = (__webpack_require__(6625)/* .DecoderBuffer */ .C); const assert = __webpack_require__(9746); // Supported tags const tags = [ 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' ]; // Public methods list const methods = [ 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', 'any', 'contains' ].concat(tags); // Overrided methods list const overrided = [ '_peekTag', '_decodeTag', '_use', '_decodeStr', '_decodeObjid', '_decodeTime', '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', '_encodeNull', '_encodeInt', '_encodeBool' ]; function Node(enc, parent, name) { const state = {}; this._baseState = state; state.name = name; state.enc = enc; state.parent = parent || null; state.children = null; // State state.tag = null; state.args = null; state.reverseArgs = null; state.choice = null; state.optional = false; state.any = false; state.obj = false; state.use = null; state.useDecoder = null; state.key = null; state['default'] = null; state.explicit = null; state.implicit = null; state.contains = null; // Should create new instance on each method if (!state.parent) { state.children = []; this._wrap(); } } module.exports = Node; const stateProps = [ 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', 'implicit', 'contains' ]; Node.prototype.clone = function clone() { const state = this._baseState; const cstate = {}; stateProps.forEach(function(prop) { cstate[prop] = state[prop]; }); const res = new this.constructor(cstate.parent); res._baseState = cstate; return res; }; Node.prototype._wrap = function wrap() { const state = this._baseState; methods.forEach(function(method) { this[method] = function _wrappedMethod() { const clone = new this.constructor(this); state.children.push(clone); return clone[method].apply(clone, arguments); }; }, this); }; Node.prototype._init = function init(body) { const state = this._baseState; assert(state.parent === null); body.call(this); // Filter children state.children = state.children.filter(function(child) { return child._baseState.parent === this; }, this); assert.equal(state.children.length, 1, 'Root node can have only one child'); }; Node.prototype._useArgs = function useArgs(args) { const state = this._baseState; // Filter children and args const children = args.filter(function(arg) { return arg instanceof this.constructor; }, this); args = args.filter(function(arg) { return !(arg instanceof this.constructor); }, this); if (children.length !== 0) { assert(state.children === null); state.children = children; // Replace parent to maintain backward link children.forEach(function(child) { child._baseState.parent = this; }, this); } if (args.length !== 0) { assert(state.args === null); state.args = args; state.reverseArgs = args.map(function(arg) { if (typeof arg !== 'object' || arg.constructor !== Object) return arg; const res = {}; Object.keys(arg).forEach(function(key) { if (key == (key | 0)) key |= 0; const value = arg[key]; res[value] = key; }); return res; }); } }; // // Overrided methods // overrided.forEach(function(method) { Node.prototype[method] = function _overrided() { const state = this._baseState; throw new Error(method + ' not implemented for encoding: ' + state.enc); }; }); // // Public methods // tags.forEach(function(tag) { Node.prototype[tag] = function _tagMethod() { const state = this._baseState; const args = Array.prototype.slice.call(arguments); assert(state.tag === null); state.tag = tag; this._useArgs(args); return this; }; }); Node.prototype.use = function use(item) { assert(item); const state = this._baseState; assert(state.use === null); state.use = item; return this; }; Node.prototype.optional = function optional() { const state = this._baseState; state.optional = true; return this; }; Node.prototype.def = function def(val) { const state = this._baseState; assert(state['default'] === null); state['default'] = val; state.optional = true; return this; }; Node.prototype.explicit = function explicit(num) { const state = this._baseState; assert(state.explicit === null && state.implicit === null); state.explicit = num; return this; }; Node.prototype.implicit = function implicit(num) { const state = this._baseState; assert(state.explicit === null && state.implicit === null); state.implicit = num; return this; }; Node.prototype.obj = function obj() { const state = this._baseState; const args = Array.prototype.slice.call(arguments); state.obj = true; if (args.length !== 0) this._useArgs(args); return this; }; Node.prototype.key = function key(newKey) { const state = this._baseState; assert(state.key === null); state.key = newKey; return this; }; Node.prototype.any = function any() { const state = this._baseState; state.any = true; return this; }; Node.prototype.choice = function choice(obj) { const state = this._baseState; assert(state.choice === null); state.choice = obj; this._useArgs(Object.keys(obj).map(function(key) { return obj[key]; })); return this; }; Node.prototype.contains = function contains(item) { const state = this._baseState; assert(state.use === null); state.contains = item; return this; }; // // Decoding // Node.prototype._decode = function decode(input, options) { const state = this._baseState; // Decode root node if (state.parent === null) return input.wrapResult(state.children[0]._decode(input, options)); let result = state['default']; let present = true; let prevKey = null; if (state.key !== null) prevKey = input.enterKey(state.key); // Check if tag is there if (state.optional) { let tag = null; if (state.explicit !== null) tag = state.explicit; else if (state.implicit !== null) tag = state.implicit; else if (state.tag !== null) tag = state.tag; if (tag === null && !state.any) { // Trial and Error const save = input.save(); try { if (state.choice === null) this._decodeGeneric(state.tag, input, options); else this._decodeChoice(input, options); present = true; } catch (e) { present = false; } input.restore(save); } else { present = this._peekTag(input, tag, state.any); if (input.isError(present)) return present; } } // Push object on stack let prevObj; if (state.obj && present) prevObj = input.enterObject(); if (present) { // Unwrap explicit values if (state.explicit !== null) { const explicit = this._decodeTag(input, state.explicit); if (input.isError(explicit)) return explicit; input = explicit; } const start = input.offset; // Unwrap implicit and normal values if (state.use === null && state.choice === null) { let save; if (state.any) save = input.save(); const body = this._decodeTag( input, state.implicit !== null ? state.implicit : state.tag, state.any ); if (input.isError(body)) return body; if (state.any) result = input.raw(save); else input = body; } if (options && options.track && state.tag !== null) options.track(input.path(), start, input.length, 'tagged'); if (options && options.track && state.tag !== null) options.track(input.path(), input.offset, input.length, 'content'); // Select proper method for tag if (state.any) { // no-op } else if (state.choice === null) { result = this._decodeGeneric(state.tag, input, options); } else { result = this._decodeChoice(input, options); } if (input.isError(result)) return result; // Decode children if (!state.any && state.choice === null && state.children !== null) { state.children.forEach(function decodeChildren(child) { // NOTE: We are ignoring errors here, to let parser continue with other // parts of encoded data child._decode(input, options); }); } // Decode contained/encoded by schema, only in bit or octet strings if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { const data = new DecoderBuffer(result); result = this._getUse(state.contains, input._reporterState.obj) ._decode(data, options); } } // Pop object if (state.obj && present) result = input.leaveObject(prevObj); // Set key if (state.key !== null && (result !== null || present === true)) input.leaveKey(prevKey, state.key, result); else if (prevKey !== null) input.exitKey(prevKey); return result; }; Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { const state = this._baseState; if (tag === 'seq' || tag === 'set') return null; if (tag === 'seqof' || tag === 'setof') return this._decodeList(input, tag, state.args[0], options); else if (/str$/.test(tag)) return this._decodeStr(input, tag, options); else if (tag === 'objid' && state.args) return this._decodeObjid(input, state.args[0], state.args[1], options); else if (tag === 'objid') return this._decodeObjid(input, null, null, options); else if (tag === 'gentime' || tag === 'utctime') return this._decodeTime(input, tag, options); else if (tag === 'null_') return this._decodeNull(input, options); else if (tag === 'bool') return this._decodeBool(input, options); else if (tag === 'objDesc') return this._decodeStr(input, tag, options); else if (tag === 'int' || tag === 'enum') return this._decodeInt(input, state.args && state.args[0], options); if (state.use !== null) { return this._getUse(state.use, input._reporterState.obj) ._decode(input, options); } else { return input.error('unknown tag: ' + tag); } }; Node.prototype._getUse = function _getUse(entity, obj) { const state = this._baseState; // Create altered use decoder if implicit is set state.useDecoder = this._use(entity, obj); assert(state.useDecoder._baseState.parent === null); state.useDecoder = state.useDecoder._baseState.children[0]; if (state.implicit !== state.useDecoder._baseState.implicit) { state.useDecoder = state.useDecoder.clone(); state.useDecoder._baseState.implicit = state.implicit; } return state.useDecoder; }; Node.prototype._decodeChoice = function decodeChoice(input, options) { const state = this._baseState; let result = null; let match = false; Object.keys(state.choice).some(function(key) { const save = input.save(); const node = state.choice[key]; try { const value = node._decode(input, options); if (input.isError(value)) return false; result = { type: key, value: value }; match = true; } catch (e) { input.restore(save); return false; } return true; }, this); if (!match) return input.error('Choice not matched'); return result; }; // // Encoding // Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { return new EncoderBuffer(data, this.reporter); }; Node.prototype._encode = function encode(data, reporter, parent) { const state = this._baseState; if (state['default'] !== null && state['default'] === data) return; const result = this._encodeValue(data, reporter, parent); if (result === undefined) return; if (this._skipDefault(result, reporter, parent)) return; return result; }; Node.prototype._encodeValue = function encode(data, reporter, parent) { const state = this._baseState; // Decode root node if (state.parent === null) return state.children[0]._encode(data, reporter || new Reporter()); let result = null; // Set reporter to share it with a child class this.reporter = reporter; // Check if data is there if (state.optional && data === undefined) { if (state['default'] !== null) data = state['default']; else return; } // Encode children first let content = null; let primitive = false; if (state.any) { // Anything that was given is translated to buffer result = this._createEncoderBuffer(data); } else if (state.choice) { result = this._encodeChoice(data, reporter); } else if (state.contains) { content = this._getUse(state.contains, parent)._encode(data, reporter); primitive = true; } else if (state.children) { content = state.children.map(function(child) { if (child._baseState.tag === 'null_') return child._encode(null, reporter, data); if (child._baseState.key === null) return reporter.error('Child should have a key'); const prevKey = reporter.enterKey(child._baseState.key); if (typeof data !== 'object') return reporter.error('Child expected, but input is not object'); const res = child._encode(data[child._baseState.key], reporter, data); reporter.leaveKey(prevKey); return res; }, this).filter(function(child) { return child; }); content = this._createEncoderBuffer(content); } else { if (state.tag === 'seqof' || state.tag === 'setof') { // TODO(indutny): this should be thrown on DSL level if (!(state.args && state.args.length === 1)) return reporter.error('Too many args for : ' + state.tag); if (!Array.isArray(data)) return reporter.error('seqof/setof, but data is not Array'); const child = this.clone(); child._baseState.implicit = null; content = this._createEncoderBuffer(data.map(function(item) { const state = this._baseState; return this._getUse(state.args[0], data)._encode(item, reporter); }, child)); } else if (state.use !== null) { result = this._getUse(state.use, parent)._encode(data, reporter); } else { content = this._encodePrimitive(state.tag, data); primitive = true; } } // Encode data itself if (!state.any && state.choice === null) { const tag = state.implicit !== null ? state.implicit : state.tag; const cls = state.implicit === null ? 'universal' : 'context'; if (tag === null) { if (state.use === null) reporter.error('Tag could be omitted only for .use()'); } else { if (state.use === null) result = this._encodeComposite(tag, primitive, cls, content); } } // Wrap in explicit if (state.explicit !== null) result = this._encodeComposite(state.explicit, false, 'context', result); return result; }; Node.prototype._encodeChoice = function encodeChoice(data, reporter) { const state = this._baseState; const node = state.choice[data.type]; if (!node) { assert( false, data.type + ' not found in ' + JSON.stringify(Object.keys(state.choice))); } return node._encode(data.value, reporter); }; Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { const state = this._baseState; if (/str$/.test(tag)) return this._encodeStr(data, tag); else if (tag === 'objid' && state.args) return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); else if (tag === 'objid') return this._encodeObjid(data, null, null); else if (tag === 'gentime' || tag === 'utctime') return this._encodeTime(data, tag); else if (tag === 'null_') return this._encodeNull(); else if (tag === 'int' || tag === 'enum') return this._encodeInt(data, state.args && state.reverseArgs[0]); else if (tag === 'bool') return this._encodeBool(data); else if (tag === 'objDesc') return this._encodeStr(data, tag); else throw new Error('Unsupported tag: ' + tag); }; Node.prototype._isNumstr = function isNumstr(str) { return /^[0-9 ]*$/.test(str); }; Node.prototype._isPrintstr = function isPrintstr(str) { return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str); }; /***/ }), /***/ 8465: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const inherits = __webpack_require__(5717); function Reporter(options) { this._reporterState = { obj: null, path: [], options: options || {}, errors: [] }; } exports.b = Reporter; Reporter.prototype.isError = function isError(obj) { return obj instanceof ReporterError; }; Reporter.prototype.save = function save() { const state = this._reporterState; return { obj: state.obj, pathLen: state.path.length }; }; Reporter.prototype.restore = function restore(data) { const state = this._reporterState; state.obj = data.obj; state.path = state.path.slice(0, data.pathLen); }; Reporter.prototype.enterKey = function enterKey(key) { return this._reporterState.path.push(key); }; Reporter.prototype.exitKey = function exitKey(index) { const state = this._reporterState; state.path = state.path.slice(0, index - 1); }; Reporter.prototype.leaveKey = function leaveKey(index, key, value) { const state = this._reporterState; this.exitKey(index); if (state.obj !== null) state.obj[key] = value; }; Reporter.prototype.path = function path() { return this._reporterState.path.join('/'); }; Reporter.prototype.enterObject = function enterObject() { const state = this._reporterState; const prev = state.obj; state.obj = {}; return prev; }; Reporter.prototype.leaveObject = function leaveObject(prev) { const state = this._reporterState; const now = state.obj; state.obj = prev; return now; }; Reporter.prototype.error = function error(msg) { let err; const state = this._reporterState; const inherited = msg instanceof ReporterError; if (inherited) { err = msg; } else { err = new ReporterError(state.path.map(function(elem) { return '[' + JSON.stringify(elem) + ']'; }).join(''), msg.message || msg, msg.stack); } if (!state.options.partial) throw err; if (!inherited) state.errors.push(err); return err; }; Reporter.prototype.wrapResult = function wrapResult(result) { const state = this._reporterState; if (!state.options.partial) return result; return { result: this.isError(result) ? null : result, errors: state.errors }; }; function ReporterError(path, msg) { this.path = path; this.rethrow(msg); } inherits(ReporterError, Error); ReporterError.prototype.rethrow = function rethrow(msg) { this.message = msg + ' at: ' + (this.path || '(shallow)'); if (Error.captureStackTrace) Error.captureStackTrace(this, ReporterError); if (!this.stack) { try { // IE only adds stack when thrown throw new Error(this.message); } catch (e) { this.stack = e.stack; } } return this; }; /***/ }), /***/ 160: /***/ (function(__unused_webpack_module, exports) { "use strict"; // Helper function reverse(map) { const res = {}; Object.keys(map).forEach(function(key) { // Convert key to integer if it is stringified if ((key | 0) == key) key = key | 0; const value = map[key]; res[value] = key; }); return res; } exports.tagClass = { 0: 'universal', 1: 'application', 2: 'context', 3: 'private' }; exports.tagClassByName = reverse(exports.tagClass); exports.tag = { 0x00: 'end', 0x01: 'bool', 0x02: 'int', 0x03: 'bitstr', 0x04: 'octstr', 0x05: 'null_', 0x06: 'objid', 0x07: 'objDesc', 0x08: 'external', 0x09: 'real', 0x0a: 'enum', 0x0b: 'embed', 0x0c: 'utf8str', 0x0d: 'relativeOid', 0x10: 'seq', 0x11: 'set', 0x12: 'numstr', 0x13: 'printstr', 0x14: 't61str', 0x15: 'videostr', 0x16: 'ia5str', 0x17: 'utctime', 0x18: 'gentime', 0x19: 'graphstr', 0x1a: 'iso646str', 0x1b: 'genstr', 0x1c: 'unistr', 0x1d: 'charstr', 0x1e: 'bmpstr' }; exports.tagByName = reverse(exports.tag); /***/ }), /***/ 6826: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const constants = exports; // Helper constants._reverse = function reverse(map) { const res = {}; Object.keys(map).forEach(function(key) { // Convert key to integer if it is stringified if ((key | 0) == key) key = key | 0; const value = map[key]; res[value] = key; }); return res; }; constants.der = __webpack_require__(160); /***/ }), /***/ 1671: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; const inherits = __webpack_require__(5717); const bignum = __webpack_require__(3550); const DecoderBuffer = (__webpack_require__(6625)/* .DecoderBuffer */ .C); const Node = __webpack_require__(1949); // Import DER constants const der = __webpack_require__(160); function DERDecoder(entity) { this.enc = 'der'; this.name = entity.name; this.entity = entity; // Construct base tree this.tree = new DERNode(); this.tree._init(entity.body); } module.exports = DERDecoder; DERDecoder.prototype.decode = function decode(data, options) { if (!DecoderBuffer.isDecoderBuffer(data)) { data = new DecoderBuffer(data, options); } return this.tree._decode(data, options); }; // Tree methods function DERNode(parent) { Node.call(this, 'der', parent); } inherits(DERNode, Node); DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { if (buffer.isEmpty()) return false; const state = buffer.save(); const decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); if (buffer.isError(decodedTag)) return decodedTag; buffer.restore(state); return decodedTag.tag === tag || decodedTag.tagStr === tag || (decodedTag.tagStr + 'of') === tag || any; }; DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { const decodedTag = derDecodeTag(buffer, 'Failed to decode tag of "' + tag + '"'); if (buffer.isError(decodedTag)) return decodedTag; let len = derDecodeLen(buffer, decodedTag.primitive, 'Failed to get length of "' + tag + '"'); // Failure if (buffer.isError(len)) return len; if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + 'of' !== tag) { return buffer.error('Failed to match tag: "' + tag + '"'); } if (decodedTag.primitive || len !== null) return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); // Indefinite length... find END tag const state = buffer.save(); const res = this._skipUntilEnd( buffer, 'Failed to skip indefinite length body: "' + this.tag + '"'); if (buffer.isError(res)) return res; len = buffer.offset - state.offset; buffer.restore(state); return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); }; DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { for (;;) { const tag = derDecodeTag(buffer, fail); if (buffer.isError(tag)) return tag; const len = derDecodeLen(buffer, tag.primitive, fail); if (buffer.isError(len)) return len; let res; if (tag.primitive || len !== null) res = buffer.skip(len); else res = this._skipUntilEnd(buffer, fail); // Failure if (buffer.isError(res)) return res; if (tag.tagStr === 'end') break; } }; DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, options) { const result = []; while (!buffer.isEmpty()) { const possibleEnd = this._peekTag(buffer, 'end'); if (buffer.isError(possibleEnd)) return possibleEnd; const res = decoder.decode(buffer, 'der', options); if (buffer.isError(res) && possibleEnd) break; result.push(res); } return result; }; DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { if (tag === 'bitstr') { const unused = buffer.readUInt8(); if (buffer.isError(unused)) return unused; return { unused: unused, data: buffer.raw() }; } else if (tag === 'bmpstr') { const raw = buffer.raw(); if (raw.length % 2 === 1) return buffer.error('Decoding of string type: bmpstr length mismatch'); let str = ''; for (let i = 0; i < raw.length / 2; i++) { str += String.fromCharCode(raw.readUInt16BE(i * 2)); } return str; } else if (tag === 'numstr') { const numstr = buffer.raw().toString('ascii'); if (!this._isNumstr(numstr)) { return buffer.error('Decoding of string type: ' + 'numstr unsupported characters'); } return numstr; } else if (tag === 'octstr') { return buffer.raw(); } else if (tag === 'objDesc') { return buffer.raw(); } else if (tag === 'printstr') { const printstr = buffer.raw().toString('ascii'); if (!this._isPrintstr(printstr)) { return buffer.error('Decoding of string type: ' + 'printstr unsupported characters'); } return printstr; } else if (/str$/.test(tag)) { return buffer.raw().toString(); } else { return buffer.error('Decoding of string type: ' + tag + ' unsupported'); } }; DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { let result; const identifiers = []; let ident = 0; let subident = 0; while (!buffer.isEmpty()) { subident = buffer.readUInt8(); ident <<= 7; ident |= subident & 0x7f; if ((subident & 0x80) === 0) { identifiers.push(ident); ident = 0; } } if (subident & 0x80) identifiers.push(ident); const first = (identifiers[0] / 40) | 0; const second = identifiers[0] % 40; if (relative) result = identifiers; else result = [first, second].concat(identifiers.slice(1)); if (values) { let tmp = values[result.join(' ')]; if (tmp === undefined) tmp = values[result.join('.')]; if (tmp !== undefined) result = tmp; } return result; }; DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { const str = buffer.raw().toString(); let year; let mon; let day; let hour; let min; let sec; if (tag === 'gentime') { year = str.slice(0, 4) | 0; mon = str.slice(4, 6) | 0; day = str.slice(6, 8) | 0; hour = str.slice(8, 10) | 0; min = str.slice(10, 12) | 0; sec = str.slice(12, 14) | 0; } else if (tag === 'utctime') { year = str.slice(0, 2) | 0; mon = str.slice(2, 4) | 0; day = str.slice(4, 6) | 0; hour = str.slice(6, 8) | 0; min = str.slice(8, 10) | 0; sec = str.slice(10, 12) | 0; if (year < 70) year = 2000 + year; else year = 1900 + year; } else { return buffer.error('Decoding ' + tag + ' time is not supported yet'); } return Date.UTC(year, mon - 1, day, hour, min, sec, 0); }; DERNode.prototype._decodeNull = function decodeNull() { return null; }; DERNode.prototype._decodeBool = function decodeBool(buffer) { const res = buffer.readUInt8(); if (buffer.isError(res)) return res; else return res !== 0; }; DERNode.prototype._decodeInt = function decodeInt(buffer, values) { // Bigint, return as it is (assume big endian) const raw = buffer.raw(); let res = new bignum(raw); if (values) res = values[res.toString(10)] || res; return res; }; DERNode.prototype._use = function use(entity, obj) { if (typeof entity === 'function') entity = entity(obj); return entity._getDecoder('der').tree; }; // Utility methods function derDecodeTag(buf, fail) { let tag = buf.readUInt8(fail); if (buf.isError(tag)) return tag; const cls = der.tagClass[tag >> 6]; const primitive = (tag & 0x20) === 0; // Multi-octet tag - load if ((tag & 0x1f) === 0x1f) { let oct = tag; tag = 0; while ((oct & 0x80) === 0x80) { oct = buf.readUInt8(fail); if (buf.isError(oct)) return oct; tag <<= 7; tag |= oct & 0x7f; } } else { tag &= 0x1f; } const tagStr = der.tag[tag]; return { cls: cls, primitive: primitive, tag: tag, tagStr: tagStr }; } function derDecodeLen(buf, primitive, fail) { let len = buf.readUInt8(fail); if (buf.isError(len)) return len; // Indefinite form if (!primitive && len === 0x80) return null; // Definite form if ((len & 0x80) === 0) { // Short form return len; } // Long form const num = len & 0x7f; if (num > 4) return buf.error('length octect is too long'); len = 0; for (let i = 0; i < num; i++) { len <<= 8; const j = buf.readUInt8(fail); if (buf.isError(j)) return j; len |= j; } return len; } /***/ }), /***/ 8307: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const decoders = exports; decoders.der = __webpack_require__(1671); decoders.pem = __webpack_require__(9631); /***/ }), /***/ 9631: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; const inherits = __webpack_require__(5717); const Buffer = (__webpack_require__(2399).Buffer); const DERDecoder = __webpack_require__(1671); function PEMDecoder(entity) { DERDecoder.call(this, entity); this.enc = 'pem'; } inherits(PEMDecoder, DERDecoder); module.exports = PEMDecoder; PEMDecoder.prototype.decode = function decode(data, options) { const lines = data.toString().split(/[\r\n]+/g); const label = options.label.toUpperCase(); const re = /^-----(BEGIN|END) ([^-]+)-----$/; let start = -1; let end = -1; for (let i = 0; i < lines.length; i++) { const match = lines[i].match(re); if (match === null) continue; if (match[2] !== label) continue; if (start === -1) { if (match[1] !== 'BEGIN') break; start = i; } else { if (match[1] !== 'END') break; end = i; break; } } if (start === -1 || end === -1) throw new Error('PEM section not found for: ' + label); const base64 = lines.slice(start + 1, end).join(''); // Remove excessive symbols base64.replace(/[^a-z0-9+/=]+/gi, ''); const input = Buffer.from(base64, 'base64'); return DERDecoder.prototype.decode.call(this, input, options); }; /***/ }), /***/ 6984: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; const inherits = __webpack_require__(5717); const Buffer = (__webpack_require__(2399).Buffer); const Node = __webpack_require__(1949); // Import DER constants const der = __webpack_require__(160); function DEREncoder(entity) { this.enc = 'der'; this.name = entity.name; this.entity = entity; // Construct base tree this.tree = new DERNode(); this.tree._init(entity.body); } module.exports = DEREncoder; DEREncoder.prototype.encode = function encode(data, reporter) { return this.tree._encode(data, reporter).join(); }; // Tree methods function DERNode(parent) { Node.call(this, 'der', parent); } inherits(DERNode, Node); DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls, content) { const encodedTag = encodeTag(tag, primitive, cls, this.reporter); // Short form if (content.length < 0x80) { const header = Buffer.alloc(2); header[0] = encodedTag; header[1] = content.length; return this._createEncoderBuffer([ header, content ]); } // Long form // Count octets required to store length let lenOctets = 1; for (let i = content.length; i >= 0x100; i >>= 8) lenOctets++; const header = Buffer.alloc(1 + 1 + lenOctets); header[0] = encodedTag; header[1] = 0x80 | lenOctets; for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) header[i] = j & 0xff; return this._createEncoderBuffer([ header, content ]); }; DERNode.prototype._encodeStr = function encodeStr(str, tag) { if (tag === 'bitstr') { return this._createEncoderBuffer([ str.unused | 0, str.data ]); } else if (tag === 'bmpstr') { const buf = Buffer.alloc(str.length * 2); for (let i = 0; i < str.length; i++) { buf.writeUInt16BE(str.charCodeAt(i), i * 2); } return this._createEncoderBuffer(buf); } else if (tag === 'numstr') { if (!this._isNumstr(str)) { return this.reporter.error('Encoding of string type: numstr supports ' + 'only digits and space'); } return this._createEncoderBuffer(str); } else if (tag === 'printstr') { if (!this._isPrintstr(str)) { return this.reporter.error('Encoding of string type: printstr supports ' + 'only latin upper and lower case letters, ' + 'digits, space, apostrophe, left and rigth ' + 'parenthesis, plus sign, comma, hyphen, ' + 'dot, slash, colon, equal sign, ' + 'question mark'); } return this._createEncoderBuffer(str); } else if (/str$/.test(tag)) { return this._createEncoderBuffer(str); } else if (tag === 'objDesc') { return this._createEncoderBuffer(str); } else { return this.reporter.error('Encoding of string type: ' + tag + ' unsupported'); } }; DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { if (typeof id === 'string') { if (!values) return this.reporter.error('string objid given, but no values map found'); if (!values.hasOwnProperty(id)) return this.reporter.error('objid not found in values map'); id = values[id].split(/[\s.]+/g); for (let i = 0; i < id.length; i++) id[i] |= 0; } else if (Array.isArray(id)) { id = id.slice(); for (let i = 0; i < id.length; i++) id[i] |= 0; } if (!Array.isArray(id)) { return this.reporter.error('objid() should be either array or string, ' + 'got: ' + JSON.stringify(id)); } if (!relative) { if (id[1] >= 40) return this.reporter.error('Second objid identifier OOB'); id.splice(0, 2, id[0] * 40 + id[1]); } // Count number of octets let size = 0; for (let i = 0; i < id.length; i++) { let ident = id[i]; for (size++; ident >= 0x80; ident >>= 7) size++; } const objid = Buffer.alloc(size); let offset = objid.length - 1; for (let i = id.length - 1; i >= 0; i--) { let ident = id[i]; objid[offset--] = ident & 0x7f; while ((ident >>= 7) > 0) objid[offset--] = 0x80 | (ident & 0x7f); } return this._createEncoderBuffer(objid); }; function two(num) { if (num < 10) return '0' + num; else return num; } DERNode.prototype._encodeTime = function encodeTime(time, tag) { let str; const date = new Date(time); if (tag === 'gentime') { str = [ two(date.getUTCFullYear()), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z' ].join(''); } else if (tag === 'utctime') { str = [ two(date.getUTCFullYear() % 100), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z' ].join(''); } else { this.reporter.error('Encoding ' + tag + ' time is not supported yet'); } return this._encodeStr(str, 'octstr'); }; DERNode.prototype._encodeNull = function encodeNull() { return this._createEncoderBuffer(''); }; DERNode.prototype._encodeInt = function encodeInt(num, values) { if (typeof num === 'string') { if (!values) return this.reporter.error('String int or enum given, but no values map'); if (!values.hasOwnProperty(num)) { return this.reporter.error('Values map doesn\'t contain: ' + JSON.stringify(num)); } num = values[num]; } // Bignum, assume big endian if (typeof num !== 'number' && !Buffer.isBuffer(num)) { const numArray = num.toArray(); if (!num.sign && numArray[0] & 0x80) { numArray.unshift(0); } num = Buffer.from(numArray); } if (Buffer.isBuffer(num)) { let size = num.length; if (num.length === 0) size++; const out = Buffer.alloc(size); num.copy(out); if (num.length === 0) out[0] = 0; return this._createEncoderBuffer(out); } if (num < 0x80) return this._createEncoderBuffer(num); if (num < 0x100) return this._createEncoderBuffer([0, num]); let size = 1; for (let i = num; i >= 0x100; i >>= 8) size++; const out = new Array(size); for (let i = out.length - 1; i >= 0; i--) { out[i] = num & 0xff; num >>= 8; } if(out[0] & 0x80) { out.unshift(0); } return this._createEncoderBuffer(Buffer.from(out)); }; DERNode.prototype._encodeBool = function encodeBool(value) { return this._createEncoderBuffer(value ? 0xff : 0); }; DERNode.prototype._use = function use(entity, obj) { if (typeof entity === 'function') entity = entity(obj); return entity._getEncoder('der').tree; }; DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { const state = this._baseState; let i; if (state['default'] === null) return false; const data = dataBuffer.join(); if (state.defaultBuffer === undefined) state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); if (data.length !== state.defaultBuffer.length) return false; for (i=0; i < data.length; i++) if (data[i] !== state.defaultBuffer[i]) return false; return true; }; // Utility methods function encodeTag(tag, primitive, cls, reporter) { let res; if (tag === 'seqof') tag = 'seq'; else if (tag === 'setof') tag = 'set'; if (der.tagByName.hasOwnProperty(tag)) res = der.tagByName[tag]; else if (typeof tag === 'number' && (tag | 0) === tag) res = tag; else return reporter.error('Unknown tag: ' + tag); if (res >= 0x1f) return reporter.error('Multi-octet tag encoding unsupported'); if (!primitive) res |= 0x20; res |= (der.tagClassByName[cls || 'universal'] << 6); return res; } /***/ }), /***/ 6579: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const encoders = exports; encoders.der = __webpack_require__(6984); encoders.pem = __webpack_require__(2883); /***/ }), /***/ 2883: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; const inherits = __webpack_require__(5717); const DEREncoder = __webpack_require__(6984); function PEMEncoder(entity) { DEREncoder.call(this, entity); this.enc = 'pem'; } inherits(PEMEncoder, DEREncoder); module.exports = PEMEncoder; PEMEncoder.prototype.encode = function encode(data, options) { const buf = DEREncoder.prototype.encode.call(this, data); const p = buf.toString('base64'); const out = [ '-----BEGIN ' + options.label + '-----' ]; for (let i = 0; i < p.length; i += 64) out.push(p.slice(i, i + 64)); out.push('-----END ' + options.label + '-----'); return out.join('\n'); }; /***/ }), /***/ 9669: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { module.exports = __webpack_require__(1609); /***/ }), /***/ 5448: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); var settle = __webpack_require__(6026); var cookies = __webpack_require__(4372); var buildURL = __webpack_require__(5327); var buildFullPath = __webpack_require__(4097); var parseHeaders = __webpack_require__(4109); var isURLSameOrigin = __webpack_require__(7985); var transitionalDefaults = __webpack_require__(7874); var AxiosError = __webpack_require__(723); var CanceledError = __webpack_require__(644); var parseProtocol = __webpack_require__(205); module.exports = function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { var requestData = config.data; var requestHeaders = config.headers; var responseType = config.responseType; var onCanceled; function done() { if (config.cancelToken) { config.cancelToken.unsubscribe(onCanceled); } if (config.signal) { config.signal.removeEventListener('abort', onCanceled); } } if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) { delete requestHeaders['Content-Type']; // Let the browser set it } var request = new XMLHttpRequest(); // HTTP basic authentication if (config.auth) { var username = config.auth.username || ''; var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); } var fullPath = buildFullPath(config.baseURL, config.url); request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); // Set the request timeout in MS request.timeout = config.timeout; function onloadend() { if (!request) { return; } // Prepare the response var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; var responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response; var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(function _resolve(value) { resolve(value); done(); }, function _reject(err) { reject(err); done(); }, response); // Clean up request request = null; } if ('onloadend' in request) { // Use onloadend if available request.onloadend = onloadend; } else { // Listen for ready state to emulate onloadend request.onreadystatechange = function handleLoad() { if (!request || request.readyState !== 4) { return; } // The request errored out and we didn't get a response, this will be // handled by onerror instead // With one exception: request that using file: protocol, most browsers // will return status as 0 even though it's a successful request if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { return; } // readystate handler is calling before onerror or ontimeout handlers, // so we should call onloadend on the next 'tick' setTimeout(onloadend); }; } // Handle browser request cancellation (as opposed to a manual cancellation) request.onabort = function handleAbort() { if (!request) { return; } reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); // Clean up request request = null; }; // Handle low level network errors request.onerror = function handleError() { // Real errors are hidden from us by the browser // onerror should only fire if it's a network error reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request)); // Clean up request request = null; }; // Handle timeout request.ontimeout = function handleTimeout() { var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; var transitional = config.transitional || transitionalDefaults; if (config.timeoutErrorMessage) { timeoutErrorMessage = config.timeoutErrorMessage; } reject(new AxiosError( timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, request)); // Clean up request request = null; }; // Add xsrf header // This is only done if running in a standard browser environment. // Specifically not if we're in a web worker, or react-native. if (utils.isStandardBrowserEnv()) { // Add xsrf header var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName] = xsrfValue; } } // Add headers to the request if ('setRequestHeader' in request) { utils.forEach(requestHeaders, function setRequestHeader(val, key) { if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { // Remove Content-Type if data is undefined delete requestHeaders[key]; } else { // Otherwise add header to the request request.setRequestHeader(key, val); } }); } // Add withCredentials to request if needed if (!utils.isUndefined(config.withCredentials)) { request.withCredentials = !!config.withCredentials; } // Add responseType to request if needed if (responseType && responseType !== 'json') { request.responseType = config.responseType; } // Handle progress if needed if (typeof config.onDownloadProgress === 'function') { request.addEventListener('progress', config.onDownloadProgress); } // Not all browsers support upload events if (typeof config.onUploadProgress === 'function' && request.upload) { request.upload.addEventListener('progress', config.onUploadProgress); } if (config.cancelToken || config.signal) { // Handle cancellation // eslint-disable-next-line func-names onCanceled = function(cancel) { if (!request) { return; } reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel); request.abort(); request = null; }; config.cancelToken && config.cancelToken.subscribe(onCanceled); if (config.signal) { config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); } } if (!requestData) { requestData = null; } var protocol = parseProtocol(fullPath); if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) { reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); return; } // Send the request request.send(requestData); }); }; /***/ }), /***/ 1609: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); var bind = __webpack_require__(1849); var Axios = __webpack_require__(321); var mergeConfig = __webpack_require__(7185); var defaults = __webpack_require__(5546); /** * Create an instance of Axios * * @param {Object} defaultConfig The default config for the instance * @return {Axios} A new instance of Axios */ function createInstance(defaultConfig) { var context = new Axios(defaultConfig); var instance = bind(Axios.prototype.request, context); // Copy axios.prototype to instance utils.extend(instance, Axios.prototype, context); // Copy context to instance utils.extend(instance, context); // Factory for creating new instances instance.create = function create(instanceConfig) { return createInstance(mergeConfig(defaultConfig, instanceConfig)); }; return instance; } // Create the default instance to be exported var axios = createInstance(defaults); // Expose Axios class to allow class inheritance axios.Axios = Axios; // Expose Cancel & CancelToken axios.CanceledError = __webpack_require__(644); axios.CancelToken = __webpack_require__(4972); axios.isCancel = __webpack_require__(6502); axios.VERSION = (__webpack_require__(7288).version); axios.toFormData = __webpack_require__(7675); // Expose AxiosError class axios.AxiosError = __webpack_require__(723); // alias for CanceledError for backward compatibility axios.Cancel = axios.CanceledError; // Expose all/spread axios.all = function all(promises) { return Promise.all(promises); }; axios.spread = __webpack_require__(8713); // Expose isAxiosError axios.isAxiosError = __webpack_require__(6268); module.exports = axios; // Allow use of default import syntax in TypeScript module.exports["default"] = axios; /***/ }), /***/ 4972: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var CanceledError = __webpack_require__(644); /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * * @class * @param {Function} executor The executor function. */ function CancelToken(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); } var resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); var token = this; // eslint-disable-next-line func-names this.promise.then(function(cancel) { if (!token._listeners) return; var i; var l = token._listeners.length; for (i = 0; i < l; i++) { token._listeners[i](cancel); } token._listeners = null; }); // eslint-disable-next-line func-names this.promise.then = function(onfulfilled) { var _resolve; // eslint-disable-next-line func-names var promise = new Promise(function(resolve) { token.subscribe(resolve); _resolve = resolve; }).then(onfulfilled); promise.cancel = function reject() { token.unsubscribe(_resolve); }; return promise; }; executor(function cancel(message) { if (token.reason) { // Cancellation has already been requested return; } token.reason = new CanceledError(message); resolvePromise(token.reason); }); } /** * Throws a `CanceledError` if cancellation has been requested. */ CancelToken.prototype.throwIfRequested = function throwIfRequested() { if (this.reason) { throw this.reason; } }; /** * Subscribe to the cancel signal */ CancelToken.prototype.subscribe = function subscribe(listener) { if (this.reason) { listener(this.reason); return; } if (this._listeners) { this._listeners.push(listener); } else { this._listeners = [listener]; } }; /** * Unsubscribe from the cancel signal */ CancelToken.prototype.unsubscribe = function unsubscribe(listener) { if (!this._listeners) { return; } var index = this._listeners.indexOf(listener); if (index !== -1) { this._listeners.splice(index, 1); } }; /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. */ CancelToken.source = function source() { var cancel; var token = new CancelToken(function executor(c) { cancel = c; }); return { token: token, cancel: cancel }; }; module.exports = CancelToken; /***/ }), /***/ 644: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var AxiosError = __webpack_require__(723); var utils = __webpack_require__(4867); /** * A `CanceledError` is an object that is thrown when an operation is canceled. * * @class * @param {string=} message The message. */ function CanceledError(message) { // eslint-disable-next-line no-eq-null,eqeqeq AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED); this.name = 'CanceledError'; } utils.inherits(CanceledError, AxiosError, { __CANCEL__: true }); module.exports = CanceledError; /***/ }), /***/ 6502: /***/ (function(module) { "use strict"; module.exports = function isCancel(value) { return !!(value && value.__CANCEL__); }; /***/ }), /***/ 321: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); var buildURL = __webpack_require__(5327); var InterceptorManager = __webpack_require__(782); var dispatchRequest = __webpack_require__(3572); var mergeConfig = __webpack_require__(7185); var buildFullPath = __webpack_require__(4097); var validator = __webpack_require__(4875); var validators = validator.validators; /** * Create a new instance of Axios * * @param {Object} instanceConfig The default config for the instance */ function Axios(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; } /** * Dispatch a request * * @param {Object} config The config specific for this request (merged with this.defaults) */ Axios.prototype.request = function request(configOrUrl, config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof configOrUrl === 'string') { config = config || {}; config.url = configOrUrl; } else { config = configOrUrl || {}; } config = mergeConfig(this.defaults, config); // Set config.method if (config.method) { config.method = config.method.toLowerCase(); } else if (this.defaults.method) { config.method = this.defaults.method.toLowerCase(); } else { config.method = 'get'; } var transitional = config.transitional; if (transitional !== undefined) { validator.assertOptions(transitional, { silentJSONParsing: validators.transitional(validators.boolean), forcedJSONParsing: validators.transitional(validators.boolean), clarifyTimeoutError: validators.transitional(validators.boolean) }, false); } // filter out skipped interceptors var requestInterceptorChain = []; var synchronousRequestInterceptors = true; this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { return; } synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); }); var responseInterceptorChain = []; this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); }); var promise; if (!synchronousRequestInterceptors) { var chain = [dispatchRequest, undefined]; Array.prototype.unshift.apply(chain, requestInterceptorChain); chain = chain.concat(responseInterceptorChain); promise = Promise.resolve(config); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; } var newConfig = config; while (requestInterceptorChain.length) { var onFulfilled = requestInterceptorChain.shift(); var onRejected = requestInterceptorChain.shift(); try { newConfig = onFulfilled(newConfig); } catch (error) { onRejected(error); break; } } try { promise = dispatchRequest(newConfig); } catch (error) { return Promise.reject(error); } while (responseInterceptorChain.length) { promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); } return promise; }; Axios.prototype.getUri = function getUri(config) { config = mergeConfig(this.defaults, config); var fullPath = buildFullPath(config.baseURL, config.url); return buildURL(fullPath, config.params, config.paramsSerializer); }; // Provide aliases for supported request methods utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { return this.request(mergeConfig(config || {}, { method: method, url: url, data: (config || {}).data })); }; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ function generateHTTPMethod(isForm) { return function httpMethod(url, data, config) { return this.request(mergeConfig(config || {}, { method: method, headers: isForm ? { 'Content-Type': 'multipart/form-data' } : {}, url: url, data: data })); }; } Axios.prototype[method] = generateHTTPMethod(); Axios.prototype[method + 'Form'] = generateHTTPMethod(true); }); module.exports = Axios; /***/ }), /***/ 723: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); /** * Create an Error with the specified message, config, error code, request and response. * * @param {string} message The error message. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [config] The config. * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The created error. */ function AxiosError(message, code, config, request, response) { Error.call(this); this.message = message; this.name = 'AxiosError'; code && (this.code = code); config && (this.config = config); request && (this.request = request); response && (this.response = response); } utils.inherits(AxiosError, Error, { toJSON: function toJSON() { return { // Standard message: this.message, name: this.name, // Microsoft description: this.description, number: this.number, // Mozilla fileName: this.fileName, lineNumber: this.lineNumber, columnNumber: this.columnNumber, stack: this.stack, // Axios config: this.config, code: this.code, status: this.response && this.response.status ? this.response.status : null }; } }); var prototype = AxiosError.prototype; var descriptors = {}; [ 'ERR_BAD_OPTION_VALUE', 'ERR_BAD_OPTION', 'ECONNABORTED', 'ETIMEDOUT', 'ERR_NETWORK', 'ERR_FR_TOO_MANY_REDIRECTS', 'ERR_DEPRECATED', 'ERR_BAD_RESPONSE', 'ERR_BAD_REQUEST', 'ERR_CANCELED' // eslint-disable-next-line func-names ].forEach(function(code) { descriptors[code] = {value: code}; }); Object.defineProperties(AxiosError, descriptors); Object.defineProperty(prototype, 'isAxiosError', {value: true}); // eslint-disable-next-line func-names AxiosError.from = function(error, code, config, request, response, customProps) { var axiosError = Object.create(prototype); utils.toFlatObject(error, axiosError, function filter(obj) { return obj !== Error.prototype; }); AxiosError.call(axiosError, error.message, code, config, request, response); axiosError.name = error.name; customProps && Object.assign(axiosError, customProps); return axiosError; }; module.exports = AxiosError; /***/ }), /***/ 782: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); function InterceptorManager() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ InterceptorManager.prototype.use = function use(fulfilled, rejected, options) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected, synchronous: options ? options.synchronous : false, runWhen: options ? options.runWhen : null }); return this.handlers.length - 1; }; /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` */ InterceptorManager.prototype.eject = function eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } }; /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `eject`. * * @param {Function} fn The function to call for each interceptor */ InterceptorManager.prototype.forEach = function forEach(fn) { utils.forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } }); }; module.exports = InterceptorManager; /***/ }), /***/ 4097: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var isAbsoluteURL = __webpack_require__(1793); var combineURLs = __webpack_require__(7303); /** * Creates a new URL by combining the baseURL with the requestedURL, * only when the requestedURL is not already an absolute URL. * If the requestURL is absolute, this function returns the requestedURL untouched. * * @param {string} baseURL The base URL * @param {string} requestedURL Absolute or relative URL to combine * @returns {string} The combined full path */ module.exports = function buildFullPath(baseURL, requestedURL) { if (baseURL && !isAbsoluteURL(requestedURL)) { return combineURLs(baseURL, requestedURL); } return requestedURL; }; /***/ }), /***/ 3572: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); var transformData = __webpack_require__(8527); var isCancel = __webpack_require__(6502); var defaults = __webpack_require__(5546); var CanceledError = __webpack_require__(644); /** * Throws a `CanceledError` if cancellation has been requested. */ function throwIfCancellationRequested(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } if (config.signal && config.signal.aborted) { throw new CanceledError(); } } /** * Dispatch a request to the server using the configured adapter. * * @param {object} config The config that is to be used for the request * @returns {Promise} The Promise to be fulfilled */ module.exports = function dispatchRequest(config) { throwIfCancellationRequested(config); // Ensure headers exist config.headers = config.headers || {}; // Transform request data config.data = transformData.call( config, config.data, config.headers, config.transformRequest ); // Flatten headers config.headers = utils.merge( config.headers.common || {}, config.headers[config.method] || {}, config.headers ); utils.forEach( ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { delete config.headers[method]; } ); var adapter = config.adapter || defaults.adapter; return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); // Transform response data response.data = transformData.call( config, response.data, response.headers, config.transformResponse ); return response; }, function onAdapterRejection(reason) { if (!isCancel(reason)) { throwIfCancellationRequested(config); // Transform response data if (reason && reason.response) { reason.response.data = transformData.call( config, reason.response.data, reason.response.headers, config.transformResponse ); } } return Promise.reject(reason); }); }; /***/ }), /***/ 7185: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); /** * Config-specific merge-function which creates a new config-object * by merging two configuration objects together. * * @param {Object} config1 * @param {Object} config2 * @returns {Object} New object resulting from merging config2 to config1 */ module.exports = function mergeConfig(config1, config2) { // eslint-disable-next-line no-param-reassign config2 = config2 || {}; var config = {}; function getMergedValue(target, source) { if (utils.isPlainObject(target) && utils.isPlainObject(source)) { return utils.merge(target, source); } else if (utils.isPlainObject(source)) { return utils.merge({}, source); } else if (utils.isArray(source)) { return source.slice(); } return source; } // eslint-disable-next-line consistent-return function mergeDeepProperties(prop) { if (!utils.isUndefined(config2[prop])) { return getMergedValue(config1[prop], config2[prop]); } else if (!utils.isUndefined(config1[prop])) { return getMergedValue(undefined, config1[prop]); } } // eslint-disable-next-line consistent-return function valueFromConfig2(prop) { if (!utils.isUndefined(config2[prop])) { return getMergedValue(undefined, config2[prop]); } } // eslint-disable-next-line consistent-return function defaultToConfig2(prop) { if (!utils.isUndefined(config2[prop])) { return getMergedValue(undefined, config2[prop]); } else if (!utils.isUndefined(config1[prop])) { return getMergedValue(undefined, config1[prop]); } } // eslint-disable-next-line consistent-return function mergeDirectKeys(prop) { if (prop in config2) { return getMergedValue(config1[prop], config2[prop]); } else if (prop in config1) { return getMergedValue(undefined, config1[prop]); } } var mergeMap = { 'url': valueFromConfig2, 'method': valueFromConfig2, 'data': valueFromConfig2, 'baseURL': defaultToConfig2, 'transformRequest': defaultToConfig2, 'transformResponse': defaultToConfig2, 'paramsSerializer': defaultToConfig2, 'timeout': defaultToConfig2, 'timeoutMessage': defaultToConfig2, 'withCredentials': defaultToConfig2, 'adapter': defaultToConfig2, 'responseType': defaultToConfig2, 'xsrfCookieName': defaultToConfig2, 'xsrfHeaderName': defaultToConfig2, 'onUploadProgress': defaultToConfig2, 'onDownloadProgress': defaultToConfig2, 'decompress': defaultToConfig2, 'maxContentLength': defaultToConfig2, 'maxBodyLength': defaultToConfig2, 'beforeRedirect': defaultToConfig2, 'transport': defaultToConfig2, 'httpAgent': defaultToConfig2, 'httpsAgent': defaultToConfig2, 'cancelToken': defaultToConfig2, 'socketPath': defaultToConfig2, 'responseEncoding': defaultToConfig2, 'validateStatus': mergeDirectKeys }; utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { var merge = mergeMap[prop] || mergeDeepProperties; var configValue = merge(prop); (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); }); return config; }; /***/ }), /***/ 6026: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var AxiosError = __webpack_require__(723); /** * Resolve or reject a Promise based on response status. * * @param {Function} resolve A function that resolves the promise. * @param {Function} reject A function that rejects the promise. * @param {object} response The response. */ module.exports = function settle(resolve, reject, response) { var validateStatus = response.config.validateStatus; if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { reject(new AxiosError( 'Request failed with status code ' + response.status, [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], response.config, response.request, response )); } }; /***/ }), /***/ 8527: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); var defaults = __webpack_require__(5546); /** * Transform the data for a request or a response * * @param {Object|String} data The data to be transformed * @param {Array} headers The headers for the request or response * @param {Array|Function} fns A single function or Array of functions * @returns {*} The resulting transformed data */ module.exports = function transformData(data, headers, fns) { var context = this || defaults; /*eslint no-param-reassign:0*/ utils.forEach(fns, function transform(fn) { data = fn.call(context, data, headers); }); return data; }; /***/ }), /***/ 5546: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* provided dependency */ var process = __webpack_require__(3454); var utils = __webpack_require__(4867); var normalizeHeaderName = __webpack_require__(6016); var AxiosError = __webpack_require__(723); var transitionalDefaults = __webpack_require__(7874); var toFormData = __webpack_require__(7675); var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } function getDefaultAdapter() { var adapter; if (typeof XMLHttpRequest !== 'undefined') { // For browsers use XHR adapter adapter = __webpack_require__(5448); } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { // For node use HTTP adapter adapter = __webpack_require__(5448); } return adapter; } function stringifySafely(rawValue, parser, encoder) { if (utils.isString(rawValue)) { try { (parser || JSON.parse)(rawValue); return utils.trim(rawValue); } catch (e) { if (e.name !== 'SyntaxError') { throw e; } } } return (encoder || JSON.stringify)(rawValue); } var defaults = { transitional: transitionalDefaults, adapter: getDefaultAdapter(), transformRequest: [function transformRequest(data, headers) { normalizeHeaderName(headers, 'Accept'); normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } var isObjectPayload = utils.isObject(data); var contentType = headers && headers['Content-Type']; var isFileList; if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) { var _FormData = this.env && this.env.FormData; return toFormData(isFileList ? {'files[]': data} : data, _FormData && new _FormData()); } else if (isObjectPayload || contentType === 'application/json') { setContentTypeIfUnset(headers, 'application/json'); return stringifySafely(data); } return data; }], transformResponse: [function transformResponse(data) { var transitional = this.transitional || defaults.transitional; var silentJSONParsing = transitional && transitional.silentJSONParsing; var forcedJSONParsing = transitional && transitional.forcedJSONParsing; var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { try { return JSON.parse(data); } catch (e) { if (strictJSONParsing) { if (e.name === 'SyntaxError') { throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); } throw e; } } } return data; }], /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, maxBodyLength: -1, env: { FormData: __webpack_require__(1623) }, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; }, headers: { common: { 'Accept': 'application/json, text/plain, */*' } } }; utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { defaults.headers[method] = {}; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); }); module.exports = defaults; /***/ }), /***/ 7874: /***/ (function(module) { "use strict"; module.exports = { silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false }; /***/ }), /***/ 7288: /***/ (function(module) { module.exports = { "version": "0.27.2" }; /***/ }), /***/ 1849: /***/ (function(module) { "use strict"; module.exports = function bind(fn, thisArg) { return function wrap() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; }; /***/ }), /***/ 5327: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); function encode(val) { return encodeURIComponent(val). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, '+'). replace(/%5B/gi, '['). replace(/%5D/gi, ']'); } /** * Build a URL by appending params to the end * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended * @returns {string} The formatted url */ module.exports = function buildURL(url, params, paramsSerializer) { /*eslint no-param-reassign:0*/ if (!params) { return url; } var serializedParams; if (paramsSerializer) { serializedParams = paramsSerializer(params); } else if (utils.isURLSearchParams(params)) { serializedParams = params.toString(); } else { var parts = []; utils.forEach(params, function serialize(val, key) { if (val === null || typeof val === 'undefined') { return; } if (utils.isArray(val)) { key = key + '[]'; } else { val = [val]; } utils.forEach(val, function parseValue(v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); } parts.push(encode(key) + '=' + encode(v)); }); }); serializedParams = parts.join('&'); } if (serializedParams) { var hashmarkIndex = url.indexOf('#'); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } return url; }; /***/ }), /***/ 7303: /***/ (function(module) { "use strict"; /** * Creates a new URL by combining the specified URLs * * @param {string} baseURL The base URL * @param {string} relativeURL The relative URL * @returns {string} The combined URL */ module.exports = function combineURLs(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; }; /***/ }), /***/ 4372: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs support document.cookie (function standardBrowserEnv() { return { write: function write(name, value, expires, path, domain, secure) { var cookie = []; cookie.push(name + '=' + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push('expires=' + new Date(expires).toGMTString()); } if (utils.isString(path)) { cookie.push('path=' + path); } if (utils.isString(domain)) { cookie.push('domain=' + domain); } if (secure === true) { cookie.push('secure'); } document.cookie = cookie.join('; '); }, read: function read(name) { var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); return (match ? decodeURIComponent(match[3]) : null); }, remove: function remove(name) { this.write(name, '', Date.now() - 86400000); } }; })() : // Non standard browser env (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return { write: function write() {}, read: function read() { return null; }, remove: function remove() {} }; })() ); /***/ }), /***/ 1793: /***/ (function(module) { "use strict"; /** * Determines whether the specified URL is absolute * * @param {string} url The URL to test * @returns {boolean} True if the specified URL is absolute, otherwise false */ module.exports = function isAbsoluteURL(url) { // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed // by any combination of letters, digits, plus, period, or hyphen. return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); }; /***/ }), /***/ 6268: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); /** * Determines whether the payload is an error thrown by Axios * * @param {*} payload The value to test * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false */ module.exports = function isAxiosError(payload) { return utils.isObject(payload) && (payload.isAxiosError === true); }; /***/ }), /***/ 7985: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. (function standardBrowserEnv() { var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement('a'); var originURL; /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ function resolveURL(url) { var href = url; if (msie) { // IE needs attribute set twice to normalize properties urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); /** * Determine if a URL shares the same origin as the current location * * @param {String} requestURL The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ return function isURLSameOrigin(requestURL) { var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); }; })() : // Non standard browser envs (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return function isURLSameOrigin() { return true; }; })() ); /***/ }), /***/ 6016: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); module.exports = function normalizeHeaderName(headers, normalizedName) { utils.forEach(headers, function processHeader(value, name) { if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { headers[normalizedName] = value; delete headers[name]; } }); }; /***/ }), /***/ 1623: /***/ (function(module) { // eslint-disable-next-line strict module.exports = null; /***/ }), /***/ 4109: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(4867); // Headers whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers var ignoreDuplicateOf = [ 'age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent' ]; /** * Parse headers into an object * * ``` * Date: Wed, 27 Aug 2014 08:58:49 GMT * Content-Type: application/json * Connection: keep-alive * Transfer-Encoding: chunked * ``` * * @param {String} headers Headers needing to be parsed * @returns {Object} Headers parsed into an object */ module.exports = function parseHeaders(headers) { var parsed = {}; var key; var val; var i; if (!headers) { return parsed; } utils.forEach(headers.split('\n'), function parser(line) { i = line.indexOf(':'); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { return; } if (key === 'set-cookie') { parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); } else { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } } }); return parsed; }; /***/ }), /***/ 205: /***/ (function(module) { "use strict"; module.exports = function parseProtocol(url) { var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); return match && match[1] || ''; }; /***/ }), /***/ 8713: /***/ (function(module) { "use strict"; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ module.exports = function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; }; /***/ }), /***/ 7675: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(8764)["Buffer"]; var utils = __webpack_require__(4867); /** * Convert a data object to FormData * @param {Object} obj * @param {?Object} [formData] * @returns {Object} **/ function toFormData(obj, formData) { // eslint-disable-next-line no-param-reassign formData = formData || new FormData(); var stack = []; function convertValue(value) { if (value === null) return ''; if (utils.isDate(value)) { return value.toISOString(); } if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); } return value; } function build(data, parentKey) { if (utils.isPlainObject(data) || utils.isArray(data)) { if (stack.indexOf(data) !== -1) { throw Error('Circular reference detected in ' + parentKey); } stack.push(data); utils.forEach(data, function each(value, key) { if (utils.isUndefined(value)) return; var fullKey = parentKey ? parentKey + '.' + key : key; var arr; if (value && !parentKey && typeof value === 'object') { if (utils.endsWith(key, '{}')) { // eslint-disable-next-line no-param-reassign value = JSON.stringify(value); } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) { // eslint-disable-next-line func-names arr.forEach(function(el) { !utils.isUndefined(el) && formData.append(fullKey, convertValue(el)); }); return; } } build(value, fullKey); }); stack.pop(); } else { formData.append(parentKey, convertValue(data)); } } build(obj); return formData; } module.exports = toFormData; /***/ }), /***/ 4875: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var VERSION = (__webpack_require__(7288).version); var AxiosError = __webpack_require__(723); var validators = {}; // eslint-disable-next-line func-names ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { validators[type] = function validator(thing) { return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; }; }); var deprecatedWarnings = {}; /** * Transitional option validator * @param {function|boolean?} validator - set to false if the transitional option has been removed * @param {string?} version - deprecated version / removed since version * @param {string?} message - some message with additional info * @returns {function} */ validators.transitional = function transitional(validator, version, message) { function formatMessage(opt, desc) { return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); } // eslint-disable-next-line func-names return function(value, opt, opts) { if (validator === false) { throw new AxiosError( formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), AxiosError.ERR_DEPRECATED ); } if (version && !deprecatedWarnings[opt]) { deprecatedWarnings[opt] = true; // eslint-disable-next-line no-console console.warn( formatMessage( opt, ' has been deprecated since v' + version + ' and will be removed in the near future' ) ); } return validator ? validator(value, opt, opts) : true; }; }; /** * Assert object's properties type * @param {object} options * @param {object} schema * @param {boolean?} allowUnknown */ function assertOptions(options, schema, allowUnknown) { if (typeof options !== 'object') { throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); } var keys = Object.keys(options); var i = keys.length; while (i-- > 0) { var opt = keys[i]; var validator = schema[opt]; if (validator) { var value = options[opt]; var result = value === undefined || validator(value, opt, options); if (result !== true) { throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); } continue; } if (allowUnknown !== true) { throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); } } } module.exports = { assertOptions: assertOptions, validators: validators }; /***/ }), /***/ 4867: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var bind = __webpack_require__(1849); // utils is a library of generic helper functions non-specific to axios var toString = Object.prototype.toString; // eslint-disable-next-line func-names var kindOf = (function(cache) { // eslint-disable-next-line func-names return function(thing) { var str = toString.call(thing); return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); }; })(Object.create(null)); function kindOfTest(type) { type = type.toLowerCase(); return function isKindOf(thing) { return kindOf(thing) === type; }; } /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray(val) { return Array.isArray(val); } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined(val) { return typeof val === 'undefined'; } /** * Determine if a value is a Buffer * * @param {Object} val The value to test * @returns {boolean} True if value is a Buffer, otherwise false */ function isBuffer(val) { return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); } /** * Determine if a value is an ArrayBuffer * * @function * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ var isArrayBuffer = kindOfTest('ArrayBuffer'); /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { var result; if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { result = ArrayBuffer.isView(val); } else { result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); } return result; } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber(val) { return typeof val === 'number'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a plain Object * * @param {Object} val The value to test * @return {boolean} True if value is a plain Object, otherwise false */ function isPlainObject(val) { if (kindOf(val) !== 'object') { return false; } var prototype = Object.getPrototypeOf(val); return prototype === null || prototype === Object.prototype; } /** * Determine if a value is a Date * * @function * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ var isDate = kindOfTest('Date'); /** * Determine if a value is a File * * @function * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ var isFile = kindOfTest('File'); /** * Determine if a value is a Blob * * @function * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ var isBlob = kindOfTest('Blob'); /** * Determine if a value is a FileList * * @function * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ var isFileList = kindOfTest('FileList'); /** * Determine if a value is a Function * * @param {Object} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ function isFunction(val) { return toString.call(val) === '[object Function]'; } /** * Determine if a value is a Stream * * @param {Object} val The value to test * @returns {boolean} True if value is a Stream, otherwise false */ function isStream(val) { return isObject(val) && isFunction(val.pipe); } /** * Determine if a value is a FormData * * @param {Object} thing The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(thing) { var pattern = '[object FormData]'; return thing && ( (typeof FormData === 'function' && thing instanceof FormData) || toString.call(thing) === pattern || (isFunction(thing.toString) && thing.toString() === pattern) ); } /** * Determine if a value is a URLSearchParams object * @function * @param {Object} val The value to test * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ var isURLSearchParams = kindOfTest('URLSearchParams'); /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim(str) { return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); } /** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: * typeof window -> undefined * typeof document -> undefined * * react-native: * navigator.product -> 'ReactNative' * nativescript * navigator.product -> 'NativeScript' or 'NS' */ function isStandardBrowserEnv() { if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { return false; } return ( typeof window !== 'undefined' && typeof document !== 'undefined' ); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object') { /*eslint no-param-reassign:0*/ obj = [obj]; } if (isArray(obj)) { // Iterate over array values for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (isPlainObject(result[key]) && isPlainObject(val)) { result[key] = merge(result[key], val); } else if (isPlainObject(val)) { result[key] = merge({}, val); } else if (isArray(val)) { result[key] = val.slice(); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } /** * Extends object a by mutably adding to it the properties of object b. * * @param {Object} a The object to be extended * @param {Object} b The object to copy properties from * @param {Object} thisArg The object to bind function to * @return {Object} The resulting value of object a */ function extend(a, b, thisArg) { forEach(b, function assignValue(val, key) { if (thisArg && typeof val === 'function') { a[key] = bind(val, thisArg); } else { a[key] = val; } }); return a; } /** * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) * * @param {string} content with BOM * @return {string} content value without BOM */ function stripBOM(content) { if (content.charCodeAt(0) === 0xFEFF) { content = content.slice(1); } return content; } /** * Inherit the prototype methods from one constructor into another * @param {function} constructor * @param {function} superConstructor * @param {object} [props] * @param {object} [descriptors] */ function inherits(constructor, superConstructor, props, descriptors) { constructor.prototype = Object.create(superConstructor.prototype, descriptors); constructor.prototype.constructor = constructor; props && Object.assign(constructor.prototype, props); } /** * Resolve object with deep prototype chain to a flat object * @param {Object} sourceObj source object * @param {Object} [destObj] * @param {Function} [filter] * @returns {Object} */ function toFlatObject(sourceObj, destObj, filter) { var props; var i; var prop; var merged = {}; destObj = destObj || {}; do { props = Object.getOwnPropertyNames(sourceObj); i = props.length; while (i-- > 0) { prop = props[i]; if (!merged[prop]) { destObj[prop] = sourceObj[prop]; merged[prop] = true; } } sourceObj = Object.getPrototypeOf(sourceObj); } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); return destObj; } /* * determines whether a string ends with the characters of a specified string * @param {String} str * @param {String} searchString * @param {Number} [position= 0] * @returns {boolean} */ function endsWith(str, searchString, position) { str = String(str); if (position === undefined || position > str.length) { position = str.length; } position -= searchString.length; var lastIndex = str.indexOf(searchString, position); return lastIndex !== -1 && lastIndex === position; } /** * Returns new array from array like object * @param {*} [thing] * @returns {Array} */ function toArray(thing) { if (!thing) return null; var i = thing.length; if (isUndefined(i)) return null; var arr = new Array(i); while (i-- > 0) { arr[i] = thing[i]; } return arr; } // eslint-disable-next-line func-names var isTypedArray = (function(TypedArray) { // eslint-disable-next-line func-names return function(thing) { return TypedArray && thing instanceof TypedArray; }; })(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array)); module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, isBuffer: isBuffer, isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString, isNumber: isNumber, isObject: isObject, isPlainObject: isPlainObject, isUndefined: isUndefined, isDate: isDate, isFile: isFile, isBlob: isBlob, isFunction: isFunction, isStream: isStream, isURLSearchParams: isURLSearchParams, isStandardBrowserEnv: isStandardBrowserEnv, forEach: forEach, merge: merge, extend: extend, trim: trim, stripBOM: stripBOM, inherits: inherits, toFlatObject: toFlatObject, kindOf: kindOf, kindOfTest: kindOfTest, endsWith: endsWith, toArray: toArray, isTypedArray: isTypedArray, isFileList: isFileList }; /***/ }), /***/ 9742: /***/ (function(__unused_webpack_module, exports) { "use strict"; exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function getLens (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('=') if (validLen === -1) validLen = len var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4) return [validLen, placeHoldersLen] } // base64 is 4/3 + up to two characters of the original data function byteLength (b64) { var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function _byteLength (b64, validLen, placeHoldersLen) { return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function toByteArray (b64) { var tmp var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) var curByte = 0 // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen var i for (i = 0; i < len; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[curByte++] = (tmp >> 16) & 0xFF arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] parts.push( lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3F] + '==' ) } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1] parts.push( lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3F] + lookup[(tmp << 2) & 0x3F] + '=' ) } return parts.join('') } /***/ }), /***/ 4431: /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;;(function (globalObject) { 'use strict'; /* * bignumber.js v9.1.0 * A JavaScript library for arbitrary-precision arithmetic. * https://github.com/MikeMcl/bignumber.js * Copyright (c) 2022 Michael Mclaughlin * MIT Licensed. * * BigNumber.prototype methods | BigNumber methods * | * absoluteValue abs | clone * comparedTo | config set * decimalPlaces dp | DECIMAL_PLACES * dividedBy div | ROUNDING_MODE * dividedToIntegerBy idiv | EXPONENTIAL_AT * exponentiatedBy pow | RANGE * integerValue | CRYPTO * isEqualTo eq | MODULO_MODE * isFinite | POW_PRECISION * isGreaterThan gt | FORMAT * isGreaterThanOrEqualTo gte | ALPHABET * isInteger | isBigNumber * isLessThan lt | maximum max * isLessThanOrEqualTo lte | minimum min * isNaN | random * isNegative | sum * isPositive | * isZero | * minus | * modulo mod | * multipliedBy times | * negated | * plus | * precision sd | * shiftedBy | * squareRoot sqrt | * toExponential | * toFixed | * toFormat | * toFraction | * toJSON | * toNumber | * toPrecision | * toString | * valueOf | * */ var BigNumber, isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil = Math.ceil, mathfloor = Math.floor, bignumberError = '[BigNumber Error] ', tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', BASE = 1e14, LOG_BASE = 14, MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 // MAX_INT32 = 0x7fffffff, // 2^31 - 1 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE = 1e7, // EDITABLE // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and // the arguments to toExponential, toFixed, toFormat, and toPrecision. MAX = 1E9; // 0 to MAX_INT32 /* * Create and return a BigNumber constructor. */ function clone(configObject) { var div, convertBase, parseNumeric, P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, ONE = new BigNumber(1), //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- // The default values below must be integers within the inclusive ranges stated. // The values can also be changed at run-time using BigNumber.set. // The maximum number of decimal places for operations involving division. DECIMAL_PLACES = 20, // 0 to MAX // The rounding mode used when rounding to the above decimal places, and when using // toExponential, toFixed, toFormat and toPrecision, and round (default value). // UP 0 Away from zero. // DOWN 1 Towards zero. // CEIL 2 Towards +Infinity. // FLOOR 3 Towards -Infinity. // HALF_UP 4 Towards nearest neighbour. If equidistant, up. // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. ROUNDING_MODE = 4, // 0 to 8 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] // The exponent value at and beneath which toString returns exponential notation. // Number type: -7 TO_EXP_NEG = -7, // 0 to -MAX // The exponent value at and above which toString returns exponential notation. // Number type: 21 TO_EXP_POS = 21, // 0 to MAX // RANGE : [MIN_EXP, MAX_EXP] // The minimum exponent value, beneath which underflow to zero occurs. // Number type: -324 (5e-324) MIN_EXP = -1e7, // -1 to -MAX // The maximum exponent value, above which overflow to Infinity occurs. // Number type: 308 (1.7976931348623157e+308) // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. MAX_EXP = 1e7, // 1 to MAX // Whether to use cryptographically-secure random number generation, if available. CRYPTO = false, // true or false // The modulo mode used when calculating the modulus: a mod n. // The quotient (q = a / n) is calculated according to the corresponding rounding mode. // The remainder (r) is calculated as: r = a - n * q. // // UP 0 The remainder is positive if the dividend is negative, else is negative. // DOWN 1 The remainder has the same sign as the dividend. // This modulo mode is commonly known as 'truncated division' and is // equivalent to (a % n) in JavaScript. // FLOOR 3 The remainder has the same sign as the divisor (Python %). // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). // The remainder is always positive. // // The truncated division, floored division, Euclidian division and IEEE 754 remainder // modes are commonly used for the modulus operation. // Although the other rounding modes can also be used, they may not give useful results. MODULO_MODE = 1, // 0 to 9 // The maximum number of significant digits of the result of the exponentiatedBy operation. // If POW_PRECISION is 0, there will be unlimited significant digits. POW_PRECISION = 0, // 0 to MAX // The format specification used by the BigNumber.prototype.toFormat method. FORMAT = { prefix: '', groupSize: 3, secondaryGroupSize: 0, groupSeparator: ',', decimalSeparator: '.', fractionGroupSize: 0, fractionGroupSeparator: '\xA0', // non-breaking space suffix: '' }, // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', // '-', '.', whitespace, or repeated character. // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', alphabetHasNormalDecimalDigits = true; //------------------------------------------------------------------------------------------ // CONSTRUCTOR /* * The BigNumber constructor and exported function. * Create and return a new instance of a BigNumber object. * * v {number|string|BigNumber} A numeric value. * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. */ function BigNumber(v, b) { var alphabet, c, caseChanged, e, i, isNum, len, str, x = this; // Enable constructor call without `new`. if (!(x instanceof BigNumber)) return new BigNumber(v, b); if (b == null) { if (v && v._isBigNumber === true) { x.s = v.s; if (!v.c || v.e > MAX_EXP) { x.c = x.e = null; } else if (v.e < MIN_EXP) { x.c = [x.e = 0]; } else { x.e = v.e; x.c = v.c.slice(); } return; } if ((isNum = typeof v == 'number') && v * 0 == 0) { // Use `1 / n` to handle minus zero also. x.s = 1 / v < 0 ? (v = -v, -1) : 1; // Fast path for integers, where n < 2147483648 (2**31). if (v === ~~v) { for (e = 0, i = v; i >= 10; i /= 10, e++); if (e > MAX_EXP) { x.c = x.e = null; } else { x.e = e; x.c = [v]; } return; } str = String(v); } else { if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; } // Decimal point? if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); // Exponential form? if ((i = str.search(/e/i)) > 0) { // Determine exponent. if (e < 0) e = i; e += +str.slice(i + 1); str = str.substring(0, i); } else if (e < 0) { // Integer. e = str.length; } } else { // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' intCheck(b, 2, ALPHABET.length, 'Base'); // Allow exponential notation to be used with base 10 argument, while // also rounding to DECIMAL_PLACES as with other bases. if (b == 10 && alphabetHasNormalDecimalDigits) { x = new BigNumber(v); return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); } str = String(v); if (isNum = typeof v == 'number') { // Avoid potential interpretation of Infinity and NaN as base 44+ values. if (v * 0 != 0) return parseNumeric(x, str, isNum, b); x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { throw Error (tooManyDigits + v); } } else { x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; } alphabet = ALPHABET.slice(0, b); e = i = 0; // Check that str is a valid base b number. // Don't use RegExp, so alphabet can contain special characters. for (len = str.length; i < len; i++) { if (alphabet.indexOf(c = str.charAt(i)) < 0) { if (c == '.') { // If '.' is not the first character and it has not be found before. if (i > e) { e = len; continue; } } else if (!caseChanged) { // Allow e.g. hexadecimal 'FF' as well as 'ff'. if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { caseChanged = true; i = -1; e = 0; continue; } } return parseNumeric(x, String(v), isNum, b); } } // Prevent later check for length on converted number. isNum = false; str = convertBase(str, b, 10, x.s); // Decimal point? if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); else e = str.length; } // Determine leading zeros. for (i = 0; str.charCodeAt(i) === 48; i++); // Determine trailing zeros. for (len = str.length; str.charCodeAt(--len) === 48;); if (str = str.slice(i, ++len)) { len -= i; // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' if (isNum && BigNumber.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { throw Error (tooManyDigits + (x.s * v)); } // Overflow? if ((e = e - i - 1) > MAX_EXP) { // Infinity. x.c = x.e = null; // Underflow? } else if (e < MIN_EXP) { // Zero. x.c = [x.e = 0]; } else { x.e = e; x.c = []; // Transform base // e is the base 10 exponent. // i is where to slice str to get the first element of the coefficient array. i = (e + 1) % LOG_BASE; if (e < 0) i += LOG_BASE; // i < 1 if (i < len) { if (i) x.c.push(+str.slice(0, i)); for (len -= LOG_BASE; i < len;) { x.c.push(+str.slice(i, i += LOG_BASE)); } i = LOG_BASE - (str = str.slice(i)).length; } else { i -= len; } for (; i--; str += '0'); x.c.push(+str); } } else { // Zero. x.c = [x.e = 0]; } } // CONSTRUCTOR PROPERTIES BigNumber.clone = clone; BigNumber.ROUND_UP = 0; BigNumber.ROUND_DOWN = 1; BigNumber.ROUND_CEIL = 2; BigNumber.ROUND_FLOOR = 3; BigNumber.ROUND_HALF_UP = 4; BigNumber.ROUND_HALF_DOWN = 5; BigNumber.ROUND_HALF_EVEN = 6; BigNumber.ROUND_HALF_CEIL = 7; BigNumber.ROUND_HALF_FLOOR = 8; BigNumber.EUCLID = 9; /* * Configure infrequently-changing library-wide settings. * * Accept an object with the following optional properties (if the value of a property is * a number, it must be an integer within the inclusive range stated): * * DECIMAL_PLACES {number} 0 to MAX * ROUNDING_MODE {number} 0 to 8 * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] * CRYPTO {boolean} true or false * MODULO_MODE {number} 0 to 9 * POW_PRECISION {number} 0 to MAX * ALPHABET {string} A string of two or more unique characters which does * not contain '.'. * FORMAT {object} An object with some of the following properties: * prefix {string} * groupSize {number} * secondaryGroupSize {number} * groupSeparator {string} * decimalSeparator {string} * fractionGroupSize {number} * fractionGroupSeparator {string} * suffix {string} * * (The values assigned to the above FORMAT object properties are not checked for validity.) * * E.g. * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) * * Ignore properties/parameters set to null or undefined, except for ALPHABET. * * Return an object with the properties current values. */ BigNumber.config = BigNumber.set = function (obj) { var p, v; if (obj != null) { if (typeof obj == 'object') { // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { v = obj[p]; intCheck(v, 0, MAX, p); DECIMAL_PLACES = v; } // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { v = obj[p]; intCheck(v, 0, 8, p); ROUNDING_MODE = v; } // EXPONENTIAL_AT {number|number[]} // Integer, -MAX to MAX inclusive or // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { v = obj[p]; if (v && v.pop) { intCheck(v[0], -MAX, 0, p); intCheck(v[1], 0, MAX, p); TO_EXP_NEG = v[0]; TO_EXP_POS = v[1]; } else { intCheck(v, -MAX, MAX, p); TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); } } // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' if (obj.hasOwnProperty(p = 'RANGE')) { v = obj[p]; if (v && v.pop) { intCheck(v[0], -MAX, -1, p); intCheck(v[1], 1, MAX, p); MIN_EXP = v[0]; MAX_EXP = v[1]; } else { intCheck(v, -MAX, MAX, p); if (v) { MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); } else { throw Error (bignumberError + p + ' cannot be zero: ' + v); } } } // CRYPTO {boolean} true or false. // '[BigNumber Error] CRYPTO not true or false: {v}' // '[BigNumber Error] crypto unavailable' if (obj.hasOwnProperty(p = 'CRYPTO')) { v = obj[p]; if (v === !!v) { if (v) { if (typeof crypto != 'undefined' && crypto && (crypto.getRandomValues || crypto.randomBytes)) { CRYPTO = v; } else { CRYPTO = !v; throw Error (bignumberError + 'crypto unavailable'); } } else { CRYPTO = v; } } else { throw Error (bignumberError + p + ' not true or false: ' + v); } } // MODULO_MODE {number} Integer, 0 to 9 inclusive. // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' if (obj.hasOwnProperty(p = 'MODULO_MODE')) { v = obj[p]; intCheck(v, 0, 9, p); MODULO_MODE = v; } // POW_PRECISION {number} Integer, 0 to MAX inclusive. // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' if (obj.hasOwnProperty(p = 'POW_PRECISION')) { v = obj[p]; intCheck(v, 0, MAX, p); POW_PRECISION = v; } // FORMAT {object} // '[BigNumber Error] FORMAT not an object: {v}' if (obj.hasOwnProperty(p = 'FORMAT')) { v = obj[p]; if (typeof v == 'object') FORMAT = v; else throw Error (bignumberError + p + ' not an object: ' + v); } // ALPHABET {string} // '[BigNumber Error] ALPHABET invalid: {v}' if (obj.hasOwnProperty(p = 'ALPHABET')) { v = obj[p]; // Disallow if less than two characters, // or if it contains '+', '-', '.', whitespace, or a repeated character. if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; ALPHABET = v; } else { throw Error (bignumberError + p + ' invalid: ' + v); } } } else { // '[BigNumber Error] Object expected: {v}' throw Error (bignumberError + 'Object expected: ' + obj); } } return { DECIMAL_PLACES: DECIMAL_PLACES, ROUNDING_MODE: ROUNDING_MODE, EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], RANGE: [MIN_EXP, MAX_EXP], CRYPTO: CRYPTO, MODULO_MODE: MODULO_MODE, POW_PRECISION: POW_PRECISION, FORMAT: FORMAT, ALPHABET: ALPHABET }; }; /* * Return true if v is a BigNumber instance, otherwise return false. * * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. * * v {any} * * '[BigNumber Error] Invalid BigNumber: {v}' */ BigNumber.isBigNumber = function (v) { if (!v || v._isBigNumber !== true) return false; if (!BigNumber.DEBUG) return true; var i, n, c = v.c, e = v.e, s = v.s; out: if ({}.toString.call(c) == '[object Array]') { if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { // If the first element is zero, the BigNumber value must be zero. if (c[0] === 0) { if (e === 0 && c.length === 1) return true; break out; } // Calculate number of digits that c[0] should have, based on the exponent. i = (e + 1) % LOG_BASE; if (i < 1) i += LOG_BASE; // Calculate number of digits of c[0]. //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { if (String(c[0]).length == i) { for (i = 0; i < c.length; i++) { n = c[i]; if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; } // Last element cannot be zero, unless it is the only element. if (n !== 0) return true; } } // Infinity/NaN } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { return true; } throw Error (bignumberError + 'Invalid BigNumber: ' + v); }; /* * Return a new BigNumber whose value is the maximum of the arguments. * * arguments {number|string|BigNumber} */ BigNumber.maximum = BigNumber.max = function () { return maxOrMin(arguments, P.lt); }; /* * Return a new BigNumber whose value is the minimum of the arguments. * * arguments {number|string|BigNumber} */ BigNumber.minimum = BigNumber.min = function () { return maxOrMin(arguments, P.gt); }; /* * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing * zeros are produced). * * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' * '[BigNumber Error] crypto unavailable' */ BigNumber.random = (function () { var pow2_53 = 0x20000000000000; // Return a 53 bit integer n, where 0 <= n < 9007199254740992. // Check if Math.random() produces more than 32 bits of randomness. // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. var random53bitInt = (Math.random() * pow2_53) & 0x1fffff ? function () { return mathfloor(Math.random() * pow2_53); } : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + (Math.random() * 0x800000 | 0); }; return function (dp) { var a, b, e, k, v, i = 0, c = [], rand = new BigNumber(ONE); if (dp == null) dp = DECIMAL_PLACES; else intCheck(dp, 0, MAX); k = mathceil(dp / LOG_BASE); if (CRYPTO) { // Browsers supporting crypto.getRandomValues. if (crypto.getRandomValues) { a = crypto.getRandomValues(new Uint32Array(k *= 2)); for (; i < k;) { // 53 bits: // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) // 11111 11111111 11111111 11111111 11100000 00000000 00000000 // ((Math.pow(2, 32) - 1) >>> 11).toString(2) // 11111 11111111 11111111 // 0x20000 is 2^21. v = a[i] * 0x20000 + (a[i + 1] >>> 11); // Rejection sampling: // 0 <= v < 9007199254740992 // Probability that v >= 9e15, is // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 if (v >= 9e15) { b = crypto.getRandomValues(new Uint32Array(2)); a[i] = b[0]; a[i + 1] = b[1]; } else { // 0 <= v <= 8999999999999999 // 0 <= (v % 1e14) <= 99999999999999 c.push(v % 1e14); i += 2; } } i = k / 2; // Node.js supporting crypto.randomBytes. } else if (crypto.randomBytes) { // buffer a = crypto.randomBytes(k *= 7); for (; i < k;) { // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 // 0x100000000 is 2^32, 0x1000000 is 2^24 // 11111 11111111 11111111 11111111 11111111 11111111 11111111 // 0 <= v < 9007199254740992 v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; if (v >= 9e15) { crypto.randomBytes(7).copy(a, i); } else { // 0 <= (v % 1e14) <= 99999999999999 c.push(v % 1e14); i += 7; } } i = k / 7; } else { CRYPTO = false; throw Error (bignumberError + 'crypto unavailable'); } } // Use Math.random. if (!CRYPTO) { for (; i < k;) { v = random53bitInt(); if (v < 9e15) c[i++] = v % 1e14; } } k = c[--i]; dp %= LOG_BASE; // Convert trailing digits to zeros according to dp. if (k && dp) { v = POWS_TEN[LOG_BASE - dp]; c[i] = mathfloor(k / v) * v; } // Remove trailing elements which are zero. for (; c[i] === 0; c.pop(), i--); // Zero? if (i < 0) { c = [e = 0]; } else { // Remove leading elements which are zero and adjust exponent accordingly. for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); // Count the digits of the first element of c to determine leading zeros, and... for (i = 1, v = c[0]; v >= 10; v /= 10, i++); // adjust the exponent accordingly. if (i < LOG_BASE) e -= LOG_BASE - i; } rand.e = e; rand.c = c; return rand; }; })(); /* * Return a BigNumber whose value is the sum of the arguments. * * arguments {number|string|BigNumber} */ BigNumber.sum = function () { var i = 1, args = arguments, sum = new BigNumber(args[0]); for (; i < args.length;) sum = sum.plus(args[i++]); return sum; }; // PRIVATE FUNCTIONS // Called by BigNumber and BigNumber.prototype.toString. convertBase = (function () { var decimal = '0123456789'; /* * Convert string of baseIn to an array of numbers of baseOut. * Eg. toBaseOut('255', 10, 16) returns [15, 15]. * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. */ function toBaseOut(str, baseIn, baseOut, alphabet) { var j, arr = [0], arrL, i = 0, len = str.length; for (; i < len;) { for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); arr[0] += alphabet.indexOf(str.charAt(i++)); for (j = 0; j < arr.length; j++) { if (arr[j] > baseOut - 1) { if (arr[j + 1] == null) arr[j + 1] = 0; arr[j + 1] += arr[j] / baseOut | 0; arr[j] %= baseOut; } } } return arr.reverse(); } // Convert a numeric string of baseIn to a numeric string of baseOut. // If the caller is toString, we are converting from base 10 to baseOut. // If the caller is BigNumber, we are converting from baseIn to base 10. return function (str, baseIn, baseOut, sign, callerIsToString) { var alphabet, d, e, k, r, x, xc, y, i = str.indexOf('.'), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; // Non-integer. if (i >= 0) { k = POW_PRECISION; // Unlimited precision. POW_PRECISION = 0; str = str.replace('.', ''); y = new BigNumber(baseIn); x = y.pow(str.length - i); POW_PRECISION = k; // Convert str as if an integer, then restore the fraction part by dividing the // result by its base raised to a power. y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), 10, baseOut, decimal); y.e = y.c.length; } // Convert the number as integer. xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet = ALPHABET, decimal) : (alphabet = decimal, ALPHABET)); // xc now represents str as an integer and converted to baseOut. e is the exponent. e = k = xc.length; // Remove trailing zeros. for (; xc[--k] == 0; xc.pop()); // Zero? if (!xc[0]) return alphabet.charAt(0); // Does str represent an integer? If so, no need for the division. if (i < 0) { --e; } else { x.c = xc; x.e = e; // The sign is needed for correct rounding. x.s = sign; x = div(x, y, dp, rm, baseOut); xc = x.c; r = x.r; e = x.e; } // xc now represents str converted to baseOut. // THe index of the rounding digit. d = e + dp + 1; // The rounding digit: the digit to the right of the digit that may be rounded up. i = xc[d]; // Look at the rounding digits and mode to determine whether to round up. k = baseOut / 2; r = r || d < 0 || xc[d + 1] != null; r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7)); // If the index of the rounding digit is not greater than zero, or xc represents // zero, then the result of the base conversion is zero or, if rounding up, a value // such as 0.00001. if (d < 1 || !xc[0]) { // 1^-dp or 0 str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); } else { // Truncate xc to the required number of decimal places. xc.length = d; // Round up? if (r) { // Rounding up may mean the previous digit has to be rounded up and so on. for (--baseOut; ++xc[--d] > baseOut;) { xc[d] = 0; if (!d) { ++e; xc = [1].concat(xc); } } } // Determine trailing zeros. for (k = xc.length; !xc[--k];); // E.g. [4, 11, 15] becomes 4bf. for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); // Add leading zeros, decimal point and trailing zeros as required. str = toFixedPoint(str, e, alphabet.charAt(0)); } // The caller will add the sign. return str; }; })(); // Perform division in the specified base. Called by div and convertBase. div = (function () { // Assume non-zero x and k. function multiply(x, k, base) { var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE, khi = k / SQRT_BASE | 0; for (x = x.slice(); i--;) { xlo = x[i] % SQRT_BASE; xhi = x[i] / SQRT_BASE | 0; m = khi * xlo + xhi * klo; temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; x[i] = temp % base; } if (carry) x = [carry].concat(x); return x; } function compare(a, b, aL, bL) { var i, cmp; if (aL != bL) { cmp = aL > bL ? 1 : -1; } else { for (i = cmp = 0; i < aL; i++) { if (a[i] != b[i]) { cmp = a[i] > b[i] ? 1 : -1; break; } } } return cmp; } function subtract(a, b, aL, base) { var i = 0; // Subtract b from a. for (; aL--;) { a[aL] -= i; i = a[aL] < b[aL] ? 1 : 0; a[aL] = i * base + a[aL] - b[aL]; } // Remove leading zeros. for (; !a[0] && a.length > 1; a.splice(0, 1)); } // x: dividend, y: divisor. return function (x, y, dp, rm, base) { var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c; // Either NaN, Infinity or 0? if (!xc || !xc[0] || !yc || !yc[0]) { return new BigNumber( // Return NaN if either NaN, or both Infinity or 0. !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. xc && xc[0] == 0 || !yc ? s * 0 : s / 0 ); } q = new BigNumber(s); qc = q.c = []; e = x.e - y.e; s = dp + e + 1; if (!base) { base = BASE; e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); s = s / LOG_BASE | 0; } // Result exponent may be one less then the current value of e. // The coefficients of the BigNumbers from convertBase may have trailing zeros. for (i = 0; yc[i] == (xc[i] || 0); i++); if (yc[i] > (xc[i] || 0)) e--; if (s < 0) { qc.push(1); more = true; } else { xL = xc.length; yL = yc.length; i = 0; s += 2; // Normalise xc and yc so highest order digit of yc is >= base / 2. n = mathfloor(base / (yc[0] + 1)); // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. // if (n > 1 || n++ == 1 && yc[0] < base / 2) { if (n > 1) { yc = multiply(yc, n, base); xc = multiply(xc, n, base); yL = yc.length; xL = xc.length; } xi = yL; rem = xc.slice(0, yL); remL = rem.length; // Add zeros to make remainder as long as divisor. for (; remL < yL; rem[remL++] = 0); yz = yc.slice(); yz = [0].concat(yz); yc0 = yc[0]; if (yc[1] >= base / 2) yc0++; // Not necessary, but to prevent trial digit n > base, when using base 3. // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; do { n = 0; // Compare divisor and remainder. cmp = compare(yc, rem, yL, remL); // If divisor < remainder. if (cmp < 0) { // Calculate trial digit, n. rem0 = rem[0]; if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); // n is how many times the divisor goes into the current remainder. n = mathfloor(rem0 / yc0); // Algorithm: // product = divisor multiplied by trial digit (n). // Compare product and remainder. // If product is greater than remainder: // Subtract divisor from product, decrement trial digit. // Subtract product from remainder. // If product was less than remainder at the last compare: // Compare new remainder and divisor. // If remainder is greater than divisor: // Subtract divisor from remainder, increment trial digit. if (n > 1) { // n may be > base only when base is 3. if (n >= base) n = base - 1; // product = divisor * trial digit. prod = multiply(yc, n, base); prodL = prod.length; remL = rem.length; // Compare product and remainder. // If product > remainder then trial digit n too high. // n is 1 too high about 5% of the time, and is not known to have // ever been more than 1 too high. while (compare(prod, rem, prodL, remL) == 1) { n--; // Subtract divisor from product. subtract(prod, yL < prodL ? yz : yc, prodL, base); prodL = prod.length; cmp = 1; } } else { // n is 0 or 1, cmp is -1. // If n is 0, there is no need to compare yc and rem again below, // so change cmp to 1 to avoid it. // If n is 1, leave cmp as -1, so yc and rem are compared again. if (n == 0) { // divisor < remainder, so n must be at least 1. cmp = n = 1; } // product = divisor prod = yc.slice(); prodL = prod.length; } if (prodL < remL) prod = [0].concat(prod); // Subtract product from remainder. subtract(rem, prod, remL, base); remL = rem.length; // If product was < remainder. if (cmp == -1) { // Compare divisor and new remainder. // If divisor < new remainder, subtract divisor from remainder. // Trial digit n too low. // n is 1 too low about 5% of the time, and very rarely 2 too low. while (compare(yc, rem, yL, remL) < 1) { n++; // Subtract divisor from remainder. subtract(rem, yL < remL ? yz : yc, remL, base); remL = rem.length; } } } else if (cmp === 0) { n++; rem = [0]; } // else cmp === 1 and n will be 0 // Add the next digit, n, to the result array. qc[i++] = n; // Update the remainder. if (rem[0]) { rem[remL++] = xc[xi] || 0; } else { rem = [xc[xi]]; remL = 1; } } while ((xi++ < xL || rem[0] != null) && s--); more = rem[0] != null; // Leading zero? if (!qc[0]) qc.splice(0, 1); } if (base == BASE) { // To calculate q.e, first get the number of digits of qc[0]. for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); // Caller is convertBase. } else { q.e = e; q.r = +more; } return q; }; })(); /* * Return a string representing the value of BigNumber n in fixed-point or exponential * notation rounded to the specified decimal places or significant digits. * * n: a BigNumber. * i: the index of the last digit required (i.e. the digit that may be rounded up). * rm: the rounding mode. * id: 1 (toExponential) or 2 (toPrecision). */ function format(n, i, rm, id) { var c0, e, ne, len, str; if (rm == null) rm = ROUNDING_MODE; else intCheck(rm, 0, 8); if (!n.c) return n.toString(); c0 = n.c[0]; ne = n.e; if (i == null) { str = coeffToString(n.c); str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential(str, ne) : toFixedPoint(str, ne, '0'); } else { n = round(new BigNumber(n), i, rm); // n.e may have changed if the value was rounded up. e = n.e; str = coeffToString(n.c); len = str.length; // toPrecision returns exponential notation if the number of significant digits // specified is less than the number of digits necessary to represent the integer // part of the value in fixed-point notation. // Exponential notation. if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { // Append zeros? for (; len < i; str += '0', len++); str = toExponential(str, e); // Fixed-point notation. } else { i -= ne; str = toFixedPoint(str, e, '0'); // Append zeros? if (e + 1 > len) { if (--i > 0) for (str += '.'; i--; str += '0'); } else { i += e - len; if (i > 0) { if (e + 1 == len) str += '.'; for (; i--; str += '0'); } } } } return n.s < 0 && c0 ? '-' + str : str; } // Handle BigNumber.max and BigNumber.min. function maxOrMin(args, method) { var n, i = 1, m = new BigNumber(args[0]); for (; i < args.length; i++) { n = new BigNumber(args[i]); // If any number is NaN, return NaN. if (!n.s) { m = n; break; } else if (method.call(m, n)) { m = n; } } return m; } /* * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. * Called by minus, plus and times. */ function normalise(n, c, e) { var i = 1, j = c.length; // Remove trailing zeros. for (; !c[--j]; c.pop()); // Calculate the base 10 exponent. First get the number of digits of c[0]. for (j = c[0]; j >= 10; j /= 10, i++); // Overflow? if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { // Infinity. n.c = n.e = null; // Underflow? } else if (e < MIN_EXP) { // Zero. n.c = [n.e = 0]; } else { n.e = e; n.c = c; } return n; } // Handle values that fail the validity test in BigNumber. parseNumeric = (function () { var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; return function (x, str, isNum, b) { var base, s = isNum ? str : str.replace(whitespaceOrPlus, ''); // No exception on ±Infinity or NaN. if (isInfinityOrNaN.test(s)) { x.s = isNaN(s) ? null : s < 0 ? -1 : 1; } else { if (!isNum) { // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i s = s.replace(basePrefix, function (m, p1, p2) { base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; return !b || b == base ? p1 : m; }); if (b) { base = b; // E.g. '1.' to '1', '.1' to '0.1' s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); } if (str != s) return new BigNumber(s, base); } // '[BigNumber Error] Not a number: {n}' // '[BigNumber Error] Not a base {b} number: {n}' if (BigNumber.DEBUG) { throw Error (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); } // NaN x.s = null; } x.c = x.e = null; } })(); /* * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. * If r is truthy, it is known that there are more digits after the rounding digit. */ function round(x, sd, rm, r) { var d, i, j, k, n, ni, rd, xc = x.c, pows10 = POWS_TEN; // if x is not Infinity or NaN... if (xc) { // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. // n is a base 1e14 number, the value of the element of array x.c containing rd. // ni is the index of n within x.c. // d is the number of digits of n. // i is the index of rd within n including leading zeros. // j is the actual index of rd within n (if < 0, rd is a leading zero). out: { // Get the number of digits of the first element of xc. for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); i = sd - d; // If the rounding digit is in the first element of xc... if (i < 0) { i += LOG_BASE; j = sd; n = xc[ni = 0]; // Get the rounding digit at index j of n. rd = n / pows10[d - j - 1] % 10 | 0; } else { ni = mathceil((i + 1) / LOG_BASE); if (ni >= xc.length) { if (r) { // Needed by sqrt. for (; xc.length <= ni; xc.push(0)); n = rd = 0; d = 1; i %= LOG_BASE; j = i - LOG_BASE + 1; } else { break out; } } else { n = k = xc[ni]; // Get the number of digits of n. for (d = 1; k >= 10; k /= 10, d++); // Get the index of rd within n. i %= LOG_BASE; // Get the index of rd within n, adjusted for leading zeros. // The number of leading zeros of n is given by LOG_BASE - d. j = i - LOG_BASE + d; // Get the rounding digit at index j of n. rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0; } } r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? // The expression n % pows10[d - j - 1] returns all digits of n to the right // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || rm == (x.s < 0 ? 8 : 7)); if (sd < 1 || !xc[0]) { xc.length = 0; if (r) { // Convert sd to decimal places. sd -= x.e + 1; // 1, 0.1, 0.01, 0.001, 0.0001 etc. xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; x.e = -sd || 0; } else { // Zero. xc[0] = x.e = 0; } return x; } // Remove excess digits. if (i == 0) { xc.length = ni; k = 1; ni--; } else { xc.length = ni + 1; k = pows10[LOG_BASE - i]; // E.g. 56700 becomes 56000 if 7 is the rounding digit. // j > 0 means i > number of leading zeros of n. xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; } // Round up? if (r) { for (; ;) { // If the digit to be rounded up is in the first element of xc... if (ni == 0) { // i will be the length of xc[0] before k is added. for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); j = xc[0] += k; for (k = 1; j >= 10; j /= 10, k++); // if i != k the length has increased. if (i != k) { x.e++; if (xc[0] == BASE) xc[0] = 1; } break; } else { xc[ni] += k; if (xc[ni] != BASE) break; xc[ni--] = 0; k = 1; } } } // Remove trailing zeros. for (i = xc.length; xc[--i] === 0; xc.pop()); } // Overflow? Infinity. if (x.e > MAX_EXP) { x.c = x.e = null; // Underflow? Zero. } else if (x.e < MIN_EXP) { x.c = [x.e = 0]; } } return x; } function valueOf(n) { var str, e = n.e; if (e === null) return n.toString(); str = coeffToString(n.c); str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(str, e) : toFixedPoint(str, e, '0'); return n.s < 0 ? '-' + str : str; } // PROTOTYPE/INSTANCE METHODS /* * Return a new BigNumber whose value is the absolute value of this BigNumber. */ P.absoluteValue = P.abs = function () { var x = new BigNumber(this); if (x.s < 0) x.s = 1; return x; }; /* * Return * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), * 0 if they have the same value, * or null if the value of either is NaN. */ P.comparedTo = function (y, b) { return compare(this, new BigNumber(y, b)); }; /* * If dp is undefined or null or true or false, return the number of decimal places of the * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. * * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or * ROUNDING_MODE if rm is omitted. * * [dp] {number} Decimal places: integer, 0 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' */ P.decimalPlaces = P.dp = function (dp, rm) { var c, n, v, x = this; if (dp != null) { intCheck(dp, 0, MAX); if (rm == null) rm = ROUNDING_MODE; else intCheck(rm, 0, 8); return round(new BigNumber(x), dp + x.e + 1, rm); } if (!(c = x.c)) return null; n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; // Subtract the number of trailing zeros of the last number. if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); if (n < 0) n = 0; return n; }; /* * n / 0 = I * n / N = N * n / I = 0 * 0 / n = 0 * 0 / 0 = N * 0 / N = N * 0 / I = 0 * N / n = N * N / 0 = N * N / N = N * N / I = N * I / n = I * I / 0 = I * I / N = N * I / I = N * * Return a new BigNumber whose value is the value of this BigNumber divided by the value of * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. */ P.dividedBy = P.div = function (y, b) { return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); }; /* * Return a new BigNumber whose value is the integer part of dividing the value of this * BigNumber by the value of BigNumber(y, b). */ P.dividedToIntegerBy = P.idiv = function (y, b) { return div(this, new BigNumber(y, b), 0, 1); }; /* * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. * * If m is present, return the result modulo m. * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. * * The modular power operation works efficiently when x, n, and m are integers, otherwise it * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. * * n {number|string|BigNumber} The exponent. An integer. * [m] {number|string|BigNumber} The modulus. * * '[BigNumber Error] Exponent not an integer: {n}' */ P.exponentiatedBy = P.pow = function (n, m) { var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, x = this; n = new BigNumber(n); // Allow NaN and ±Infinity, but not other non-integers. if (n.c && !n.isInteger()) { throw Error (bignumberError + 'Exponent not an integer: ' + valueOf(n)); } if (m != null) m = new BigNumber(m); // Exponent of MAX_SAFE_INTEGER is 15. nIsBig = n.e > 14; // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { // The sign of the result of pow when x is negative depends on the evenness of n. // If +n overflows to ±Infinity, the evenness of n would be not be known. y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n))); return m ? y.mod(m) : y; } nIsNeg = n.s < 0; if (m) { // x % m returns NaN if abs(m) is zero, or m is NaN. if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); isModExp = !nIsNeg && x.isInteger() && m.isInteger(); if (isModExp) x = x.mod(m); // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 // [1, 240000000] ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 // [80000000000000] [99999750000000] : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { // If x is negative and n is odd, k = -0, else k = 0. k = x.s < 0 && isOdd(n) ? -0 : 0; // If x >= 1, k = ±Infinity. if (x.e > -1) k = 1 / k; // If n is negative return ±0, else return ±Infinity. return new BigNumber(nIsNeg ? 1 / k : k); } else if (POW_PRECISION) { // Truncating each coefficient array to a length of k after each multiplication // equates to truncating significant digits to POW_PRECISION + [28, 41], // i.e. there will be a minimum of 28 guard digits retained. k = mathceil(POW_PRECISION / LOG_BASE + 2); } if (nIsBig) { half = new BigNumber(0.5); if (nIsNeg) n.s = 1; nIsOdd = isOdd(n); } else { i = Math.abs(+valueOf(n)); nIsOdd = i % 2; } y = new BigNumber(ONE); // Performs 54 loop iterations for n of 9007199254740991. for (; ;) { if (nIsOdd) { y = y.times(x); if (!y.c) break; if (k) { if (y.c.length > k) y.c.length = k; } else if (isModExp) { y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); } } if (i) { i = mathfloor(i / 2); if (i === 0) break; nIsOdd = i % 2; } else { n = n.times(half); round(n, n.e + 1, 1); if (n.e > 14) { nIsOdd = isOdd(n); } else { i = +valueOf(n); if (i === 0) break; nIsOdd = i % 2; } } x = x.times(x); if (k) { if (x.c && x.c.length > k) x.c.length = k; } else if (isModExp) { x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); } } if (isModExp) return y; if (nIsNeg) y = ONE.div(y); return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; }; /* * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer * using rounding mode rm, or ROUNDING_MODE if rm is omitted. * * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' */ P.integerValue = function (rm) { var n = new BigNumber(this); if (rm == null) rm = ROUNDING_MODE; else intCheck(rm, 0, 8); return round(n, n.e + 1, rm); }; /* * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), * otherwise return false. */ P.isEqualTo = P.eq = function (y, b) { return compare(this, new BigNumber(y, b)) === 0; }; /* * Return true if the value of this BigNumber is a finite number, otherwise return false. */ P.isFinite = function () { return !!this.c; }; /* * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), * otherwise return false. */ P.isGreaterThan = P.gt = function (y, b) { return compare(this, new BigNumber(y, b)) > 0; }; /* * Return true if the value of this BigNumber is greater than or equal to the value of * BigNumber(y, b), otherwise return false. */ P.isGreaterThanOrEqualTo = P.gte = function (y, b) { return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; }; /* * Return true if the value of this BigNumber is an integer, otherwise return false. */ P.isInteger = function () { return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; }; /* * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), * otherwise return false. */ P.isLessThan = P.lt = function (y, b) { return compare(this, new BigNumber(y, b)) < 0; }; /* * Return true if the value of this BigNumber is less than or equal to the value of * BigNumber(y, b), otherwise return false. */ P.isLessThanOrEqualTo = P.lte = function (y, b) { return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; }; /* * Return true if the value of this BigNumber is NaN, otherwise return false. */ P.isNaN = function () { return !this.s; }; /* * Return true if the value of this BigNumber is negative, otherwise return false. */ P.isNegative = function () { return this.s < 0; }; /* * Return true if the value of this BigNumber is positive, otherwise return false. */ P.isPositive = function () { return this.s > 0; }; /* * Return true if the value of this BigNumber is 0 or -0, otherwise return false. */ P.isZero = function () { return !!this.c && this.c[0] == 0; }; /* * n - 0 = n * n - N = N * n - I = -I * 0 - n = -n * 0 - 0 = 0 * 0 - N = N * 0 - I = -I * N - n = N * N - 0 = N * N - N = N * N - I = N * I - n = I * I - 0 = I * I - N = N * I - I = N * * Return a new BigNumber whose value is the value of this BigNumber minus the value of * BigNumber(y, b). */ P.minus = function (y, b) { var i, j, t, xLTy, x = this, a = x.s; y = new BigNumber(y, b); b = y.s; // Either NaN? if (!a || !b) return new BigNumber(NaN); // Signs differ? if (a != b) { y.s = -b; return x.plus(y); } var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; if (!xe || !ye) { // Either Infinity? if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); // Either zero? if (!xc[0] || !yc[0]) { // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity ROUNDING_MODE == 3 ? -0 : 0); } } xe = bitFloor(xe); ye = bitFloor(ye); xc = xc.slice(); // Determine which is the bigger number. if (a = xe - ye) { if (xLTy = a < 0) { a = -a; t = xc; } else { ye = xe; t = yc; } t.reverse(); // Prepend zeros to equalise exponents. for (b = a; b--; t.push(0)); t.reverse(); } else { // Exponents equal. Check digit by digit. j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; for (a = b = 0; b < j; b++) { if (xc[b] != yc[b]) { xLTy = xc[b] < yc[b]; break; } } } // x < y? Point xc to the array of the bigger number. if (xLTy) { t = xc; xc = yc; yc = t; y.s = -y.s; } b = (j = yc.length) - (i = xc.length); // Append zeros to xc if shorter. // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. if (b > 0) for (; b--; xc[i++] = 0); b = BASE - 1; // Subtract yc from xc. for (; j > a;) { if (xc[--j] < yc[j]) { for (i = j; i && !xc[--i]; xc[i] = b); --xc[i]; xc[j] += BASE; } xc[j] -= yc[j]; } // Remove leading zeros and adjust exponent accordingly. for (; xc[0] == 0; xc.splice(0, 1), --ye); // Zero? if (!xc[0]) { // Following IEEE 754 (2008) 6.3, // n - n = +0 but n - n = -0 when rounding towards -Infinity. y.s = ROUNDING_MODE == 3 ? -1 : 1; y.c = [y.e = 0]; return y; } // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity // for finite x and y. return normalise(y, xc, ye); }; /* * n % 0 = N * n % N = N * n % I = n * 0 % n = 0 * -0 % n = -0 * 0 % 0 = N * 0 % N = N * 0 % I = 0 * N % n = N * N % 0 = N * N % N = N * N % I = N * I % n = N * I % 0 = N * I % N = N * I % I = N * * Return a new BigNumber whose value is the value of this BigNumber modulo the value of * BigNumber(y, b). The result depends on the value of MODULO_MODE. */ P.modulo = P.mod = function (y, b) { var q, s, x = this; y = new BigNumber(y, b); // Return NaN if x is Infinity or NaN, or y is NaN or zero. if (!x.c || !y.s || y.c && !y.c[0]) { return new BigNumber(NaN); // Return x if y is Infinity or x is zero. } else if (!y.c || x.c && !x.c[0]) { return new BigNumber(x); } if (MODULO_MODE == 9) { // Euclidian division: q = sign(y) * floor(x / abs(y)) // r = x - qy where 0 <= r < abs(y) s = y.s; y.s = 1; q = div(x, y, 0, 3); y.s = s; q.s *= s; } else { q = div(x, y, 0, MODULO_MODE); } y = x.minus(q.times(y)); // To match JavaScript %, ensure sign of zero is sign of dividend. if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; return y; }; /* * n * 0 = 0 * n * N = N * n * I = I * 0 * n = 0 * 0 * 0 = 0 * 0 * N = N * 0 * I = N * N * n = N * N * 0 = N * N * N = N * N * I = N * I * n = I * I * 0 = N * I * N = N * I * I = I * * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value * of BigNumber(y, b). */ P.multipliedBy = P.times = function (y, b) { var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = (y = new BigNumber(y, b)).c; // Either NaN, ±Infinity or ±0? if (!xc || !yc || !xc[0] || !yc[0]) { // Return NaN if either is NaN, or one is 0 and the other is Infinity. if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { y.c = y.e = y.s = null; } else { y.s *= x.s; // Return ±Infinity if either is ±Infinity. if (!xc || !yc) { y.c = y.e = null; // Return ±0 if either is ±0. } else { y.c = [0]; y.e = 0; } } return y; } e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); y.s *= x.s; xcL = xc.length; ycL = yc.length; // Ensure xc points to longer array and xcL to its length. if (xcL < ycL) { zc = xc; xc = yc; yc = zc; i = xcL; xcL = ycL; ycL = i; } // Initialise the result array with zeros. for (i = xcL + ycL, zc = []; i--; zc.push(0)); base = BASE; sqrtBase = SQRT_BASE; for (i = ycL; --i >= 0;) { c = 0; ylo = yc[i] % sqrtBase; yhi = yc[i] / sqrtBase | 0; for (k = xcL, j = i + k; j > i;) { xlo = xc[--k] % sqrtBase; xhi = xc[k] / sqrtBase | 0; m = yhi * xlo + xhi * ylo; xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; zc[j--] = xlo % base; } zc[j] = c; } if (c) { ++e; } else { zc.splice(0, 1); } return normalise(y, zc, e); }; /* * Return a new BigNumber whose value is the value of this BigNumber negated, * i.e. multiplied by -1. */ P.negated = function () { var x = new BigNumber(this); x.s = -x.s || null; return x; }; /* * n + 0 = n * n + N = N * n + I = I * 0 + n = n * 0 + 0 = 0 * 0 + N = N * 0 + I = I * N + n = N * N + 0 = N * N + N = N * N + I = N * I + n = I * I + 0 = I * I + N = N * I + I = I * * Return a new BigNumber whose value is the value of this BigNumber plus the value of * BigNumber(y, b). */ P.plus = function (y, b) { var t, x = this, a = x.s; y = new BigNumber(y, b); b = y.s; // Either NaN? if (!a || !b) return new BigNumber(NaN); // Signs differ? if (a != b) { y.s = -b; return x.minus(y); } var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; if (!xe || !ye) { // Return ±Infinity if either ±Infinity. if (!xc || !yc) return new BigNumber(a / 0); // Either zero? // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); } xe = bitFloor(xe); ye = bitFloor(ye); xc = xc.slice(); // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. if (a = xe - ye) { if (a > 0) { ye = xe; t = yc; } else { a = -a; t = xc; } t.reverse(); for (; a--; t.push(0)); t.reverse(); } a = xc.length; b = yc.length; // Point xc to the longer array, and b to the shorter length. if (a - b < 0) { t = yc; yc = xc; xc = t; b = a; } // Only start adding at yc.length - 1 as the further digits of xc can be ignored. for (a = 0; b;) { a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; } if (a) { xc = [a].concat(xc); ++ye; } // No need to check for zero, as +x + +y != 0 && -x + -y != 0 // ye = MAX_EXP + 1 possible return normalise(y, xc, ye); }; /* * If sd is undefined or null or true or false, return the number of significant digits of * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. * If sd is true include integer-part trailing zeros in the count. * * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or * ROUNDING_MODE if rm is omitted. * * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. * boolean: whether to count integer-part trailing zeros: true or false. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' */ P.precision = P.sd = function (sd, rm) { var c, n, v, x = this; if (sd != null && sd !== !!sd) { intCheck(sd, 1, MAX); if (rm == null) rm = ROUNDING_MODE; else intCheck(rm, 0, 8); return round(new BigNumber(x), sd, rm); } if (!(c = x.c)) return null; v = c.length - 1; n = v * LOG_BASE + 1; if (v = c[v]) { // Subtract the number of trailing zeros of the last element. for (; v % 10 == 0; v /= 10, n--); // Add the number of digits of the first element. for (v = c[0]; v >= 10; v /= 10, n++); } if (sd && x.e + 1 > n) n = x.e + 1; return n; }; /* * Return a new BigNumber whose value is the value of this BigNumber shifted by k places * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. * * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' */ P.shiftedBy = function (k) { intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); return this.times('1e' + k); }; /* * sqrt(-n) = N * sqrt(N) = N * sqrt(-I) = N * sqrt(I) = I * sqrt(0) = 0 * sqrt(-0) = -0 * * Return a new BigNumber whose value is the square root of the value of this BigNumber, * rounded according to DECIMAL_PLACES and ROUNDING_MODE. */ P.squareRoot = P.sqrt = function () { var m, n, r, rep, t, x = this, c = x.c, s = x.s, e = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber('0.5'); // Negative/NaN/Infinity/zero? if (s !== 1 || !c || !c[0]) { return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); } // Initial estimate. s = Math.sqrt(+valueOf(x)); // Math.sqrt underflow/overflow? // Pass x to Math.sqrt as integer, then adjust the exponent of the result. if (s == 0 || s == 1 / 0) { n = coeffToString(c); if ((n.length + e) % 2 == 0) n += '0'; s = Math.sqrt(+n); e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); if (s == 1 / 0) { n = '5e' + e; } else { n = s.toExponential(); n = n.slice(0, n.indexOf('e') + 1) + e; } r = new BigNumber(n); } else { r = new BigNumber(s + ''); } // Check for zero. // r could be zero if MIN_EXP is changed after the this value was created. // This would cause a division by zero (x/t) and hence Infinity below, which would cause // coeffToString to throw. if (r.c[0]) { e = r.e; s = e + dp; if (s < 3) s = 0; // Newton-Raphson iteration. for (; ;) { t = r; r = half.times(t.plus(div(x, t, dp, 1))); if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { // The exponent of r may here be one less than the final result exponent, // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits // are indexed correctly. if (r.e < e) --s; n = n.slice(s - 3, s + 1); // The 4th rounding digit may be in error by -1 so if the 4 rounding digits // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the // iteration. if (n == '9999' || !rep && n == '4999') { // On the first iteration only, check to see if rounding up gives the // exact result as the nines may infinitely repeat. if (!rep) { round(t, t.e + DECIMAL_PLACES + 2, 0); if (t.times(t).eq(x)) { r = t; break; } } dp += 4; s += 4; rep = 1; } else { // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact // result. If not, then there are further digits and m will be truthy. if (!+n || !+n.slice(1) && n.charAt(0) == '5') { // Truncate to the first rounding digit. round(r, r.e + DECIMAL_PLACES + 2, 1); m = !r.times(r).eq(x); } break; } } } } return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); }; /* * Return a string representing the value of this BigNumber in exponential notation and * rounded using ROUNDING_MODE to dp fixed decimal places. * * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' */ P.toExponential = function (dp, rm) { if (dp != null) { intCheck(dp, 0, MAX); dp++; } return format(this, dp, rm, 1); }; /* * Return a string representing the value of this BigNumber in fixed-point notation rounding * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. * * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', * but e.g. (-0.00001).toFixed(0) is '-0'. * * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' */ P.toFixed = function (dp, rm) { if (dp != null) { intCheck(dp, 0, MAX); dp = dp + this.e + 1; } return format(this, dp, rm); }; /* * Return a string representing the value of this BigNumber in fixed-point notation rounded * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties * of the format or FORMAT object (see BigNumber.set). * * The formatting object may contain some or all of the properties shown below. * * FORMAT = { * prefix: '', * groupSize: 3, * secondaryGroupSize: 0, * groupSeparator: ',', * decimalSeparator: '.', * fractionGroupSize: 0, * fractionGroupSeparator: '\xA0', // non-breaking space * suffix: '' * }; * * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * [format] {object} Formatting options. See FORMAT pbject above. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' * '[BigNumber Error] Argument not an object: {format}' */ P.toFormat = function (dp, rm, format) { var str, x = this; if (format == null) { if (dp != null && rm && typeof rm == 'object') { format = rm; rm = null; } else if (dp && typeof dp == 'object') { format = dp; dp = rm = null; } else { format = FORMAT; } } else if (typeof format != 'object') { throw Error (bignumberError + 'Argument not an object: ' + format); } str = x.toFixed(dp, rm); if (x.c) { var i, arr = str.split('.'), g1 = +format.groupSize, g2 = +format.secondaryGroupSize, groupSeparator = format.groupSeparator || '', intPart = arr[0], fractionPart = arr[1], isNeg = x.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; if (g2) { i = g1; g1 = g2; g2 = i; len -= i; } if (g1 > 0 && len > 0) { i = len % g1 || g1; intPart = intDigits.substr(0, i); for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); if (isNeg) intPart = '-' + intPart; } str = fractionPart ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), '$&' + (format.fractionGroupSeparator || '')) : fractionPart) : intPart; } return (format.prefix || '') + str + (format.suffix || ''); }; /* * Return an array of two BigNumbers representing the value of this BigNumber as a simple * fraction with an integer numerator and an integer denominator. * The denominator will be a positive non-zero value less than or equal to the specified * maximum denominator. If a maximum denominator is not specified, the denominator will be * the lowest value necessary to represent the number exactly. * * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. * * '[BigNumber Error] Argument {not an integer|out of range} : {md}' */ P.toFraction = function (md) { var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, x = this, xc = x.c; if (md != null) { n = new BigNumber(md); // Throw if md is less than one or is not an integer, unless it is Infinity. if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { throw Error (bignumberError + 'Argument ' + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); } } if (!xc) return new BigNumber(x); d = new BigNumber(ONE); n1 = d0 = new BigNumber(ONE); d1 = n0 = new BigNumber(ONE); s = coeffToString(xc); // Determine initial denominator. // d is a power of 10 and the minimum max denominator that specifies the value exactly. e = d.e = s.length - x.e - 1; d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; exp = MAX_EXP; MAX_EXP = 1 / 0; n = new BigNumber(s); // n0 = d1 = 0 n0.c[0] = 0; for (; ;) { q = div(n, d, 0, 1); d2 = d0.plus(q.times(d1)); if (d2.comparedTo(md) == 1) break; d0 = d1; d1 = d2; n1 = n0.plus(q.times(d2 = n1)); n0 = d2; d = n.minus(q.times(d2 = d)); n = d2; } d2 = div(md.minus(d0), d1, 0, 1); n0 = n0.plus(d2.times(n1)); d0 = d0.plus(d2.times(d1)); n0.s = n1.s = x.s; e = e * 2; // Determine which fraction is closer to x, n0/d0 or n1/d1 r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; MAX_EXP = exp; return r; }; /* * Return the value of this BigNumber converted to a number primitive. */ P.toNumber = function () { return +valueOf(this); }; /* * Return a string representing the value of this BigNumber rounded to sd significant digits * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits * necessary to represent the integer part of the value in fixed-point notation, then use * exponential notation. * * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' */ P.toPrecision = function (sd, rm) { if (sd != null) intCheck(sd, 1, MAX); return format(this, sd, rm, 2); }; /* * Return a string representing the value of this BigNumber in base b, or base 10 if b is * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than * TO_EXP_NEG, return exponential notation. * * [b] {number} Integer, 2 to ALPHABET.length inclusive. * * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' */ P.toString = function (b) { var str, n = this, s = n.s, e = n.e; // Infinity or NaN? if (e === null) { if (s) { str = 'Infinity'; if (s < 0) str = '-' + str; } else { str = 'NaN'; } } else { if (b == null) { str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(coeffToString(n.c), e) : toFixedPoint(coeffToString(n.c), e, '0'); } else if (b === 10 && alphabetHasNormalDecimalDigits) { n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); str = toFixedPoint(coeffToString(n.c), n.e, '0'); } else { intCheck(b, 2, ALPHABET.length, 'Base'); str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); } if (s < 0 && n.c[0]) str = '-' + str; } return str; }; /* * Return as toString, but do not accept a base argument, and include the minus sign for * negative zero. */ P.valueOf = P.toJSON = function () { return valueOf(this); }; P._isBigNumber = true; if (configObject != null) BigNumber.set(configObject); return BigNumber; } // PRIVATE HELPER FUNCTIONS // These functions don't need access to variables, // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. function bitFloor(n) { var i = n | 0; return n > 0 || n === i ? i : i - 1; } // Return a coefficient array as a string of base 10 digits. function coeffToString(a) { var s, z, i = 1, j = a.length, r = a[0] + ''; for (; i < j;) { s = a[i++] + ''; z = LOG_BASE - s.length; for (; z--; s = '0' + s); r += s; } // Determine trailing zeros. for (j = r.length; r.charCodeAt(--j) === 48;); return r.slice(0, j + 1 || 1); } // Compare the value of BigNumbers x and y. function compare(x, y) { var a, b, xc = x.c, yc = y.c, i = x.s, j = y.s, k = x.e, l = y.e; // Either NaN? if (!i || !j) return null; a = xc && !xc[0]; b = yc && !yc[0]; // Either zero? if (a || b) return a ? b ? 0 : -j : i; // Signs differ? if (i != j) return i; a = i < 0; b = k == l; // Either Infinity? if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; // Compare exponents. if (!b) return k > l ^ a ? 1 : -1; j = (k = xc.length) < (l = yc.length) ? k : l; // Compare digit by digit. for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; // Compare lengths. return k == l ? 0 : k > l ^ a ? 1 : -1; } /* * Check that n is a primitive number, an integer, and in range, otherwise throw. */ function intCheck(n, min, max, name) { if (n < min || n > max || n !== mathfloor(n)) { throw Error (bignumberError + (name || 'Argument') + (typeof n == 'number' ? n < min || n > max ? ' out of range: ' : ' not an integer: ' : ' not a primitive number: ') + String(n)); } } // Assumes finite n. function isOdd(n) { var k = n.c.length - 1; return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; } function toExponential(str, e) { return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + (e < 0 ? 'e' : 'e+') + e; } function toFixedPoint(str, e, z) { var len, zs; // Negative exponent? if (e < 0) { // Prepend zeros. for (zs = z + '.'; ++e; zs += z); str = zs + str; // Positive exponent } else { len = str.length; // Append zeros. if (++e > len) { for (zs = z, e -= len; --e; zs += z); str += zs; } else if (e < len) { str = str.slice(0, e) + '.' + str.slice(e); } } return str; } // EXPORT BigNumber = clone(); BigNumber['default'] = BigNumber.BigNumber = BigNumber; // AMD. if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return BigNumber; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); // Node.js and other environments that support module.exports. } else {} })(this); /***/ }), /***/ 3550: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /* module decorator */ module = __webpack_require__.nmd(module); (function (module, exports) { 'use strict'; // Utils function assert (val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } // Could use `inherits` module, but don't want to move from single file // architecture yet. function inherits (ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } // BN function BN (number, base, endian) { if (BN.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; // Reduction context this.red = null; if (number !== null) { if (base === 'le' || base === 'be') { endian = base; base = 10; } this._init(number || 0, base || 10, endian || 'be'); } } if (typeof module === 'object') { module.exports = BN; } else { exports.BN = BN; } BN.BN = BN; BN.wordSize = 26; var Buffer; try { if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { Buffer = window.Buffer; } else { Buffer = (__webpack_require__(6601).Buffer); } } catch (e) { } BN.isBN = function isBN (num) { if (num instanceof BN) { return true; } return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; BN.max = function max (left, right) { if (left.cmp(right) > 0) return left; return right; }; BN.min = function min (left, right) { if (left.cmp(right) < 0) return left; return right; }; BN.prototype._init = function init (number, base, endian) { if (typeof number === 'number') { return this._initNumber(number, base, endian); } if (typeof number === 'object') { return this._initArray(number, base, endian); } if (base === 'hex') { base = 16; } assert(base === (base | 0) && base >= 2 && base <= 36); number = number.toString().replace(/\s+/g, ''); var start = 0; if (number[0] === '-') { start++; this.negative = 1; } if (start < number.length) { if (base === 16) { this._parseHex(number, start, endian); } else { this._parseBase(number, base, start); if (endian === 'le') { this._initArray(this.toArray(), base, endian); } } } }; BN.prototype._initNumber = function _initNumber (number, base, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 0x4000000) { this.words = [ number & 0x3ffffff ]; this.length = 1; } else if (number < 0x10000000000000) { this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff ]; this.length = 2; } else { assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff, 1 ]; this.length = 3; } if (endian !== 'le') return; // Reverse the bytes this._initArray(this.toArray(), base, endian); }; BN.prototype._initArray = function _initArray (number, base, endian) { // Perhaps a Uint8Array assert(typeof number.length === 'number'); if (number.length <= 0) { this.words = [ 0 ]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; var off = 0; if (endian === 'be') { for (i = number.length - 1, j = 0; i >= 0; i -= 3) { w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } else if (endian === 'le') { for (i = 0, j = 0; i < number.length; i += 3) { w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } return this.strip(); }; function parseHex4Bits (string, index) { var c = string.charCodeAt(index); // 'A' - 'F' if (c >= 65 && c <= 70) { return c - 55; // 'a' - 'f' } else if (c >= 97 && c <= 102) { return c - 87; // '0' - '9' } else { return (c - 48) & 0xf; } } function parseHexByte (string, lowerBound, index) { var r = parseHex4Bits(string, index); if (index - 1 >= lowerBound) { r |= parseHex4Bits(string, index - 1) << 4; } return r; } BN.prototype._parseHex = function _parseHex (number, start, endian) { // Create possibly bigger array to ensure that it fits the number this.length = Math.ceil((number.length - start) / 6); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } // 24-bits chunks var off = 0; var j = 0; var w; if (endian === 'be') { for (i = number.length - 1; i >= start; i -= 2) { w = parseHexByte(number, start, i) << off; this.words[j] |= w & 0x3ffffff; if (off >= 18) { off -= 18; j += 1; this.words[j] |= w >>> 26; } else { off += 8; } } } else { var parseLength = number.length - start; for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { w = parseHexByte(number, start, i) << off; this.words[j] |= w & 0x3ffffff; if (off >= 18) { off -= 18; j += 1; this.words[j] |= w >>> 26; } else { off += 8; } } } this.strip(); }; function parseBase (str, start, end, mul) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r *= mul; // 'a' if (c >= 49) { r += c - 49 + 0xa; // 'A' } else if (c >= 17) { r += c - 17 + 0xa; // '0' - '9' } else { r += c; } } return r; } BN.prototype._parseBase = function _parseBase (number, base, start) { // Initialize as zero this.words = [ 0 ]; this.length = 1; // Find length of limb in base for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { limbLen++; } limbLen--; limbPow = (limbPow / base) | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i = start; i < end; i += limbLen) { word = parseBase(number, i, i + limbLen, base); this.imuln(limbPow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i, number.length, base); for (i = 0; i < mod; i++) { pow *= base; } this.imuln(pow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } this.strip(); }; BN.prototype.copy = function copy (dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { dest.words[i] = this.words[i]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; BN.prototype.clone = function clone () { var r = new BN(null); this.copy(r); return r; }; BN.prototype._expand = function _expand (size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; // Remove leading `0` from `this` BN.prototype.strip = function strip () { while (this.length > 1 && this.words[this.length - 1] === 0) { this.length--; } return this._normSign(); }; BN.prototype._normSign = function _normSign () { // -0 = 0 if (this.length === 1 && this.words[0] === 0) { this.negative = 0; } return this; }; BN.prototype.inspect = function inspect () { return (this.red ? ''; }; /* var zeros = []; var groupSizes = []; var groupBases = []; var s = ''; var i = -1; while (++i < BN.wordSize) { zeros[i] = s; s += '0'; } groupSizes[0] = 0; groupSizes[1] = 0; groupBases[0] = 0; groupBases[1] = 0; var base = 2 - 1; while (++base < 36 + 1) { var groupSize = 0; var groupBase = 1; while (groupBase < (1 << BN.wordSize) / base) { groupBase *= base; groupSize += 1; } groupSizes[base] = groupSize; groupBases[base] = groupBase; } */ var zeros = [ '', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000' ]; var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]; var groupBases = [ 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 ]; BN.prototype.toString = function toString (base, padding) { base = base || 10; padding = padding | 0 || 1; var out; if (base === 16 || base === 'hex') { out = ''; var off = 0; var carry = 0; for (var i = 0; i < this.length; i++) { var w = this.words[i]; var word = (((w << off) | carry) & 0xffffff).toString(16); carry = (w >>> (24 - off)) & 0xffffff; if (carry !== 0 || i !== this.length - 1) { out = zeros[6 - word.length] + word + out; } else { out = word + out; } off += 2; if (off >= 26) { off -= 26; i--; } } if (carry !== 0) { out = carry.toString(16) + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } if (base === (base | 0) && base >= 2 && base <= 36) { // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); var groupBase = groupBases[base]; out = ''; var c = this.clone(); c.negative = 0; while (!c.isZero()) { var r = c.modn(groupBase).toString(base); c = c.idivn(groupBase); if (!c.isZero()) { out = zeros[groupSize - r.length] + r + out; } else { out = r + out; } } if (this.isZero()) { out = '0' + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } assert(false, 'Base should be between 2 and 36'); }; BN.prototype.toNumber = function toNumber () { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 0x4000000; } else if (this.length === 3 && this.words[2] === 0x01) { // NOTE: at this stage it is known that the top bit is set ret += 0x10000000000000 + (this.words[1] * 0x4000000); } else if (this.length > 2) { assert(false, 'Number can only safely store up to 53 bits'); } return (this.negative !== 0) ? -ret : ret; }; BN.prototype.toJSON = function toJSON () { return this.toString(16); }; BN.prototype.toBuffer = function toBuffer (endian, length) { assert(typeof Buffer !== 'undefined'); return this.toArrayLike(Buffer, endian, length); }; BN.prototype.toArray = function toArray (endian, length) { return this.toArrayLike(Array, endian, length); }; BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { var byteLength = this.byteLength(); var reqLength = length || Math.max(1, byteLength); assert(byteLength <= reqLength, 'byte array longer than desired length'); assert(reqLength > 0, 'Requested array length <= 0'); this.strip(); var littleEndian = endian === 'le'; var res = new ArrayType(reqLength); var b, i; var q = this.clone(); if (!littleEndian) { // Assume big-endian for (i = 0; i < reqLength - byteLength; i++) { res[i] = 0; } for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[reqLength - i - 1] = b; } } else { for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[i] = b; } for (; i < reqLength; i++) { res[i] = 0; } } return res; }; if (Math.clz32) { BN.prototype._countBits = function _countBits (w) { return 32 - Math.clz32(w); }; } else { BN.prototype._countBits = function _countBits (w) { var t = w; var r = 0; if (t >= 0x1000) { r += 13; t >>>= 13; } if (t >= 0x40) { r += 7; t >>>= 7; } if (t >= 0x8) { r += 4; t >>>= 4; } if (t >= 0x02) { r += 2; t >>>= 2; } return r + t; }; } BN.prototype._zeroBits = function _zeroBits (w) { // Short-cut if (w === 0) return 26; var t = w; var r = 0; if ((t & 0x1fff) === 0) { r += 13; t >>>= 13; } if ((t & 0x7f) === 0) { r += 7; t >>>= 7; } if ((t & 0xf) === 0) { r += 4; t >>>= 4; } if ((t & 0x3) === 0) { r += 2; t >>>= 2; } if ((t & 0x1) === 0) { r++; } return r; }; // Return number of used bits in a BN BN.prototype.bitLength = function bitLength () { var w = this.words[this.length - 1]; var hi = this._countBits(w); return (this.length - 1) * 26 + hi; }; function toBitArray (num) { var w = new Array(num.bitLength()); for (var bit = 0; bit < w.length; bit++) { var off = (bit / 26) | 0; var wbit = bit % 26; w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; } return w; } // Number of trailing zero bits BN.prototype.zeroBits = function zeroBits () { if (this.isZero()) return 0; var r = 0; for (var i = 0; i < this.length; i++) { var b = this._zeroBits(this.words[i]); r += b; if (b !== 26) break; } return r; }; BN.prototype.byteLength = function byteLength () { return Math.ceil(this.bitLength() / 8); }; BN.prototype.toTwos = function toTwos (width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN.prototype.fromTwos = function fromTwos (width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN.prototype.isNeg = function isNeg () { return this.negative !== 0; }; // Return negative clone of `this` BN.prototype.neg = function neg () { return this.clone().ineg(); }; BN.prototype.ineg = function ineg () { if (!this.isZero()) { this.negative ^= 1; } return this; }; // Or `num` with `this` in-place BN.prototype.iuor = function iuor (num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i = 0; i < num.length; i++) { this.words[i] = this.words[i] | num.words[i]; } return this.strip(); }; BN.prototype.ior = function ior (num) { assert((this.negative | num.negative) === 0); return this.iuor(num); }; // Or `num` with `this` BN.prototype.or = function or (num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN.prototype.uor = function uor (num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; // And `num` with `this` in-place BN.prototype.iuand = function iuand (num) { // b = min-length(num, this) var b; if (this.length > num.length) { b = num; } else { b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = this.words[i] & num.words[i]; } this.length = b.length; return this.strip(); }; BN.prototype.iand = function iand (num) { assert((this.negative | num.negative) === 0); return this.iuand(num); }; // And `num` with `this` BN.prototype.and = function and (num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN.prototype.uand = function uand (num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; // Xor `num` with `this` in-place BN.prototype.iuxor = function iuxor (num) { // a.length > b.length var a; var b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = a.words[i] ^ b.words[i]; } if (this !== a) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = a.length; return this.strip(); }; BN.prototype.ixor = function ixor (num) { assert((this.negative | num.negative) === 0); return this.iuxor(num); }; // Xor `num` with `this` BN.prototype.xor = function xor (num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN.prototype.uxor = function uxor (num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; // Not ``this`` with ``width`` bitwidth BN.prototype.inotn = function inotn (width) { assert(typeof width === 'number' && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; // Extend the buffer with leading zeroes this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } // Handle complete words for (var i = 0; i < bytesNeeded; i++) { this.words[i] = ~this.words[i] & 0x3ffffff; } // Handle the residue if (bitsLeft > 0) { this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); } // And remove leading zeroes return this.strip(); }; BN.prototype.notn = function notn (width) { return this.clone().inotn(width); }; // Set `bit` of `this` BN.prototype.setn = function setn (bit, val) { assert(typeof bit === 'number' && bit >= 0); var off = (bit / 26) | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | (1 << wbit); } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this.strip(); }; // Add `num` to `this` in-place BN.prototype.iadd = function iadd (num) { var r; // negative + positive if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r = this.isub(num); this.negative ^= 1; return this._normSign(); // positive + negative } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r = this.isub(num); num.negative = 1; return r._normSign(); } // a.length > b.length var a, b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) + (b.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } this.length = a.length; if (carry !== 0) { this.words[this.length] = carry; this.length++; // Copy the rest of the words } else if (a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } return this; }; // Add `num` to `this` BN.prototype.add = function add (num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; // Subtract `num` from `this` in-place BN.prototype.isub = function isub (num) { // this - (-num) = this + num if (num.negative !== 0) { num.negative = 0; var r = this.iadd(num); num.negative = 1; return r._normSign(); // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } // At this point both numbers are positive var cmp = this.cmp(num); // Optimization - zeroify if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } // a > b var a, b; if (cmp > 0) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) - (b.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } // Copy rest of the words if (carry === 0 && i < a.length && a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = Math.max(this.length, i); if (a !== this) { this.negative = 1; } return this.strip(); }; // Subtract `num` from `this` BN.prototype.sub = function sub (num) { return this.clone().isub(num); }; function smallMulTo (self, num, out) { out.negative = num.negative ^ self.negative; var len = (self.length + num.length) | 0; out.length = len; len = (len - 1) | 0; // Peel one iteration (compiler can't do it, because of code complexity) var a = self.words[0] | 0; var b = num.words[0] | 0; var r = a * b; var lo = r & 0x3ffffff; var carry = (r / 0x4000000) | 0; out.words[0] = lo; for (var k = 1; k < len; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = carry >>> 26; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = (k - j) | 0; a = self.words[i] | 0; b = num.words[j] | 0; r = a * b + rword; ncarry += (r / 0x4000000) | 0; rword = r & 0x3ffffff; } out.words[k] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k] = carry | 0; } else { out.length--; } return out.strip(); } // TODO(indutny): it may be reasonable to omit it for users who don't need // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit // multiplication (like elliptic secp256k1). var comb10MulTo = function comb10MulTo (self, num, out) { var a = self.words; var b = num.words; var o = out.words; var c = 0; var lo; var mid; var hi; var a0 = a[0] | 0; var al0 = a0 & 0x1fff; var ah0 = a0 >>> 13; var a1 = a[1] | 0; var al1 = a1 & 0x1fff; var ah1 = a1 >>> 13; var a2 = a[2] | 0; var al2 = a2 & 0x1fff; var ah2 = a2 >>> 13; var a3 = a[3] | 0; var al3 = a3 & 0x1fff; var ah3 = a3 >>> 13; var a4 = a[4] | 0; var al4 = a4 & 0x1fff; var ah4 = a4 >>> 13; var a5 = a[5] | 0; var al5 = a5 & 0x1fff; var ah5 = a5 >>> 13; var a6 = a[6] | 0; var al6 = a6 & 0x1fff; var ah6 = a6 >>> 13; var a7 = a[7] | 0; var al7 = a7 & 0x1fff; var ah7 = a7 >>> 13; var a8 = a[8] | 0; var al8 = a8 & 0x1fff; var ah8 = a8 >>> 13; var a9 = a[9] | 0; var al9 = a9 & 0x1fff; var ah9 = a9 >>> 13; var b0 = b[0] | 0; var bl0 = b0 & 0x1fff; var bh0 = b0 >>> 13; var b1 = b[1] | 0; var bl1 = b1 & 0x1fff; var bh1 = b1 >>> 13; var b2 = b[2] | 0; var bl2 = b2 & 0x1fff; var bh2 = b2 >>> 13; var b3 = b[3] | 0; var bl3 = b3 & 0x1fff; var bh3 = b3 >>> 13; var b4 = b[4] | 0; var bl4 = b4 & 0x1fff; var bh4 = b4 >>> 13; var b5 = b[5] | 0; var bl5 = b5 & 0x1fff; var bh5 = b5 >>> 13; var b6 = b[6] | 0; var bl6 = b6 & 0x1fff; var bh6 = b6 >>> 13; var b7 = b[7] | 0; var bl7 = b7 & 0x1fff; var bh7 = b7 >>> 13; var b8 = b[8] | 0; var bl8 = b8 & 0x1fff; var bh8 = b8 >>> 13; var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ lo = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = (mid + Math.imul(ah0, bl0)) | 0; hi = Math.imul(ah0, bh0); var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; w0 &= 0x3ffffff; /* k = 1 */ lo = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = (mid + Math.imul(ah1, bl0)) | 0; hi = Math.imul(ah1, bh0); lo = (lo + Math.imul(al0, bl1)) | 0; mid = (mid + Math.imul(al0, bh1)) | 0; mid = (mid + Math.imul(ah0, bl1)) | 0; hi = (hi + Math.imul(ah0, bh1)) | 0; var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; w1 &= 0x3ffffff; /* k = 2 */ lo = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = (mid + Math.imul(ah2, bl0)) | 0; hi = Math.imul(ah2, bh0); lo = (lo + Math.imul(al1, bl1)) | 0; mid = (mid + Math.imul(al1, bh1)) | 0; mid = (mid + Math.imul(ah1, bl1)) | 0; hi = (hi + Math.imul(ah1, bh1)) | 0; lo = (lo + Math.imul(al0, bl2)) | 0; mid = (mid + Math.imul(al0, bh2)) | 0; mid = (mid + Math.imul(ah0, bl2)) | 0; hi = (hi + Math.imul(ah0, bh2)) | 0; var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; w2 &= 0x3ffffff; /* k = 3 */ lo = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = (mid + Math.imul(ah3, bl0)) | 0; hi = Math.imul(ah3, bh0); lo = (lo + Math.imul(al2, bl1)) | 0; mid = (mid + Math.imul(al2, bh1)) | 0; mid = (mid + Math.imul(ah2, bl1)) | 0; hi = (hi + Math.imul(ah2, bh1)) | 0; lo = (lo + Math.imul(al1, bl2)) | 0; mid = (mid + Math.imul(al1, bh2)) | 0; mid = (mid + Math.imul(ah1, bl2)) | 0; hi = (hi + Math.imul(ah1, bh2)) | 0; lo = (lo + Math.imul(al0, bl3)) | 0; mid = (mid + Math.imul(al0, bh3)) | 0; mid = (mid + Math.imul(ah0, bl3)) | 0; hi = (hi + Math.imul(ah0, bh3)) | 0; var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; w3 &= 0x3ffffff; /* k = 4 */ lo = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = (mid + Math.imul(ah4, bl0)) | 0; hi = Math.imul(ah4, bh0); lo = (lo + Math.imul(al3, bl1)) | 0; mid = (mid + Math.imul(al3, bh1)) | 0; mid = (mid + Math.imul(ah3, bl1)) | 0; hi = (hi + Math.imul(ah3, bh1)) | 0; lo = (lo + Math.imul(al2, bl2)) | 0; mid = (mid + Math.imul(al2, bh2)) | 0; mid = (mid + Math.imul(ah2, bl2)) | 0; hi = (hi + Math.imul(ah2, bh2)) | 0; lo = (lo + Math.imul(al1, bl3)) | 0; mid = (mid + Math.imul(al1, bh3)) | 0; mid = (mid + Math.imul(ah1, bl3)) | 0; hi = (hi + Math.imul(ah1, bh3)) | 0; lo = (lo + Math.imul(al0, bl4)) | 0; mid = (mid + Math.imul(al0, bh4)) | 0; mid = (mid + Math.imul(ah0, bl4)) | 0; hi = (hi + Math.imul(ah0, bh4)) | 0; var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; w4 &= 0x3ffffff; /* k = 5 */ lo = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = (mid + Math.imul(ah5, bl0)) | 0; hi = Math.imul(ah5, bh0); lo = (lo + Math.imul(al4, bl1)) | 0; mid = (mid + Math.imul(al4, bh1)) | 0; mid = (mid + Math.imul(ah4, bl1)) | 0; hi = (hi + Math.imul(ah4, bh1)) | 0; lo = (lo + Math.imul(al3, bl2)) | 0; mid = (mid + Math.imul(al3, bh2)) | 0; mid = (mid + Math.imul(ah3, bl2)) | 0; hi = (hi + Math.imul(ah3, bh2)) | 0; lo = (lo + Math.imul(al2, bl3)) | 0; mid = (mid + Math.imul(al2, bh3)) | 0; mid = (mid + Math.imul(ah2, bl3)) | 0; hi = (hi + Math.imul(ah2, bh3)) | 0; lo = (lo + Math.imul(al1, bl4)) | 0; mid = (mid + Math.imul(al1, bh4)) | 0; mid = (mid + Math.imul(ah1, bl4)) | 0; hi = (hi + Math.imul(ah1, bh4)) | 0; lo = (lo + Math.imul(al0, bl5)) | 0; mid = (mid + Math.imul(al0, bh5)) | 0; mid = (mid + Math.imul(ah0, bl5)) | 0; hi = (hi + Math.imul(ah0, bh5)) | 0; var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; w5 &= 0x3ffffff; /* k = 6 */ lo = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = (mid + Math.imul(ah6, bl0)) | 0; hi = Math.imul(ah6, bh0); lo = (lo + Math.imul(al5, bl1)) | 0; mid = (mid + Math.imul(al5, bh1)) | 0; mid = (mid + Math.imul(ah5, bl1)) | 0; hi = (hi + Math.imul(ah5, bh1)) | 0; lo = (lo + Math.imul(al4, bl2)) | 0; mid = (mid + Math.imul(al4, bh2)) | 0; mid = (mid + Math.imul(ah4, bl2)) | 0; hi = (hi + Math.imul(ah4, bh2)) | 0; lo = (lo + Math.imul(al3, bl3)) | 0; mid = (mid + Math.imul(al3, bh3)) | 0; mid = (mid + Math.imul(ah3, bl3)) | 0; hi = (hi + Math.imul(ah3, bh3)) | 0; lo = (lo + Math.imul(al2, bl4)) | 0; mid = (mid + Math.imul(al2, bh4)) | 0; mid = (mid + Math.imul(ah2, bl4)) | 0; hi = (hi + Math.imul(ah2, bh4)) | 0; lo = (lo + Math.imul(al1, bl5)) | 0; mid = (mid + Math.imul(al1, bh5)) | 0; mid = (mid + Math.imul(ah1, bl5)) | 0; hi = (hi + Math.imul(ah1, bh5)) | 0; lo = (lo + Math.imul(al0, bl6)) | 0; mid = (mid + Math.imul(al0, bh6)) | 0; mid = (mid + Math.imul(ah0, bl6)) | 0; hi = (hi + Math.imul(ah0, bh6)) | 0; var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; w6 &= 0x3ffffff; /* k = 7 */ lo = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = (mid + Math.imul(ah7, bl0)) | 0; hi = Math.imul(ah7, bh0); lo = (lo + Math.imul(al6, bl1)) | 0; mid = (mid + Math.imul(al6, bh1)) | 0; mid = (mid + Math.imul(ah6, bl1)) | 0; hi = (hi + Math.imul(ah6, bh1)) | 0; lo = (lo + Math.imul(al5, bl2)) | 0; mid = (mid + Math.imul(al5, bh2)) | 0; mid = (mid + Math.imul(ah5, bl2)) | 0; hi = (hi + Math.imul(ah5, bh2)) | 0; lo = (lo + Math.imul(al4, bl3)) | 0; mid = (mid + Math.imul(al4, bh3)) | 0; mid = (mid + Math.imul(ah4, bl3)) | 0; hi = (hi + Math.imul(ah4, bh3)) | 0; lo = (lo + Math.imul(al3, bl4)) | 0; mid = (mid + Math.imul(al3, bh4)) | 0; mid = (mid + Math.imul(ah3, bl4)) | 0; hi = (hi + Math.imul(ah3, bh4)) | 0; lo = (lo + Math.imul(al2, bl5)) | 0; mid = (mid + Math.imul(al2, bh5)) | 0; mid = (mid + Math.imul(ah2, bl5)) | 0; hi = (hi + Math.imul(ah2, bh5)) | 0; lo = (lo + Math.imul(al1, bl6)) | 0; mid = (mid + Math.imul(al1, bh6)) | 0; mid = (mid + Math.imul(ah1, bl6)) | 0; hi = (hi + Math.imul(ah1, bh6)) | 0; lo = (lo + Math.imul(al0, bl7)) | 0; mid = (mid + Math.imul(al0, bh7)) | 0; mid = (mid + Math.imul(ah0, bl7)) | 0; hi = (hi + Math.imul(ah0, bh7)) | 0; var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; w7 &= 0x3ffffff; /* k = 8 */ lo = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = (mid + Math.imul(ah8, bl0)) | 0; hi = Math.imul(ah8, bh0); lo = (lo + Math.imul(al7, bl1)) | 0; mid = (mid + Math.imul(al7, bh1)) | 0; mid = (mid + Math.imul(ah7, bl1)) | 0; hi = (hi + Math.imul(ah7, bh1)) | 0; lo = (lo + Math.imul(al6, bl2)) | 0; mid = (mid + Math.imul(al6, bh2)) | 0; mid = (mid + Math.imul(ah6, bl2)) | 0; hi = (hi + Math.imul(ah6, bh2)) | 0; lo = (lo + Math.imul(al5, bl3)) | 0; mid = (mid + Math.imul(al5, bh3)) | 0; mid = (mid + Math.imul(ah5, bl3)) | 0; hi = (hi + Math.imul(ah5, bh3)) | 0; lo = (lo + Math.imul(al4, bl4)) | 0; mid = (mid + Math.imul(al4, bh4)) | 0; mid = (mid + Math.imul(ah4, bl4)) | 0; hi = (hi + Math.imul(ah4, bh4)) | 0; lo = (lo + Math.imul(al3, bl5)) | 0; mid = (mid + Math.imul(al3, bh5)) | 0; mid = (mid + Math.imul(ah3, bl5)) | 0; hi = (hi + Math.imul(ah3, bh5)) | 0; lo = (lo + Math.imul(al2, bl6)) | 0; mid = (mid + Math.imul(al2, bh6)) | 0; mid = (mid + Math.imul(ah2, bl6)) | 0; hi = (hi + Math.imul(ah2, bh6)) | 0; lo = (lo + Math.imul(al1, bl7)) | 0; mid = (mid + Math.imul(al1, bh7)) | 0; mid = (mid + Math.imul(ah1, bl7)) | 0; hi = (hi + Math.imul(ah1, bh7)) | 0; lo = (lo + Math.imul(al0, bl8)) | 0; mid = (mid + Math.imul(al0, bh8)) | 0; mid = (mid + Math.imul(ah0, bl8)) | 0; hi = (hi + Math.imul(ah0, bh8)) | 0; var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; w8 &= 0x3ffffff; /* k = 9 */ lo = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = (mid + Math.imul(ah9, bl0)) | 0; hi = Math.imul(ah9, bh0); lo = (lo + Math.imul(al8, bl1)) | 0; mid = (mid + Math.imul(al8, bh1)) | 0; mid = (mid + Math.imul(ah8, bl1)) | 0; hi = (hi + Math.imul(ah8, bh1)) | 0; lo = (lo + Math.imul(al7, bl2)) | 0; mid = (mid + Math.imul(al7, bh2)) | 0; mid = (mid + Math.imul(ah7, bl2)) | 0; hi = (hi + Math.imul(ah7, bh2)) | 0; lo = (lo + Math.imul(al6, bl3)) | 0; mid = (mid + Math.imul(al6, bh3)) | 0; mid = (mid + Math.imul(ah6, bl3)) | 0; hi = (hi + Math.imul(ah6, bh3)) | 0; lo = (lo + Math.imul(al5, bl4)) | 0; mid = (mid + Math.imul(al5, bh4)) | 0; mid = (mid + Math.imul(ah5, bl4)) | 0; hi = (hi + Math.imul(ah5, bh4)) | 0; lo = (lo + Math.imul(al4, bl5)) | 0; mid = (mid + Math.imul(al4, bh5)) | 0; mid = (mid + Math.imul(ah4, bl5)) | 0; hi = (hi + Math.imul(ah4, bh5)) | 0; lo = (lo + Math.imul(al3, bl6)) | 0; mid = (mid + Math.imul(al3, bh6)) | 0; mid = (mid + Math.imul(ah3, bl6)) | 0; hi = (hi + Math.imul(ah3, bh6)) | 0; lo = (lo + Math.imul(al2, bl7)) | 0; mid = (mid + Math.imul(al2, bh7)) | 0; mid = (mid + Math.imul(ah2, bl7)) | 0; hi = (hi + Math.imul(ah2, bh7)) | 0; lo = (lo + Math.imul(al1, bl8)) | 0; mid = (mid + Math.imul(al1, bh8)) | 0; mid = (mid + Math.imul(ah1, bl8)) | 0; hi = (hi + Math.imul(ah1, bh8)) | 0; lo = (lo + Math.imul(al0, bl9)) | 0; mid = (mid + Math.imul(al0, bh9)) | 0; mid = (mid + Math.imul(ah0, bl9)) | 0; hi = (hi + Math.imul(ah0, bh9)) | 0; var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; w9 &= 0x3ffffff; /* k = 10 */ lo = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = (mid + Math.imul(ah9, bl1)) | 0; hi = Math.imul(ah9, bh1); lo = (lo + Math.imul(al8, bl2)) | 0; mid = (mid + Math.imul(al8, bh2)) | 0; mid = (mid + Math.imul(ah8, bl2)) | 0; hi = (hi + Math.imul(ah8, bh2)) | 0; lo = (lo + Math.imul(al7, bl3)) | 0; mid = (mid + Math.imul(al7, bh3)) | 0; mid = (mid + Math.imul(ah7, bl3)) | 0; hi = (hi + Math.imul(ah7, bh3)) | 0; lo = (lo + Math.imul(al6, bl4)) | 0; mid = (mid + Math.imul(al6, bh4)) | 0; mid = (mid + Math.imul(ah6, bl4)) | 0; hi = (hi + Math.imul(ah6, bh4)) | 0; lo = (lo + Math.imul(al5, bl5)) | 0; mid = (mid + Math.imul(al5, bh5)) | 0; mid = (mid + Math.imul(ah5, bl5)) | 0; hi = (hi + Math.imul(ah5, bh5)) | 0; lo = (lo + Math.imul(al4, bl6)) | 0; mid = (mid + Math.imul(al4, bh6)) | 0; mid = (mid + Math.imul(ah4, bl6)) | 0; hi = (hi + Math.imul(ah4, bh6)) | 0; lo = (lo + Math.imul(al3, bl7)) | 0; mid = (mid + Math.imul(al3, bh7)) | 0; mid = (mid + Math.imul(ah3, bl7)) | 0; hi = (hi + Math.imul(ah3, bh7)) | 0; lo = (lo + Math.imul(al2, bl8)) | 0; mid = (mid + Math.imul(al2, bh8)) | 0; mid = (mid + Math.imul(ah2, bl8)) | 0; hi = (hi + Math.imul(ah2, bh8)) | 0; lo = (lo + Math.imul(al1, bl9)) | 0; mid = (mid + Math.imul(al1, bh9)) | 0; mid = (mid + Math.imul(ah1, bl9)) | 0; hi = (hi + Math.imul(ah1, bh9)) | 0; var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; w10 &= 0x3ffffff; /* k = 11 */ lo = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = (mid + Math.imul(ah9, bl2)) | 0; hi = Math.imul(ah9, bh2); lo = (lo + Math.imul(al8, bl3)) | 0; mid = (mid + Math.imul(al8, bh3)) | 0; mid = (mid + Math.imul(ah8, bl3)) | 0; hi = (hi + Math.imul(ah8, bh3)) | 0; lo = (lo + Math.imul(al7, bl4)) | 0; mid = (mid + Math.imul(al7, bh4)) | 0; mid = (mid + Math.imul(ah7, bl4)) | 0; hi = (hi + Math.imul(ah7, bh4)) | 0; lo = (lo + Math.imul(al6, bl5)) | 0; mid = (mid + Math.imul(al6, bh5)) | 0; mid = (mid + Math.imul(ah6, bl5)) | 0; hi = (hi + Math.imul(ah6, bh5)) | 0; lo = (lo + Math.imul(al5, bl6)) | 0; mid = (mid + Math.imul(al5, bh6)) | 0; mid = (mid + Math.imul(ah5, bl6)) | 0; hi = (hi + Math.imul(ah5, bh6)) | 0; lo = (lo + Math.imul(al4, bl7)) | 0; mid = (mid + Math.imul(al4, bh7)) | 0; mid = (mid + Math.imul(ah4, bl7)) | 0; hi = (hi + Math.imul(ah4, bh7)) | 0; lo = (lo + Math.imul(al3, bl8)) | 0; mid = (mid + Math.imul(al3, bh8)) | 0; mid = (mid + Math.imul(ah3, bl8)) | 0; hi = (hi + Math.imul(ah3, bh8)) | 0; lo = (lo + Math.imul(al2, bl9)) | 0; mid = (mid + Math.imul(al2, bh9)) | 0; mid = (mid + Math.imul(ah2, bl9)) | 0; hi = (hi + Math.imul(ah2, bh9)) | 0; var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; w11 &= 0x3ffffff; /* k = 12 */ lo = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = (mid + Math.imul(ah9, bl3)) | 0; hi = Math.imul(ah9, bh3); lo = (lo + Math.imul(al8, bl4)) | 0; mid = (mid + Math.imul(al8, bh4)) | 0; mid = (mid + Math.imul(ah8, bl4)) | 0; hi = (hi + Math.imul(ah8, bh4)) | 0; lo = (lo + Math.imul(al7, bl5)) | 0; mid = (mid + Math.imul(al7, bh5)) | 0; mid = (mid + Math.imul(ah7, bl5)) | 0; hi = (hi + Math.imul(ah7, bh5)) | 0; lo = (lo + Math.imul(al6, bl6)) | 0; mid = (mid + Math.imul(al6, bh6)) | 0; mid = (mid + Math.imul(ah6, bl6)) | 0; hi = (hi + Math.imul(ah6, bh6)) | 0; lo = (lo + Math.imul(al5, bl7)) | 0; mid = (mid + Math.imul(al5, bh7)) | 0; mid = (mid + Math.imul(ah5, bl7)) | 0; hi = (hi + Math.imul(ah5, bh7)) | 0; lo = (lo + Math.imul(al4, bl8)) | 0; mid = (mid + Math.imul(al4, bh8)) | 0; mid = (mid + Math.imul(ah4, bl8)) | 0; hi = (hi + Math.imul(ah4, bh8)) | 0; lo = (lo + Math.imul(al3, bl9)) | 0; mid = (mid + Math.imul(al3, bh9)) | 0; mid = (mid + Math.imul(ah3, bl9)) | 0; hi = (hi + Math.imul(ah3, bh9)) | 0; var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; w12 &= 0x3ffffff; /* k = 13 */ lo = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = (mid + Math.imul(ah9, bl4)) | 0; hi = Math.imul(ah9, bh4); lo = (lo + Math.imul(al8, bl5)) | 0; mid = (mid + Math.imul(al8, bh5)) | 0; mid = (mid + Math.imul(ah8, bl5)) | 0; hi = (hi + Math.imul(ah8, bh5)) | 0; lo = (lo + Math.imul(al7, bl6)) | 0; mid = (mid + Math.imul(al7, bh6)) | 0; mid = (mid + Math.imul(ah7, bl6)) | 0; hi = (hi + Math.imul(ah7, bh6)) | 0; lo = (lo + Math.imul(al6, bl7)) | 0; mid = (mid + Math.imul(al6, bh7)) | 0; mid = (mid + Math.imul(ah6, bl7)) | 0; hi = (hi + Math.imul(ah6, bh7)) | 0; lo = (lo + Math.imul(al5, bl8)) | 0; mid = (mid + Math.imul(al5, bh8)) | 0; mid = (mid + Math.imul(ah5, bl8)) | 0; hi = (hi + Math.imul(ah5, bh8)) | 0; lo = (lo + Math.imul(al4, bl9)) | 0; mid = (mid + Math.imul(al4, bh9)) | 0; mid = (mid + Math.imul(ah4, bl9)) | 0; hi = (hi + Math.imul(ah4, bh9)) | 0; var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; w13 &= 0x3ffffff; /* k = 14 */ lo = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = (mid + Math.imul(ah9, bl5)) | 0; hi = Math.imul(ah9, bh5); lo = (lo + Math.imul(al8, bl6)) | 0; mid = (mid + Math.imul(al8, bh6)) | 0; mid = (mid + Math.imul(ah8, bl6)) | 0; hi = (hi + Math.imul(ah8, bh6)) | 0; lo = (lo + Math.imul(al7, bl7)) | 0; mid = (mid + Math.imul(al7, bh7)) | 0; mid = (mid + Math.imul(ah7, bl7)) | 0; hi = (hi + Math.imul(ah7, bh7)) | 0; lo = (lo + Math.imul(al6, bl8)) | 0; mid = (mid + Math.imul(al6, bh8)) | 0; mid = (mid + Math.imul(ah6, bl8)) | 0; hi = (hi + Math.imul(ah6, bh8)) | 0; lo = (lo + Math.imul(al5, bl9)) | 0; mid = (mid + Math.imul(al5, bh9)) | 0; mid = (mid + Math.imul(ah5, bl9)) | 0; hi = (hi + Math.imul(ah5, bh9)) | 0; var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; w14 &= 0x3ffffff; /* k = 15 */ lo = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = (mid + Math.imul(ah9, bl6)) | 0; hi = Math.imul(ah9, bh6); lo = (lo + Math.imul(al8, bl7)) | 0; mid = (mid + Math.imul(al8, bh7)) | 0; mid = (mid + Math.imul(ah8, bl7)) | 0; hi = (hi + Math.imul(ah8, bh7)) | 0; lo = (lo + Math.imul(al7, bl8)) | 0; mid = (mid + Math.imul(al7, bh8)) | 0; mid = (mid + Math.imul(ah7, bl8)) | 0; hi = (hi + Math.imul(ah7, bh8)) | 0; lo = (lo + Math.imul(al6, bl9)) | 0; mid = (mid + Math.imul(al6, bh9)) | 0; mid = (mid + Math.imul(ah6, bl9)) | 0; hi = (hi + Math.imul(ah6, bh9)) | 0; var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; w15 &= 0x3ffffff; /* k = 16 */ lo = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = (mid + Math.imul(ah9, bl7)) | 0; hi = Math.imul(ah9, bh7); lo = (lo + Math.imul(al8, bl8)) | 0; mid = (mid + Math.imul(al8, bh8)) | 0; mid = (mid + Math.imul(ah8, bl8)) | 0; hi = (hi + Math.imul(ah8, bh8)) | 0; lo = (lo + Math.imul(al7, bl9)) | 0; mid = (mid + Math.imul(al7, bh9)) | 0; mid = (mid + Math.imul(ah7, bl9)) | 0; hi = (hi + Math.imul(ah7, bh9)) | 0; var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; w16 &= 0x3ffffff; /* k = 17 */ lo = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = (mid + Math.imul(ah9, bl8)) | 0; hi = Math.imul(ah9, bh8); lo = (lo + Math.imul(al8, bl9)) | 0; mid = (mid + Math.imul(al8, bh9)) | 0; mid = (mid + Math.imul(ah8, bl9)) | 0; hi = (hi + Math.imul(ah8, bh9)) | 0; var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; w17 &= 0x3ffffff; /* k = 18 */ lo = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = (mid + Math.imul(ah9, bl9)) | 0; hi = Math.imul(ah9, bh9); var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; w18 &= 0x3ffffff; o[0] = w0; o[1] = w1; o[2] = w2; o[3] = w3; o[4] = w4; o[5] = w5; o[6] = w6; o[7] = w7; o[8] = w8; o[9] = w9; o[10] = w10; o[11] = w11; o[12] = w12; o[13] = w13; o[14] = w14; o[15] = w15; o[16] = w16; o[17] = w17; o[18] = w18; if (c !== 0) { o[19] = c; out.length++; } return out; }; // Polyfill comb if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo (self, num, out) { out.negative = num.negative ^ self.negative; out.length = self.length + num.length; var carry = 0; var hncarry = 0; for (var k = 0; k < out.length - 1; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = hncarry; hncarry = 0; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = k - j; var a = self.words[i] | 0; var b = num.words[j] | 0; var r = a * b; var lo = r & 0x3ffffff; ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; lo = (lo + rword) | 0; rword = lo & 0x3ffffff; ncarry = (ncarry + (lo >>> 26)) | 0; hncarry += ncarry >>> 26; ncarry &= 0x3ffffff; } out.words[k] = rword; carry = ncarry; ncarry = hncarry; } if (carry !== 0) { out.words[k] = carry; } else { out.length--; } return out.strip(); } function jumboMulTo (self, num, out) { var fftm = new FFTM(); return fftm.mulp(self, num, out); } BN.prototype.mulTo = function mulTo (num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; // Cooley-Tukey algorithm for FFT // slightly revisited to rely on looping instead of recursion function FFTM (x, y) { this.x = x; this.y = y; } FFTM.prototype.makeRBT = function makeRBT (N) { var t = new Array(N); var l = BN.prototype._countBits(N) - 1; for (var i = 0; i < N; i++) { t[i] = this.revBin(i, l, N); } return t; }; // Returns binary-reversed representation of `x` FFTM.prototype.revBin = function revBin (x, l, N) { if (x === 0 || x === N - 1) return x; var rb = 0; for (var i = 0; i < l; i++) { rb |= (x & 1) << (l - i - 1); x >>= 1; } return rb; }; // Performs "tweedling" phase, therefore 'emulating' // behaviour of the recursive algorithm FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { for (var i = 0; i < N; i++) { rtws[i] = rws[rbt[i]]; itws[i] = iws[rbt[i]]; } }; FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { this.permute(rbt, rws, iws, rtws, itws, N); for (var s = 1; s < N; s <<= 1) { var l = s << 1; var rtwdf = Math.cos(2 * Math.PI / l); var itwdf = Math.sin(2 * Math.PI / l); for (var p = 0; p < N; p += l) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j = 0; j < s; j++) { var re = rtws[p + j]; var ie = itws[p + j]; var ro = rtws[p + j + s]; var io = itws[p + j + s]; var rx = rtwdf_ * ro - itwdf_ * io; io = rtwdf_ * io + itwdf_ * ro; ro = rx; rtws[p + j] = re + ro; itws[p + j] = ie + io; rtws[p + j + s] = re - ro; itws[p + j + s] = ie - io; /* jshint maxdepth : false */ if (j !== l) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; var i = 0; for (N = N / 2 | 0; N; N = N >>> 1) { i++; } return 1 << i + 1 + odd; }; FFTM.prototype.conjugate = function conjugate (rws, iws, N) { if (N <= 1) return; for (var i = 0; i < N / 2; i++) { var t = rws[i]; rws[i] = rws[N - i - 1]; rws[N - i - 1] = t; t = iws[i]; iws[i] = -iws[N - i - 1]; iws[N - i - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b (ws, N) { var carry = 0; for (var i = 0; i < N / 2; i++) { var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry; ws[i] = w & 0x3ffffff; if (w < 0x4000000) { carry = 0; } else { carry = w / 0x4000000 | 0; } } return ws; }; FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { var carry = 0; for (var i = 0; i < len; i++) { carry = carry + (ws[i] | 0); rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; } // Pad with zeroes for (i = 2 * len; i < N; ++i) { rws[i] = 0; } assert(carry === 0); assert((carry & ~0x1fff) === 0); }; FFTM.prototype.stub = function stub (N) { var ph = new Array(N); for (var i = 0; i < N; i++) { ph[i] = 0; } return ph; }; FFTM.prototype.mulp = function mulp (x, y, out) { var N = 2 * this.guessLen13b(x.length, y.length); var rbt = this.makeRBT(N); var _ = this.stub(N); var rws = new Array(N); var rwst = new Array(N); var iwst = new Array(N); var nrws = new Array(N); var nrwst = new Array(N); var niwst = new Array(N); var rmws = out.words; rmws.length = N; this.convert13b(x.words, x.length, rws, N); this.convert13b(y.words, y.length, nrws, N); this.transform(rws, _, rwst, iwst, N, rbt); this.transform(nrws, _, nrwst, niwst, N, rbt); for (var i = 0; i < N; i++) { var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; rwst[i] = rx; } this.conjugate(rwst, iwst, N); this.transform(rwst, iwst, rmws, _, N, rbt); this.conjugate(rmws, _, N); this.normalize13b(rmws, N); out.negative = x.negative ^ y.negative; out.length = x.length + y.length; return out.strip(); }; // Multiply `this` by `num` BN.prototype.mul = function mul (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; // Multiply employing FFT BN.prototype.mulf = function mulf (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; // In-place Multiplication BN.prototype.imul = function imul (num) { return this.clone().mulTo(num, this); }; BN.prototype.imuln = function imuln (num) { assert(typeof num === 'number'); assert(num < 0x4000000); // Carry var carry = 0; for (var i = 0; i < this.length; i++) { var w = (this.words[i] | 0) * num; var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); carry >>= 26; carry += (w / 0x4000000) | 0; // NOTE: lo is 27bit maximum carry += lo >>> 26; this.words[i] = lo & 0x3ffffff; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.muln = function muln (num) { return this.clone().imuln(num); }; // `this` * `this` BN.prototype.sqr = function sqr () { return this.mul(this); }; // `this` * `this` in-place BN.prototype.isqr = function isqr () { return this.imul(this.clone()); }; // Math.pow(`this`, `num`) BN.prototype.pow = function pow (num) { var w = toBitArray(num); if (w.length === 0) return new BN(1); // Skip leading zeroes var res = this; for (var i = 0; i < w.length; i++, res = res.sqr()) { if (w[i] !== 0) break; } if (++i < w.length) { for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { if (w[i] === 0) continue; res = res.mul(q); } } return res; }; // Shift-left in-place BN.prototype.iushln = function iushln (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); var i; if (r !== 0) { var carry = 0; for (i = 0; i < this.length; i++) { var newCarry = this.words[i] & carryMask; var c = ((this.words[i] | 0) - newCarry) << r; this.words[i] = c | carry; carry = newCarry >>> (26 - r); } if (carry) { this.words[i] = carry; this.length++; } } if (s !== 0) { for (i = this.length - 1; i >= 0; i--) { this.words[i + s] = this.words[i]; } for (i = 0; i < s; i++) { this.words[i] = 0; } this.length += s; } return this.strip(); }; BN.prototype.ishln = function ishln (bits) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushln(bits); }; // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits BN.prototype.iushrn = function iushrn (bits, hint, extended) { assert(typeof bits === 'number' && bits >= 0); var h; if (hint) { h = (hint - (hint % 26)) / 26; } else { h = 0; } var r = bits % 26; var s = Math.min((bits - r) / 26, this.length); var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); var maskedWords = extended; h -= s; h = Math.max(0, h); // Extended mode, copy masked part if (maskedWords) { for (var i = 0; i < s; i++) { maskedWords.words[i] = this.words[i]; } maskedWords.length = s; } if (s === 0) { // No-op, we should not move anything at all } else if (this.length > s) { this.length -= s; for (i = 0; i < this.length; i++) { this.words[i] = this.words[i + s]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { var word = this.words[i] | 0; this.words[i] = (carry << (26 - r)) | (word >>> r); carry = word & mask; } // Push carried bits as a mask if (maskedWords && carry !== 0) { maskedWords.words[maskedWords.length++] = carry; } if (this.length === 0) { this.words[0] = 0; this.length = 1; } return this.strip(); }; BN.prototype.ishrn = function ishrn (bits, hint, extended) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushrn(bits, hint, extended); }; // Shift-left BN.prototype.shln = function shln (bits) { return this.clone().ishln(bits); }; BN.prototype.ushln = function ushln (bits) { return this.clone().iushln(bits); }; // Shift-right BN.prototype.shrn = function shrn (bits) { return this.clone().ishrn(bits); }; BN.prototype.ushrn = function ushrn (bits) { return this.clone().iushrn(bits); }; // Test if n bit is set BN.prototype.testn = function testn (bit) { assert(typeof bit === 'number' && bit >= 0); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) return false; // Check bit and return var w = this.words[s]; return !!(w & q); }; // Return only lowers bits of number (in-place) BN.prototype.imaskn = function imaskn (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; assert(this.negative === 0, 'imaskn works only with positive numbers'); if (this.length <= s) { return this; } if (r !== 0) { s++; } this.length = Math.min(s, this.length); if (r !== 0) { var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); this.words[this.length - 1] &= mask; } return this.strip(); }; // Return only lowers bits of number BN.prototype.maskn = function maskn (bits) { return this.clone().imaskn(bits); }; // Add plain number `num` to `this` BN.prototype.iaddn = function iaddn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.isubn(-num); // Possible sign change if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) < num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } // Add without checks return this._iaddn(num); }; BN.prototype._iaddn = function _iaddn (num) { this.words[0] += num; // Carry for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { this.words[i] -= 0x4000000; if (i === this.length - 1) { this.words[i + 1] = 1; } else { this.words[i + 1]++; } } this.length = Math.max(this.length, i + 1); return this; }; // Subtract plain number `num` from `this` BN.prototype.isubn = function isubn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { // Carry for (var i = 0; i < this.length && this.words[i] < 0; i++) { this.words[i] += 0x4000000; this.words[i + 1] -= 1; } } return this.strip(); }; BN.prototype.addn = function addn (num) { return this.clone().iaddn(num); }; BN.prototype.subn = function subn (num) { return this.clone().isubn(num); }; BN.prototype.iabs = function iabs () { this.negative = 0; return this; }; BN.prototype.abs = function abs () { return this.clone().iabs(); }; BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { var len = num.length + shift; var i; this._expand(len); var w; var carry = 0; for (i = 0; i < num.length; i++) { w = (this.words[i + shift] | 0) + carry; var right = (num.words[i] | 0) * mul; w -= right & 0x3ffffff; carry = (w >> 26) - ((right / 0x4000000) | 0); this.words[i + shift] = w & 0x3ffffff; } for (; i < this.length - shift; i++) { w = (this.words[i + shift] | 0) + carry; carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } if (carry === 0) return this.strip(); // Subtraction overflow assert(carry === -1); carry = 0; for (i = 0; i < this.length; i++) { w = -(this.words[i] | 0) + carry; carry = w >> 26; this.words[i] = w & 0x3ffffff; } this.negative = 1; return this.strip(); }; BN.prototype._wordDiv = function _wordDiv (num, mode) { var shift = this.length - num.length; var a = this.clone(); var b = num; // Normalize var bhi = b.words[b.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b = b.ushln(shift); a.iushln(shift); bhi = b.words[b.length - 1] | 0; } // Initialize quotient var m = a.length - b.length; var q; if (mode !== 'mod') { q = new BN(null); q.length = m + 1; q.words = new Array(q.length); for (var i = 0; i < q.length; i++) { q.words[i] = 0; } } var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; if (q) { q.words[m] = 1; } } for (var j = m - 1; j >= 0; j--) { var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max // (0x7ffffff) qj = Math.min((qj / bhi) | 0, 0x3ffffff); a._ishlnsubmul(b, qj, j); while (a.negative !== 0) { qj--; a.negative = 0; a._ishlnsubmul(b, 1, j); if (!a.isZero()) { a.negative ^= 1; } } if (q) { q.words[j] = qj; } } if (q) { q.strip(); } a.strip(); // Denormalize if (mode !== 'div' && shift !== 0) { a.iushrn(shift); } return { div: q || null, mod: a }; }; // NOTE: 1) `mode` can be set to `mod` to request mod only, // to `div` to request div only, or be absent to // request both div & mod // 2) `positive` is true if unsigned mod is requested BN.prototype.divmod = function divmod (num, mode, positive) { assert(!num.isZero()); if (this.isZero()) { return { div: new BN(0), mod: new BN(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== 'mod') { div = res.div.neg(); } if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div: div, mod: mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== 'mod') { div = res.div.neg(); } return { div: div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod: mod }; } // Both numbers are positive at this point // Strip both numbers to approximate shift value if (num.length > this.length || this.cmp(num) < 0) { return { div: new BN(0), mod: this }; } // Very short reduction if (num.length === 1) { if (mode === 'div') { return { div: this.divn(num.words[0]), mod: null }; } if (mode === 'mod') { return { div: null, mod: new BN(this.modn(num.words[0])) }; } return { div: this.divn(num.words[0]), mod: new BN(this.modn(num.words[0])) }; } return this._wordDiv(num, mode); }; // Find `this` / `num` BN.prototype.div = function div (num) { return this.divmod(num, 'div', false).div; }; // Find `this` % `num` BN.prototype.mod = function mod (num) { return this.divmod(num, 'mod', false).mod; }; BN.prototype.umod = function umod (num) { return this.divmod(num, 'mod', true).mod; }; // Find Round(`this` / `num`) BN.prototype.divRound = function divRound (num) { var dm = this.divmod(num); // Fast case - exact division if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(1); var r2 = num.andln(1); var cmp = mod.cmp(half); // Round down if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; // Round up return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); }; BN.prototype.modn = function modn (num) { assert(num <= 0x3ffffff); var p = (1 << 26) % num; var acc = 0; for (var i = this.length - 1; i >= 0; i--) { acc = (p * acc + (this.words[i] | 0)) % num; } return acc; }; // In-place division by number BN.prototype.idivn = function idivn (num) { assert(num <= 0x3ffffff); var carry = 0; for (var i = this.length - 1; i >= 0; i--) { var w = (this.words[i] | 0) + carry * 0x4000000; this.words[i] = (w / num) | 0; carry = w % num; } return this.strip(); }; BN.prototype.divn = function divn (num) { return this.clone().idivn(num); }; BN.prototype.egcd = function egcd (p) { assert(p.negative === 0); assert(!p.isZero()); var x = this; var y = p.clone(); if (x.negative !== 0) { x = x.umod(p); } else { x = x.clone(); } // A * x + B * y = x var A = new BN(1); var B = new BN(0); // C * x + D * y = y var C = new BN(0); var D = new BN(1); var g = 0; while (x.isEven() && y.isEven()) { x.iushrn(1); y.iushrn(1); ++g; } var yp = y.clone(); var xp = x.clone(); while (!x.isZero()) { for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { x.iushrn(i); while (i-- > 0) { if (A.isOdd() || B.isOdd()) { A.iadd(yp); B.isub(xp); } A.iushrn(1); B.iushrn(1); } } for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { y.iushrn(j); while (j-- > 0) { if (C.isOdd() || D.isOdd()) { C.iadd(yp); D.isub(xp); } C.iushrn(1); D.iushrn(1); } } if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); B.isub(D); } else { y.isub(x); C.isub(A); D.isub(B); } } return { a: C, b: D, gcd: y.iushln(g) }; }; // This is reduced incarnation of the binary EEA // above, designated to invert members of the // _prime_ fields F(p) at a maximal speed BN.prototype._invmp = function _invmp (p) { assert(p.negative === 0); assert(!p.isZero()); var a = this; var b = p.clone(); if (a.negative !== 0) { a = a.umod(p); } else { a = a.clone(); } var x1 = new BN(1); var x2 = new BN(0); var delta = b.clone(); while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { a.iushrn(i); while (i-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { b.iushrn(j); while (j-- > 0) { if (x2.isOdd()) { x2.iadd(delta); } x2.iushrn(1); } } if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); } else { b.isub(a); x2.isub(x1); } } var res; if (a.cmpn(1) === 0) { res = x1; } else { res = x2; } if (res.cmpn(0) < 0) { res.iadd(p); } return res; }; BN.prototype.gcd = function gcd (num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a = this.clone(); var b = num.clone(); a.negative = 0; b.negative = 0; // Remove common factor of two for (var shift = 0; a.isEven() && b.isEven(); shift++) { a.iushrn(1); b.iushrn(1); } do { while (a.isEven()) { a.iushrn(1); } while (b.isEven()) { b.iushrn(1); } var r = a.cmp(b); if (r < 0) { // Swap `a` and `b` to make `a` always bigger than `b` var t = a; a = b; b = t; } else if (r === 0 || b.cmpn(1) === 0) { break; } a.isub(b); } while (true); return b.iushln(shift); }; // Invert number in the field F(num) BN.prototype.invm = function invm (num) { return this.egcd(num).a.umod(num); }; BN.prototype.isEven = function isEven () { return (this.words[0] & 1) === 0; }; BN.prototype.isOdd = function isOdd () { return (this.words[0] & 1) === 1; }; // And first word and num BN.prototype.andln = function andln (num) { return this.words[0] & num; }; // Increment at the bit position in-line BN.prototype.bincn = function bincn (bit) { assert(typeof bit === 'number'); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) { this._expand(s + 1); this.words[s] |= q; return this; } // Add bit and propagate, if needed var carry = q; for (var i = s; carry !== 0 && i < this.length; i++) { var w = this.words[i] | 0; w += carry; carry = w >>> 26; w &= 0x3ffffff; this.words[i] = w; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.isZero = function isZero () { return this.length === 1 && this.words[0] === 0; }; BN.prototype.cmpn = function cmpn (num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this.strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert(num <= 0x3ffffff, 'Number is too big'); var w = this.words[0] | 0; res = w === num ? 0 : w < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; // Compare two numbers and return: // 1 - if `this` > `num` // 0 - if `this` == `num` // -1 - if `this` < `num` BN.prototype.cmp = function cmp (num) { if (this.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; return res; }; // Unsigned comparison BN.prototype.ucmp = function ucmp (num) { // At this point both numbers have the same sign if (this.length > num.length) return 1; if (this.length < num.length) return -1; var res = 0; for (var i = this.length - 1; i >= 0; i--) { var a = this.words[i] | 0; var b = num.words[i] | 0; if (a === b) continue; if (a < b) { res = -1; } else if (a > b) { res = 1; } break; } return res; }; BN.prototype.gtn = function gtn (num) { return this.cmpn(num) === 1; }; BN.prototype.gt = function gt (num) { return this.cmp(num) === 1; }; BN.prototype.gten = function gten (num) { return this.cmpn(num) >= 0; }; BN.prototype.gte = function gte (num) { return this.cmp(num) >= 0; }; BN.prototype.ltn = function ltn (num) { return this.cmpn(num) === -1; }; BN.prototype.lt = function lt (num) { return this.cmp(num) === -1; }; BN.prototype.lten = function lten (num) { return this.cmpn(num) <= 0; }; BN.prototype.lte = function lte (num) { return this.cmp(num) <= 0; }; BN.prototype.eqn = function eqn (num) { return this.cmpn(num) === 0; }; BN.prototype.eq = function eq (num) { return this.cmp(num) === 0; }; // // A reduce context, could be using montgomery or something better, depending // on the `m` itself. // BN.red = function red (num) { return new Red(num); }; BN.prototype.toRed = function toRed (ctx) { assert(!this.red, 'Already a number in reduction context'); assert(this.negative === 0, 'red works only with positives'); return ctx.convertTo(this)._forceRed(ctx); }; BN.prototype.fromRed = function fromRed () { assert(this.red, 'fromRed works only with numbers in reduction context'); return this.red.convertFrom(this); }; BN.prototype._forceRed = function _forceRed (ctx) { this.red = ctx; return this; }; BN.prototype.forceRed = function forceRed (ctx) { assert(!this.red, 'Already a number in reduction context'); return this._forceRed(ctx); }; BN.prototype.redAdd = function redAdd (num) { assert(this.red, 'redAdd works only with red numbers'); return this.red.add(this, num); }; BN.prototype.redIAdd = function redIAdd (num) { assert(this.red, 'redIAdd works only with red numbers'); return this.red.iadd(this, num); }; BN.prototype.redSub = function redSub (num) { assert(this.red, 'redSub works only with red numbers'); return this.red.sub(this, num); }; BN.prototype.redISub = function redISub (num) { assert(this.red, 'redISub works only with red numbers'); return this.red.isub(this, num); }; BN.prototype.redShl = function redShl (num) { assert(this.red, 'redShl works only with red numbers'); return this.red.shl(this, num); }; BN.prototype.redMul = function redMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.mul(this, num); }; BN.prototype.redIMul = function redIMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.imul(this, num); }; BN.prototype.redSqr = function redSqr () { assert(this.red, 'redSqr works only with red numbers'); this.red._verify1(this); return this.red.sqr(this); }; BN.prototype.redISqr = function redISqr () { assert(this.red, 'redISqr works only with red numbers'); this.red._verify1(this); return this.red.isqr(this); }; // Square root over p BN.prototype.redSqrt = function redSqrt () { assert(this.red, 'redSqrt works only with red numbers'); this.red._verify1(this); return this.red.sqrt(this); }; BN.prototype.redInvm = function redInvm () { assert(this.red, 'redInvm works only with red numbers'); this.red._verify1(this); return this.red.invm(this); }; // Return negative clone of `this` % `red modulo` BN.prototype.redNeg = function redNeg () { assert(this.red, 'redNeg works only with red numbers'); this.red._verify1(this); return this.red.neg(this); }; BN.prototype.redPow = function redPow (num) { assert(this.red && !num.red, 'redPow(normalNum)'); this.red._verify1(this); return this.red.pow(this, num); }; // Prime numbers with efficient reduction var primes = { k256: null, p224: null, p192: null, p25519: null }; // Pseudo-Mersenne prime function MPrime (name, p) { // P = 2 ^ N - K this.name = name; this.p = new BN(p, 16); this.n = this.p.bitLength(); this.k = new BN(1).iushln(this.n).isub(this.p); this.tmp = this._tmp(); } MPrime.prototype._tmp = function _tmp () { var tmp = new BN(null); tmp.words = new Array(Math.ceil(this.n / 13)); return tmp; }; MPrime.prototype.ireduce = function ireduce (num) { // Assumes that `num` is less than `P^2` // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) var r = num; var rlen; do { this.split(r, this.tmp); r = this.imulK(r); r = r.iadd(this.tmp); rlen = r.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r.ucmp(this.p); if (cmp === 0) { r.words[0] = 0; r.length = 1; } else if (cmp > 0) { r.isub(this.p); } else { if (r.strip !== undefined) { // r is BN v4 instance r.strip(); } else { // r is BN v5 instance r._strip(); } } return r; }; MPrime.prototype.split = function split (input, out) { input.iushrn(this.n, 0, out); }; MPrime.prototype.imulK = function imulK (num) { return num.imul(this.k); }; function K256 () { MPrime.call( this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); } inherits(K256, MPrime); K256.prototype.split = function split (input, output) { // 256 = 9 * 26 + 22 var mask = 0x3fffff; var outLen = Math.min(input.length, 9); for (var i = 0; i < outLen; i++) { output.words[i] = input.words[i]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } // Shift by 9 limbs var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i = 10; i < input.length; i++) { var next = input.words[i] | 0; input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); prev = next; } prev >>>= 22; input.words[i - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK (num) { // K = 0x1000003d1 = [ 0x40, 0x3d1 ] num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 var lo = 0; for (var i = 0; i < num.length; i++) { var w = num.words[i] | 0; lo += w * 0x3d1; num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 0); } // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224 () { MPrime.call( this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); function P192 () { MPrime.call( this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); function P25519 () { // 2 ^ 255 - 19 MPrime.call( this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK (num) { // K = 0x13 var carry = 0; for (var i = 0; i < num.length; i++) { var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 26; num.words[i] = lo; carry = hi; } if (carry !== 0) { num.words[num.length++] = carry; } return num; }; // Exported mostly for testing purposes, use plain name instead BN._prime = function prime (name) { // Cached version of prime if (primes[name]) return primes[name]; var prime; if (name === 'k256') { prime = new K256(); } else if (name === 'p224') { prime = new P224(); } else if (name === 'p192') { prime = new P192(); } else if (name === 'p25519') { prime = new P25519(); } else { throw new Error('Unknown prime ' + name); } primes[name] = prime; return prime; }; // // Base reduction engine // function Red (m) { if (typeof m === 'string') { var prime = BN._prime(m); this.m = prime.p; this.prime = prime; } else { assert(m.gtn(1), 'modulus must be greater than 1'); this.m = m; this.prime = null; } } Red.prototype._verify1 = function _verify1 (a) { assert(a.negative === 0, 'red works only with positives'); assert(a.red, 'red works only with red numbers'); }; Red.prototype._verify2 = function _verify2 (a, b) { assert((a.negative | b.negative) === 0, 'red works only with positives'); assert(a.red && a.red === b.red, 'red works only with red numbers'); }; Red.prototype.imod = function imod (a) { if (this.prime) return this.prime.ireduce(a)._forceRed(this); return a.umod(this.m)._forceRed(this); }; Red.prototype.neg = function neg (a) { if (a.isZero()) { return a.clone(); } return this.m.sub(a)._forceRed(this); }; Red.prototype.add = function add (a, b) { this._verify2(a, b); var res = a.add(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res._forceRed(this); }; Red.prototype.iadd = function iadd (a, b) { this._verify2(a, b); var res = a.iadd(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res; }; Red.prototype.sub = function sub (a, b) { this._verify2(a, b); var res = a.sub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res._forceRed(this); }; Red.prototype.isub = function isub (a, b) { this._verify2(a, b); var res = a.isub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res; }; Red.prototype.shl = function shl (a, num) { this._verify1(a); return this.imod(a.ushln(num)); }; Red.prototype.imul = function imul (a, b) { this._verify2(a, b); return this.imod(a.imul(b)); }; Red.prototype.mul = function mul (a, b) { this._verify2(a, b); return this.imod(a.mul(b)); }; Red.prototype.isqr = function isqr (a) { return this.imul(a, a.clone()); }; Red.prototype.sqr = function sqr (a) { return this.mul(a, a); }; Red.prototype.sqrt = function sqrt (a) { if (a.isZero()) return a.clone(); var mod3 = this.m.andln(3); assert(mod3 % 2 === 1); // Fast case if (mod3 === 3) { var pow = this.m.add(new BN(1)).iushrn(2); return this.pow(a, pow); } // Tonelli-Shanks algorithm (Totally unoptimized and slow) // // Find Q and S, that Q * 2 ^ S = (P - 1) var q = this.m.subn(1); var s = 0; while (!q.isZero() && q.andln(1) === 0) { s++; q.iushrn(1); } assert(!q.isZero()); var one = new BN(1).toRed(this); var nOne = one.redNeg(); // Find quadratic non-residue // NOTE: Max is such because of generalized Riemann hypothesis. var lpow = this.m.subn(1).iushrn(1); var z = this.m.bitLength(); z = new BN(2 * z * z).toRed(this); while (this.pow(z, lpow).cmp(nOne) !== 0) { z.redIAdd(nOne); } var c = this.pow(z, q); var r = this.pow(a, q.addn(1).iushrn(1)); var t = this.pow(a, q); var m = s; while (t.cmp(one) !== 0) { var tmp = t; for (var i = 0; tmp.cmp(one) !== 0; i++) { tmp = tmp.redSqr(); } assert(i < m); var b = this.pow(c, new BN(1).iushln(m - i - 1)); r = r.redMul(b); c = b.redSqr(); t = t.redMul(c); m = i; } return r; }; Red.prototype.invm = function invm (a) { var inv = a._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow (a, num) { if (num.isZero()) return new BN(1).toRed(this); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); wnd[1] = a; for (var i = 2; i < wnd.length; i++) { wnd[i] = this.mul(wnd[i - 1], a); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i = num.length - 1; i >= 0; i--) { var word = num.words[i]; for (var j = start - 1; j >= 0; j--) { var bit = (word >> j) & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo (num) { var r = num.umod(this.m); return r === num ? r.clone() : r; }; Red.prototype.convertFrom = function convertFrom (num) { var res = num.clone(); res.red = null; return res; }; // // Montgomery method engine // BN.mont = function mont (num) { return new Mont(num); }; function Mont (m) { Red.call(this, m); this.shift = this.m.bitLength(); if (this.shift % 26 !== 0) { this.shift += 26 - (this.shift % 26); } this.r = new BN(1).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo (num) { return this.imod(num.ushln(this.shift)); }; Mont.prototype.convertFrom = function convertFrom (num) { var r = this.imod(num.mul(this.rinv)); r.red = null; return r; }; Mont.prototype.imul = function imul (a, b) { if (a.isZero() || b.isZero()) { a.words[0] = 0; a.length = 1; return a; } var t = a.imul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.mul = function mul (a, b) { if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); var t = a.mul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.invm = function invm (a) { // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R var res = this.imod(a._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })( false || module, this); /***/ }), /***/ 9931: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var r; module.exports = function rand(len) { if (!r) r = new Rand(null); return r.generate(len); }; function Rand(rand) { this.rand = rand; } module.exports.Rand = Rand; Rand.prototype.generate = function generate(len) { return this._rand(len); }; // Emulate crypto API using randy Rand.prototype._rand = function _rand(n) { if (this.rand.getBytes) return this.rand.getBytes(n); var res = new Uint8Array(n); for (var i = 0; i < res.length; i++) res[i] = this.rand.getByte(); return res; }; if (typeof self === 'object') { if (self.crypto && self.crypto.getRandomValues) { // Modern browsers Rand.prototype._rand = function _rand(n) { var arr = new Uint8Array(n); self.crypto.getRandomValues(arr); return arr; }; } else if (self.msCrypto && self.msCrypto.getRandomValues) { // IE Rand.prototype._rand = function _rand(n) { var arr = new Uint8Array(n); self.msCrypto.getRandomValues(arr); return arr; }; // Safari's WebWorkers do not have `crypto` } else if (typeof window === 'object') { // Old junk Rand.prototype._rand = function() { throw new Error('Not implemented yet'); }; } } else { // Node.js or Web worker with no crypto support try { var crypto = __webpack_require__(9214); if (typeof crypto.randomBytes !== 'function') throw new Error('Not supported'); Rand.prototype._rand = function _rand(n) { return crypto.randomBytes(n); }; } catch (e) { } } /***/ }), /***/ 1708: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* global indexedDB */ const { AbstractLevel } = __webpack_require__(875) const ModuleError = __webpack_require__(4473) const parallel = __webpack_require__(9967) const { fromCallback } = __webpack_require__(6957) const { Iterator } = __webpack_require__(8212) const deserialize = __webpack_require__(9687) const clear = __webpack_require__(7753) const createKeyRange = __webpack_require__(1217) // Keep as-is for compatibility with existing level-js databases const DEFAULT_PREFIX = 'level-js-' const kIDB = Symbol('idb') const kNamePrefix = Symbol('namePrefix') const kLocation = Symbol('location') const kVersion = Symbol('version') const kStore = Symbol('store') const kOnComplete = Symbol('onComplete') const kPromise = Symbol('promise') class BrowserLevel extends AbstractLevel { constructor (location, options, _) { // To help migrating to abstract-level if (typeof options === 'function' || typeof _ === 'function') { throw new ModuleError('The levelup-style callback argument has been removed', { code: 'LEVEL_LEGACY' }) } const { prefix, version, ...forward } = options || {} super({ encodings: { view: true }, snapshots: false, createIfMissing: false, errorIfExists: false, seek: true }, forward) if (typeof location !== 'string') { throw new Error('constructor requires a location string argument') } // TODO (next major): remove default prefix this[kLocation] = location this[kNamePrefix] = prefix == null ? DEFAULT_PREFIX : prefix this[kVersion] = parseInt(version || 1, 10) this[kIDB] = null } get location () { return this[kLocation] } get namePrefix () { return this[kNamePrefix] } get version () { return this[kVersion] } // Exposed for backwards compat and unit tests get db () { return this[kIDB] } get type () { return 'browser-level' } _open (options, callback) { const req = indexedDB.open(this[kNamePrefix] + this[kLocation], this[kVersion]) req.onerror = function () { callback(req.error || new Error('unknown error')) } req.onsuccess = () => { this[kIDB] = req.result callback() } req.onupgradeneeded = (ev) => { const db = ev.target.result if (!db.objectStoreNames.contains(this[kLocation])) { db.createObjectStore(this[kLocation]) } } } [kStore] (mode) { const transaction = this[kIDB].transaction([this[kLocation]], mode) return transaction.objectStore(this[kLocation]) } [kOnComplete] (request, callback) { const transaction = request.transaction // Take advantage of the fact that a non-canceled request error aborts // the transaction. I.e. no need to listen for "request.onerror". transaction.onabort = function () { callback(transaction.error || new Error('aborted by user')) } transaction.oncomplete = function () { callback(null, request.result) } } _get (key, options, callback) { const store = this[kStore]('readonly') let req try { req = store.get(key) } catch (err) { return this.nextTick(callback, err) } this[kOnComplete](req, function (err, value) { if (err) return callback(err) if (value === undefined) { return callback(new ModuleError('Entry not found', { code: 'LEVEL_NOT_FOUND' })) } callback(null, deserialize(value)) }) } _getMany (keys, options, callback) { const store = this[kStore]('readonly') const tasks = keys.map((key) => (next) => { let request try { request = store.get(key) } catch (err) { return next(err) } request.onsuccess = () => { const value = request.result next(null, value === undefined ? value : deserialize(value)) } request.onerror = (ev) => { ev.stopPropagation() next(request.error) } }) parallel(tasks, 16, callback) } _del (key, options, callback) { const store = this[kStore]('readwrite') let req try { req = store.delete(key) } catch (err) { return this.nextTick(callback, err) } this[kOnComplete](req, callback) } _put (key, value, options, callback) { const store = this[kStore]('readwrite') let req try { // Will throw a DataError or DataCloneError if the environment // does not support serializing the key or value respectively. req = store.put(value, key) } catch (err) { return this.nextTick(callback, err) } this[kOnComplete](req, callback) } // TODO: implement key and value iterators _iterator (options) { return new Iterator(this, this[kLocation], options) } _batch (operations, options, callback) { const store = this[kStore]('readwrite') const transaction = store.transaction let index = 0 let error transaction.onabort = function () { callback(error || transaction.error || new Error('aborted by user')) } transaction.oncomplete = function () { callback() } // Wait for a request to complete before making the next, saving CPU. function loop () { const op = operations[index++] const key = op.key let req try { req = op.type === 'del' ? store.delete(key) : store.put(op.value, key) } catch (err) { error = err transaction.abort() return } if (index < operations.length) { req.onsuccess = loop } else if (typeof transaction.commit === 'function') { // Commit now instead of waiting for auto-commit transaction.commit() } } loop() } _clear (options, callback) { let keyRange let req try { keyRange = createKeyRange(options) } catch (e) { // The lower key is greater than the upper key. // IndexedDB throws an error, but we'll just do nothing. return this.nextTick(callback) } if (options.limit >= 0) { // IDBObjectStore#delete(range) doesn't have such an option. // Fall back to cursor-based implementation. return clear(this, this[kLocation], keyRange, options, callback) } try { const store = this[kStore]('readwrite') req = keyRange ? store.delete(keyRange) : store.clear() } catch (err) { return this.nextTick(callback, err) } this[kOnComplete](req, callback) } _close (callback) { this[kIDB].close() this.nextTick(callback) } } BrowserLevel.destroy = function (location, prefix, callback) { if (typeof prefix === 'function') { callback = prefix prefix = DEFAULT_PREFIX } callback = fromCallback(callback, kPromise) const request = indexedDB.deleteDatabase(prefix + location) request.onsuccess = function () { callback() } request.onerror = function (err) { callback(err) } return callback[kPromise] } exports.BrowserLevel = BrowserLevel /***/ }), /***/ 8212: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const { AbstractIterator } = __webpack_require__(875) const createKeyRange = __webpack_require__(1217) const deserialize = __webpack_require__(9687) const kCache = Symbol('cache') const kFinished = Symbol('finished') const kOptions = Symbol('options') const kCurrentOptions = Symbol('currentOptions') const kPosition = Symbol('position') const kLocation = Symbol('location') const kFirst = Symbol('first') const emptyOptions = {} class Iterator extends AbstractIterator { constructor (db, location, options) { super(db, options) this[kCache] = [] this[kFinished] = this.limit === 0 this[kOptions] = options this[kCurrentOptions] = { ...options } this[kPosition] = undefined this[kLocation] = location this[kFirst] = true } // Note: if called by _all() then size can be Infinity. This is an internal // detail; by design AbstractIterator.nextv() does not support Infinity. _nextv (size, options, callback) { this[kFirst] = false if (this[kFinished]) { return this.nextTick(callback, null, []) } else if (this[kCache].length > 0) { // TODO: mixing next and nextv is not covered by test suite size = Math.min(size, this[kCache].length) return this.nextTick(callback, null, this[kCache].splice(0, size)) } // Adjust range by what we already visited if (this[kPosition] !== undefined) { if (this[kOptions].reverse) { this[kCurrentOptions].lt = this[kPosition] this[kCurrentOptions].lte = undefined } else { this[kCurrentOptions].gt = this[kPosition] this[kCurrentOptions].gte = undefined } } let keyRange try { keyRange = createKeyRange(this[kCurrentOptions]) } catch (_) { // The lower key is greater than the upper key. // IndexedDB throws an error, but we'll just return 0 results. this[kFinished] = true return this.nextTick(callback, null, []) } const transaction = this.db.db.transaction([this[kLocation]], 'readonly') const store = transaction.objectStore(this[kLocation]) const entries = [] if (!this[kOptions].reverse) { let keys let values const complete = () => { // Wait for both requests to complete if (keys === undefined || values === undefined) return const length = Math.max(keys.length, values.length) if (length === 0 || size === Infinity) { this[kFinished] = true } else { this[kPosition] = keys[length - 1] } // Resize entries.length = length // Merge keys and values for (let i = 0; i < length; i++) { const key = keys[i] const value = values[i] entries[i] = [ this[kOptions].keys && key !== undefined ? deserialize(key) : undefined, this[kOptions].values && value !== undefined ? deserialize(value) : undefined ] } maybeCommit(transaction) } // If keys were not requested and size is Infinity, we don't have to keep // track of position and can thus skip getting keys. if (this[kOptions].keys || size < Infinity) { store.getAllKeys(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => { keys = ev.target.result complete() } } else { keys = [] this.nextTick(complete) } if (this[kOptions].values) { store.getAll(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => { values = ev.target.result complete() } } else { values = [] this.nextTick(complete) } } else { // Can't use getAll() in reverse, so use a slower cursor that yields one item at a time // TODO: test if all target browsers support openKeyCursor const method = !this[kOptions].values && store.openKeyCursor ? 'openKeyCursor' : 'openCursor' store[method](keyRange, 'prev').onsuccess = (ev) => { const cursor = ev.target.result if (cursor) { const { key, value } = cursor this[kPosition] = key entries.push([ this[kOptions].keys && key !== undefined ? deserialize(key) : undefined, this[kOptions].values && value !== undefined ? deserialize(value) : undefined ]) if (entries.length < size) { cursor.continue() } else { maybeCommit(transaction) } } else { this[kFinished] = true } } } // If an error occurs (on the request), the transaction will abort. transaction.onabort = () => { callback(transaction.error || new Error('aborted by user')) callback = null } transaction.oncomplete = () => { callback(null, entries) callback = null } } _next (callback) { if (this[kCache].length > 0) { const [key, value] = this[kCache].shift() this.nextTick(callback, null, key, value) } else if (this[kFinished]) { this.nextTick(callback) } else { let size = Math.min(100, this.limit - this.count) if (this[kFirst]) { // It's common to only want one entry initially or after a seek() this[kFirst] = false size = 1 } this._nextv(size, emptyOptions, (err, entries) => { if (err) return callback(err) this[kCache] = entries this._next(callback) }) } } _all (options, callback) { this[kFirst] = false // TODO: mixing next and all is not covered by test suite const cache = this[kCache].splice(0, this[kCache].length) const size = this.limit - this.count - cache.length if (size <= 0) { return this.nextTick(callback, null, cache) } this._nextv(size, emptyOptions, (err, entries) => { if (err) return callback(err) if (cache.length > 0) entries = cache.concat(entries) callback(null, entries) }) } _seek (target, options) { this[kFirst] = true this[kCache] = [] this[kFinished] = false this[kPosition] = undefined // TODO: not covered by test suite this[kCurrentOptions] = { ...this[kOptions] } let keyRange try { keyRange = createKeyRange(this[kOptions]) } catch (_) { this[kFinished] = true return } if (keyRange !== null && !keyRange.includes(target)) { this[kFinished] = true } else if (this[kOptions].reverse) { this[kCurrentOptions].lte = target } else { this[kCurrentOptions].gte = target } } } exports.Iterator = Iterator function maybeCommit (transaction) { // Commit (meaning close) now instead of waiting for auto-commit if (typeof transaction.commit === 'function') { transaction.commit() } } /***/ }), /***/ 7753: /***/ (function(module) { "use strict"; module.exports = function clear (db, location, keyRange, options, callback) { if (options.limit === 0) return db.nextTick(callback) const transaction = db.db.transaction([location], 'readwrite') const store = transaction.objectStore(location) let count = 0 transaction.oncomplete = function () { callback() } transaction.onabort = function () { callback(transaction.error || new Error('aborted by user')) } // A key cursor is faster (skips reading values) but not supported by IE // TODO: we no longer support IE. Test others const method = store.openKeyCursor ? 'openKeyCursor' : 'openCursor' const direction = options.reverse ? 'prev' : 'next' store[method](keyRange, direction).onsuccess = function (ev) { const cursor = ev.target.result if (cursor) { // Wait for a request to complete before continuing, saving CPU. store.delete(cursor.key).onsuccess = function () { if (options.limit <= 0 || ++count < options.limit) { cursor.continue() } } } } } /***/ }), /***/ 9687: /***/ (function(module) { "use strict"; const textEncoder = new TextEncoder() module.exports = function (data) { if (data instanceof Uint8Array) { return data } else if (data instanceof ArrayBuffer) { return new Uint8Array(data) } else { // Non-binary data stored with an old version (level-js < 5.0.0) return textEncoder.encode(data) } } /***/ }), /***/ 1217: /***/ (function(module) { "use strict"; /* global IDBKeyRange */ module.exports = function createKeyRange (options) { const lower = options.gte !== undefined ? options.gte : options.gt !== undefined ? options.gt : undefined const upper = options.lte !== undefined ? options.lte : options.lt !== undefined ? options.lt : undefined const lowerExclusive = options.gte === undefined const upperExclusive = options.lte === undefined if (lower !== undefined && upper !== undefined) { return IDBKeyRange.bound(lower, upper, lowerExclusive, upperExclusive) } else if (lower !== undefined) { return IDBKeyRange.lowerBound(lower, lowerExclusive) } else if (upper !== undefined) { return IDBKeyRange.upperBound(upper, upperExclusive) } else { return null } } /***/ }), /***/ 3533: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { const Buffer = (__webpack_require__(9509).Buffer) module.exports = class BufferPipe { /** * Creates a new instance of a pipe * @param {Buffer} buf - an optional buffer to start with */ constructor (buf = Buffer.from([])) { this.buffer = buf } /** * read `num` number of bytes from the pipe * @param {Number} num * @return {Buffer} */ read (num) { const data = this.buffer.subarray(0, num) this.buffer = this.buffer.subarray(num) return data } /** * Wites a buffer to the pipe * @param {Buffer} buf */ write (buf) { buf = Buffer.from(buf) this.buffer = Buffer.concat([this.buffer, buf]) } } /***/ }), /***/ 8764: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ const base64 = __webpack_require__(9742) const ieee754 = __webpack_require__(645) const customInspectSymbol = (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation : null exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 const K_MAX_LENGTH = 0x7fffffff exports.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { console.error( 'This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' ) } function typedArraySupport () { // Can typed array instances can be augmented? try { const arr = new Uint8Array(1) const proto = { foo: function () { return 42 } } Object.setPrototypeOf(proto, Uint8Array.prototype) Object.setPrototypeOf(arr, proto) return arr.foo() === 42 } catch (e) { return false } } Object.defineProperty(Buffer.prototype, 'parent', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.buffer } }) Object.defineProperty(Buffer.prototype, 'offset', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.byteOffset } }) function createBuffer (length) { if (length > K_MAX_LENGTH) { throw new RangeError('The value "' + length + '" is invalid for option "size"') } // Return an augmented `Uint8Array` instance const buf = new Uint8Array(length) Object.setPrototypeOf(buf, Buffer.prototype) return buf } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new TypeError( 'The "string" argument must be of type string. Received type number' ) } return allocUnsafe(arg) } return from(arg, encodingOrOffset, length) } Buffer.poolSize = 8192 // not used by this implementation function from (value, encodingOrOffset, length) { if (typeof value === 'string') { return fromString(value, encodingOrOffset) } if (ArrayBuffer.isView(value)) { return fromArrayView(value) } if (value == null) { throw new TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } if (isInstance(value, ArrayBuffer) || (value && isInstance(value.buffer, ArrayBuffer))) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof SharedArrayBuffer !== 'undefined' && (isInstance(value, SharedArrayBuffer) || (value && isInstance(value.buffer, SharedArrayBuffer)))) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'number') { throw new TypeError( 'The "value" argument must not be of type number. Received type number' ) } const valueOf = value.valueOf && value.valueOf() if (valueOf != null && valueOf !== value) { return Buffer.from(valueOf, encodingOrOffset, length) } const b = fromObject(value) if (b) return b if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length) } throw new TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length) } // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) Object.setPrototypeOf(Buffer, Uint8Array) function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be of type number') } else if (size < 0) { throw new RangeError('The value "' + size + '" is invalid for option "size"') } } function alloc (size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpreted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill) } return createBuffer(size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding) } function allocUnsafe (size) { assertSize(size) return createBuffer(size < 0 ? 0 : checked(size) | 0) } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } const length = byteLength(string, encoding) | 0 let buf = createBuffer(length) const actual = buf.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual) } return buf } function fromArrayLike (array) { const length = array.length < 0 ? 0 : checked(array.length) | 0 const buf = createBuffer(length) for (let i = 0; i < length; i += 1) { buf[i] = array[i] & 255 } return buf } function fromArrayView (arrayView) { if (isInstance(arrayView, Uint8Array)) { const copy = new Uint8Array(arrayView) return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) } return fromArrayLike(arrayView) } function fromArrayBuffer (array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('"offset" is outside of buffer bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('"length" is outside of buffer bounds') } let buf if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array) } else if (length === undefined) { buf = new Uint8Array(array, byteOffset) } else { buf = new Uint8Array(array, byteOffset, length) } // Return an augmented `Uint8Array` instance Object.setPrototypeOf(buf, Buffer.prototype) return buf } function fromObject (obj) { if (Buffer.isBuffer(obj)) { const len = checked(obj.length) | 0 const buf = createBuffer(len) if (buf.length === 0) { return buf } obj.copy(buf, 0, 0, len) return buf } if (obj.length !== undefined) { if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { return createBuffer(0) } return fromArrayLike(obj) } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data) } } function checked (length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return b != null && b._isBuffer === true && b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false } Buffer.compare = function compare (a, b) { if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError( 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' ) } if (a === b) return 0 let x = a.length let y = b.length for (let i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } let i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } const buffer = Buffer.allocUnsafe(length) let pos = 0 for (i = 0; i < list.length; ++i) { let buf = list[i] if (isInstance(buf, Uint8Array)) { if (pos + buf.length > buffer.length) { if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) buf.copy(buffer, pos) } else { Uint8Array.prototype.set.call( buffer, buf, pos ) } } else if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } else { buf.copy(buffer, pos) } pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { throw new TypeError( 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + typeof string ) } const len = string.length const mustMatch = (arguments.length > 2 && arguments[2] === true) if (!mustMatch && len === 0) return 0 // Use a for loop to avoid recursion let loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) { return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 } encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { let loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coercion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) // to detect a Buffer instance. It's not possible to use `instanceof Buffer` // reliably in a browserify context because there could be multiple different // copies of the 'buffer' package in use. This method works even for Buffer // instances that were created from another copy of the `buffer` package. // See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer = true function swap (b, n, m) { const i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { const len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (let i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { const len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (let i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { const len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (let i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { const length = this.length if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.toLocaleString = Buffer.prototype.toString Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { let str = '' const max = exports.INSPECT_MAX_BYTES str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() if (this.length > max) str += ' ... ' return '' } if (customInspectSymbol) { Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (isInstance(target, Uint8Array)) { target = Buffer.from(target, target.offset, target.byteLength) } if (!Buffer.isBuffer(target)) { throw new TypeError( 'The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + (typeof target) ) } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 let x = thisEnd - thisStart let y = end - start const len = Math.min(x, y) const thisCopy = this.slice(thisStart, thisEnd) const targetCopy = target.slice(start, end) for (let i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (numberIsNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { let indexSize = 1 let arrLength = arr.length let valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } let i if (dir) { let foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { let found = true for (let j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 const remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } const strLen = string.length if (length > strLen / 2) { length = strLen / 2 } let i for (i = 0; i < length; ++i) { const parsed = parseInt(string.substr(i * 2, 2), 16) if (numberIsNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0 if (isFinite(length)) { length = length >>> 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } const remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' let loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': case 'latin1': case 'binary': return asciiWrite(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) const res = [] let i = start while (i < end) { const firstByte = buf[i] let codePoint = null let bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { let secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety const MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { const len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". let res = '' let i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { let ret = '' end = Math.min(buf.length, end) for (let i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { let ret = '' end = Math.min(buf.length, end) for (let i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { const len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len let out = '' for (let i = start; i < end; ++i) { out += hexSliceLookupTable[buf[i]] } return out } function utf16leSlice (buf, start, end) { const bytes = buf.slice(start, end) let res = '' // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) for (let i = 0; i < bytes.length - 1; i += 2) { res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) } return res } Buffer.prototype.slice = function slice (start, end) { const len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start const newBuf = this.subarray(start, end) // Return an augmented `Uint8Array` instance Object.setPrototypeOf(newBuf, Buffer.prototype) return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUintLE = Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) let val = this[offset] let mul = 1 let i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } let val = this[offset + --byteLength] let mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) { offset = offset >>> 0 validateNumber(offset, 'offset') const first = this[offset] const last = this[offset + 7] if (first === undefined || last === undefined) { boundsError(offset, this.length - 8) } const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24 const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24 return BigInt(lo) + (BigInt(hi) << BigInt(32)) }) Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) { offset = offset >>> 0 validateNumber(offset, 'offset') const first = this[offset] const last = this[offset + 7] if (first === undefined || last === undefined) { boundsError(offset, this.length - 8) } const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset] const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last return (BigInt(hi) << BigInt(32)) + BigInt(lo) }) Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) let val = this[offset] let mul = 1 let i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) let i = byteLength let mul = 1 let val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) const val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) const val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) { offset = offset >>> 0 validateNumber(offset, 'offset') const first = this[offset] const last = this[offset + 7] if (first === undefined || last === undefined) { boundsError(offset, this.length - 8) } const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24) // Overflow return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24) }) Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) { offset = offset >>> 0 validateNumber(offset, 'offset') const first = this[offset] const last = this[offset + 7] if (first === undefined || last === undefined) { boundsError(offset, this.length - 8) } const val = (first << 24) + // Overflow this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset] return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last) }) Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUintLE = Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { const maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } let mul = 1 let i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { const maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } let i = byteLength - 1 let mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) return offset + 4 } Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } function wrtBigUInt64LE (buf, value, offset, min, max) { checkIntBI(value, min, max, buf, offset, 7) let lo = Number(value & BigInt(0xffffffff)) buf[offset++] = lo lo = lo >> 8 buf[offset++] = lo lo = lo >> 8 buf[offset++] = lo lo = lo >> 8 buf[offset++] = lo let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) buf[offset++] = hi hi = hi >> 8 buf[offset++] = hi hi = hi >> 8 buf[offset++] = hi hi = hi >> 8 buf[offset++] = hi return offset } function wrtBigUInt64BE (buf, value, offset, min, max) { checkIntBI(value, min, max, buf, offset, 7) let lo = Number(value & BigInt(0xffffffff)) buf[offset + 7] = lo lo = lo >> 8 buf[offset + 6] = lo lo = lo >> 8 buf[offset + 5] = lo lo = lo >> 8 buf[offset + 4] = lo let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) buf[offset + 3] = hi hi = hi >> 8 buf[offset + 2] = hi hi = hi >> 8 buf[offset + 1] = hi hi = hi >> 8 buf[offset] = hi return offset + 8 } Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) { return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) }) Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) { return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) }) Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { const limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } let i = 0 let mul = 1 let sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { const limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } let i = byteLength - 1 let mul = 1 let sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) { return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) }) Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) { return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) }) function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('Index out of range') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } const len = end - start if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { // Use built-in when available, missing from IE11 this.copyWithin(targetStart, start, end) } else { Uint8Array.prototype.set.call( target, this.subarray(start, end), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } if (val.length === 1) { const code = val.charCodeAt(0) if ((encoding === 'utf8' && code < 128) || encoding === 'latin1') { // Fast path: If `val` fits into a single byte, use that numeric value. val = code } } } else if (typeof val === 'number') { val = val & 255 } else if (typeof val === 'boolean') { val = Number(val) } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 let i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { const bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding) const len = bytes.length if (len === 0) { throw new TypeError('The value "' + val + '" is invalid for argument "value"') } for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // CUSTOM ERRORS // ============= // Simplified versions from Node, changed for Buffer-only usage const errors = {} function E (sym, getMessage, Base) { errors[sym] = class NodeError extends Base { constructor () { super() Object.defineProperty(this, 'message', { value: getMessage.apply(this, arguments), writable: true, configurable: true }) // Add the error code to the name to include it in the stack trace. this.name = `${this.name} [${sym}]` // Access the stack to generate the error message including the error code // from the name. this.stack // eslint-disable-line no-unused-expressions // Reset the name to the actual name. delete this.name } get code () { return sym } set code (value) { Object.defineProperty(this, 'code', { configurable: true, enumerable: true, value, writable: true }) } toString () { return `${this.name} [${sym}]: ${this.message}` } } } E('ERR_BUFFER_OUT_OF_BOUNDS', function (name) { if (name) { return `${name} is outside of buffer bounds` } return 'Attempt to access memory outside buffer bounds' }, RangeError) E('ERR_INVALID_ARG_TYPE', function (name, actual) { return `The "${name}" argument must be of type number. Received type ${typeof actual}` }, TypeError) E('ERR_OUT_OF_RANGE', function (str, range, input) { let msg = `The value of "${str}" is out of range.` let received = input if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { received = addNumericalSeparator(String(input)) } else if (typeof input === 'bigint') { received = String(input) if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { received = addNumericalSeparator(received) } received += 'n' } msg += ` It must be ${range}. Received ${received}` return msg }, RangeError) function addNumericalSeparator (val) { let res = '' let i = val.length const start = val[0] === '-' ? 1 : 0 for (; i >= start + 4; i -= 3) { res = `_${val.slice(i - 3, i)}${res}` } return `${val.slice(0, i)}${res}` } // CHECK FUNCTIONS // =============== function checkBounds (buf, offset, byteLength) { validateNumber(offset, 'offset') if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { boundsError(offset, buf.length - (byteLength + 1)) } } function checkIntBI (value, min, max, buf, offset, byteLength) { if (value > max || value < min) { const n = typeof min === 'bigint' ? 'n' : '' let range if (byteLength > 3) { if (min === 0 || min === BigInt(0)) { range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}` } else { range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + `${(byteLength + 1) * 8 - 1}${n}` } } else { range = `>= ${min}${n} and <= ${max}${n}` } throw new errors.ERR_OUT_OF_RANGE('value', range, value) } checkBounds(buf, offset, byteLength) } function validateNumber (value, name) { if (typeof value !== 'number') { throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value) } } function boundsError (value, length, type) { if (Math.floor(value) !== value) { validateNumber(value, type) throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value) } if (length < 0) { throw new errors.ERR_BUFFER_OUT_OF_BOUNDS() } throw new errors.ERR_OUT_OF_RANGE(type || 'offset', `>= ${type ? 1 : 0} and <= ${length}`, value) } // HELPER FUNCTIONS // ================ const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g function base64clean (str) { // Node takes equal signs as end of the Base64 encoding str = str.split('=')[0] // Node strips out invalid characters like \n and \t from the string, base64-js does not str = str.trim().replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function utf8ToBytes (string, units) { units = units || Infinity let codePoint const length = string.length let leadSurrogate = null const bytes = [] for (let i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { const byteArray = [] for (let i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { let c, hi, lo const byteArray = [] for (let i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { let i for (i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass // the `instanceof` check but they should be treated as of that type. // See: https://github.com/feross/buffer/issues/166 function isInstance (obj, type) { return obj instanceof type || (obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name) } function numberIsNaN (obj) { // For IE11 support return obj !== obj // eslint-disable-line no-self-compare } // Create lookup table for `toString('hex')` // See: https://github.com/feross/buffer/issues/219 const hexSliceLookupTable = (function () { const alphabet = '0123456789abcdef' const table = new Array(256) for (let i = 0; i < 16; ++i) { const i16 = i * 16 for (let j = 0; j < 16; ++j) { table[i16 + j] = alphabet[i] + alphabet[j] } } return table })() // Return not function with Error if BigInt not supported function defineBigIntMethod (fn) { return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn } function BufferBigIntNotDefined () { throw new Error('BigInt not supported') } /***/ }), /***/ 1924: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var GetIntrinsic = __webpack_require__(210); var callBind = __webpack_require__(5559); var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); module.exports = function callBoundIntrinsic(name, allowMissing) { var intrinsic = GetIntrinsic(name, !!allowMissing); if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { return callBind(intrinsic); } return intrinsic; }; /***/ }), /***/ 5559: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var bind = __webpack_require__(8612); var GetIntrinsic = __webpack_require__(210); var $apply = GetIntrinsic('%Function.prototype.apply%'); var $call = GetIntrinsic('%Function.prototype.call%'); var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); var $max = GetIntrinsic('%Math.max%'); if ($defineProperty) { try { $defineProperty({}, 'a', { value: 1 }); } catch (e) { // IE 8 has a broken defineProperty $defineProperty = null; } } module.exports = function callBind(originalFunction) { var func = $reflectApply(bind, $call, arguments); if ($gOPD && $defineProperty) { var desc = $gOPD(func, 'length'); if (desc.configurable) { // original length, plus the receiver, minus any additional arguments (after the receiver) $defineProperty( func, 'length', { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } ); } } return func; }; var applyBind = function applyBind() { return $reflectApply(bind, $apply, arguments); }; if ($defineProperty) { $defineProperty(module.exports, 'apply', { value: applyBind }); } else { module.exports.apply = applyBind; } /***/ }), /***/ 6957: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var nextTick = __webpack_require__(886) exports.fromCallback = function (callback, symbol) { if (callback === undefined) { var promise = new Promise(function (resolve, reject) { callback = function (err, res) { if (err) reject(err) else resolve(res) } }) callback[symbol !== undefined ? symbol : 'promise'] = promise } else if (typeof callback !== 'function') { throw new TypeError('Callback must be a function') } return callback } exports.fromPromise = function (promise, callback) { if (callback === undefined) return promise promise .then(function (res) { nextTick(() => callback(null, res)) }) .catch(function (err) { nextTick(() => callback(err)) }) } /***/ }), /***/ 886: /***/ (function(module) { module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn) /***/ }), /***/ 6266: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var elliptic = exports; elliptic.version = (__webpack_require__(8597)/* .version */ .i8); elliptic.utils = __webpack_require__(953); elliptic.rand = __webpack_require__(9931); elliptic.curve = __webpack_require__(8254); elliptic.curves = __webpack_require__(5427); // Protocols elliptic.ec = __webpack_require__(7954); elliptic.eddsa = __webpack_require__(5980); /***/ }), /***/ 4918: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var BN = __webpack_require__(3550); var utils = __webpack_require__(953); var getNAF = utils.getNAF; var getJSF = utils.getJSF; var assert = utils.assert; function BaseCurve(type, conf) { this.type = type; this.p = new BN(conf.p, 16); // Use Montgomery, when there is no fast reduction for the prime this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); // Useful for many curves this.zero = new BN(0).toRed(this.red); this.one = new BN(1).toRed(this.red); this.two = new BN(2).toRed(this.red); // Curve configuration, optional this.n = conf.n && new BN(conf.n, 16); this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); // Temporary arrays this._wnafT1 = new Array(4); this._wnafT2 = new Array(4); this._wnafT3 = new Array(4); this._wnafT4 = new Array(4); this._bitLength = this.n ? this.n.bitLength() : 0; // Generalized Greg Maxwell's trick var adjustCount = this.n && this.p.div(this.n); if (!adjustCount || adjustCount.cmpn(100) > 0) { this.redN = null; } else { this._maxwellTrick = true; this.redN = this.n.toRed(this.red); } } module.exports = BaseCurve; BaseCurve.prototype.point = function point() { throw new Error('Not implemented'); }; BaseCurve.prototype.validate = function validate() { throw new Error('Not implemented'); }; BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { assert(p.precomputed); var doubles = p._getDoubles(); var naf = getNAF(k, 1, this._bitLength); var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); I /= 3; // Translate into more windowed form var repr = []; var j; var nafW; for (j = 0; j < naf.length; j += doubles.step) { nafW = 0; for (var l = j + doubles.step - 1; l >= j; l--) nafW = (nafW << 1) + naf[l]; repr.push(nafW); } var a = this.jpoint(null, null, null); var b = this.jpoint(null, null, null); for (var i = I; i > 0; i--) { for (j = 0; j < repr.length; j++) { nafW = repr[j]; if (nafW === i) b = b.mixedAdd(doubles.points[j]); else if (nafW === -i) b = b.mixedAdd(doubles.points[j].neg()); } a = a.add(b); } return a.toP(); }; BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { var w = 4; // Precompute window var nafPoints = p._getNAFPoints(w); w = nafPoints.wnd; var wnd = nafPoints.points; // Get NAF form var naf = getNAF(k, w, this._bitLength); // Add `this`*(N+1) for every w-NAF index var acc = this.jpoint(null, null, null); for (var i = naf.length - 1; i >= 0; i--) { // Count zeroes for (var l = 0; i >= 0 && naf[i] === 0; i--) l++; if (i >= 0) l++; acc = acc.dblp(l); if (i < 0) break; var z = naf[i]; assert(z !== 0); if (p.type === 'affine') { // J +- P if (z > 0) acc = acc.mixedAdd(wnd[(z - 1) >> 1]); else acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); } else { // J +- J if (z > 0) acc = acc.add(wnd[(z - 1) >> 1]); else acc = acc.add(wnd[(-z - 1) >> 1].neg()); } } return p.type === 'affine' ? acc.toP() : acc; }; BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, points, coeffs, len, jacobianResult) { var wndWidth = this._wnafT1; var wnd = this._wnafT2; var naf = this._wnafT3; // Fill all arrays var max = 0; var i; var j; var p; for (i = 0; i < len; i++) { p = points[i]; var nafPoints = p._getNAFPoints(defW); wndWidth[i] = nafPoints.wnd; wnd[i] = nafPoints.points; } // Comb small window NAFs for (i = len - 1; i >= 1; i -= 2) { var a = i - 1; var b = i; if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength); naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength); max = Math.max(naf[a].length, max); max = Math.max(naf[b].length, max); continue; } var comb = [ points[a], /* 1 */ null, /* 3 */ null, /* 5 */ points[b], /* 7 */ ]; // Try to avoid Projective points, if possible if (points[a].y.cmp(points[b].y) === 0) { comb[1] = points[a].add(points[b]); comb[2] = points[a].toJ().mixedAdd(points[b].neg()); } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { comb[1] = points[a].toJ().mixedAdd(points[b]); comb[2] = points[a].add(points[b].neg()); } else { comb[1] = points[a].toJ().mixedAdd(points[b]); comb[2] = points[a].toJ().mixedAdd(points[b].neg()); } var index = [ -3, /* -1 -1 */ -1, /* -1 0 */ -5, /* -1 1 */ -7, /* 0 -1 */ 0, /* 0 0 */ 7, /* 0 1 */ 5, /* 1 -1 */ 1, /* 1 0 */ 3, /* 1 1 */ ]; var jsf = getJSF(coeffs[a], coeffs[b]); max = Math.max(jsf[0].length, max); naf[a] = new Array(max); naf[b] = new Array(max); for (j = 0; j < max; j++) { var ja = jsf[0][j] | 0; var jb = jsf[1][j] | 0; naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; naf[b][j] = 0; wnd[a] = comb; } } var acc = this.jpoint(null, null, null); var tmp = this._wnafT4; for (i = max; i >= 0; i--) { var k = 0; while (i >= 0) { var zero = true; for (j = 0; j < len; j++) { tmp[j] = naf[j][i] | 0; if (tmp[j] !== 0) zero = false; } if (!zero) break; k++; i--; } if (i >= 0) k++; acc = acc.dblp(k); if (i < 0) break; for (j = 0; j < len; j++) { var z = tmp[j]; p; if (z === 0) continue; else if (z > 0) p = wnd[j][(z - 1) >> 1]; else if (z < 0) p = wnd[j][(-z - 1) >> 1].neg(); if (p.type === 'affine') acc = acc.mixedAdd(p); else acc = acc.add(p); } } // Zeroify references for (i = 0; i < len; i++) wnd[i] = null; if (jacobianResult) return acc; else return acc.toP(); }; function BasePoint(curve, type) { this.curve = curve; this.type = type; this.precomputed = null; } BaseCurve.BasePoint = BasePoint; BasePoint.prototype.eq = function eq(/*other*/) { throw new Error('Not implemented'); }; BasePoint.prototype.validate = function validate() { return this.curve.validate(this); }; BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { bytes = utils.toArray(bytes, enc); var len = this.p.byteLength(); // uncompressed, hybrid-odd, hybrid-even if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && bytes.length - 1 === 2 * len) { if (bytes[0] === 0x06) assert(bytes[bytes.length - 1] % 2 === 0); else if (bytes[0] === 0x07) assert(bytes[bytes.length - 1] % 2 === 1); var res = this.point(bytes.slice(1, 1 + len), bytes.slice(1 + len, 1 + 2 * len)); return res; } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && bytes.length - 1 === len) { return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); } throw new Error('Unknown point format'); }; BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { return this.encode(enc, true); }; BasePoint.prototype._encode = function _encode(compact) { var len = this.curve.p.byteLength(); var x = this.getX().toArray('be', len); if (compact) return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); return [ 0x04 ].concat(x, this.getY().toArray('be', len)); }; BasePoint.prototype.encode = function encode(enc, compact) { return utils.encode(this._encode(compact), enc); }; BasePoint.prototype.precompute = function precompute(power) { if (this.precomputed) return this; var precomputed = { doubles: null, naf: null, beta: null, }; precomputed.naf = this._getNAFPoints(8); precomputed.doubles = this._getDoubles(4, power); precomputed.beta = this._getBeta(); this.precomputed = precomputed; return this; }; BasePoint.prototype._hasDoubles = function _hasDoubles(k) { if (!this.precomputed) return false; var doubles = this.precomputed.doubles; if (!doubles) return false; return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); }; BasePoint.prototype._getDoubles = function _getDoubles(step, power) { if (this.precomputed && this.precomputed.doubles) return this.precomputed.doubles; var doubles = [ this ]; var acc = this; for (var i = 0; i < power; i += step) { for (var j = 0; j < step; j++) acc = acc.dbl(); doubles.push(acc); } return { step: step, points: doubles, }; }; BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { if (this.precomputed && this.precomputed.naf) return this.precomputed.naf; var res = [ this ]; var max = (1 << wnd) - 1; var dbl = max === 1 ? null : this.dbl(); for (var i = 1; i < max; i++) res[i] = res[i - 1].add(dbl); return { wnd: wnd, points: res, }; }; BasePoint.prototype._getBeta = function _getBeta() { return null; }; BasePoint.prototype.dblp = function dblp(k) { var r = this; for (var i = 0; i < k; i++) r = r.dbl(); return r; }; /***/ }), /***/ 1138: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(953); var BN = __webpack_require__(3550); var inherits = __webpack_require__(5717); var Base = __webpack_require__(4918); var assert = utils.assert; function EdwardsCurve(conf) { // NOTE: Important as we are creating point in Base.call() this.twisted = (conf.a | 0) !== 1; this.mOneA = this.twisted && (conf.a | 0) === -1; this.extended = this.mOneA; Base.call(this, 'edwards', conf); this.a = new BN(conf.a, 16).umod(this.red.m); this.a = this.a.toRed(this.red); this.c = new BN(conf.c, 16).toRed(this.red); this.c2 = this.c.redSqr(); this.d = new BN(conf.d, 16).toRed(this.red); this.dd = this.d.redAdd(this.d); assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); this.oneC = (conf.c | 0) === 1; } inherits(EdwardsCurve, Base); module.exports = EdwardsCurve; EdwardsCurve.prototype._mulA = function _mulA(num) { if (this.mOneA) return num.redNeg(); else return this.a.redMul(num); }; EdwardsCurve.prototype._mulC = function _mulC(num) { if (this.oneC) return num; else return this.c.redMul(num); }; // Just for compatibility with Short curve EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { return this.point(x, y, z, t); }; EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { x = new BN(x, 16); if (!x.red) x = x.toRed(this.red); var x2 = x.redSqr(); var rhs = this.c2.redSub(this.a.redMul(x2)); var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); var y2 = rhs.redMul(lhs.redInvm()); var y = y2.redSqrt(); if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error('invalid point'); var isOdd = y.fromRed().isOdd(); if (odd && !isOdd || !odd && isOdd) y = y.redNeg(); return this.point(x, y); }; EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { y = new BN(y, 16); if (!y.red) y = y.toRed(this.red); // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) var y2 = y.redSqr(); var lhs = y2.redSub(this.c2); var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); var x2 = lhs.redMul(rhs.redInvm()); if (x2.cmp(this.zero) === 0) { if (odd) throw new Error('invalid point'); else return this.point(this.zero, y); } var x = x2.redSqrt(); if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) throw new Error('invalid point'); if (x.fromRed().isOdd() !== odd) x = x.redNeg(); return this.point(x, y); }; EdwardsCurve.prototype.validate = function validate(point) { if (point.isInfinity()) return true; // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) point.normalize(); var x2 = point.x.redSqr(); var y2 = point.y.redSqr(); var lhs = x2.redMul(this.a).redAdd(y2); var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); return lhs.cmp(rhs) === 0; }; function Point(curve, x, y, z, t) { Base.BasePoint.call(this, curve, 'projective'); if (x === null && y === null && z === null) { this.x = this.curve.zero; this.y = this.curve.one; this.z = this.curve.one; this.t = this.curve.zero; this.zOne = true; } else { this.x = new BN(x, 16); this.y = new BN(y, 16); this.z = z ? new BN(z, 16) : this.curve.one; this.t = t && new BN(t, 16); if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); if (!this.z.red) this.z = this.z.toRed(this.curve.red); if (this.t && !this.t.red) this.t = this.t.toRed(this.curve.red); this.zOne = this.z === this.curve.one; // Use extended coordinates if (this.curve.extended && !this.t) { this.t = this.x.redMul(this.y); if (!this.zOne) this.t = this.t.redMul(this.z.redInvm()); } } } inherits(Point, Base.BasePoint); EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { return Point.fromJSON(this, obj); }; EdwardsCurve.prototype.point = function point(x, y, z, t) { return new Point(this, x, y, z, t); }; Point.fromJSON = function fromJSON(curve, obj) { return new Point(curve, obj[0], obj[1], obj[2]); }; Point.prototype.inspect = function inspect() { if (this.isInfinity()) return ''; return ''; }; Point.prototype.isInfinity = function isInfinity() { // XXX This code assumes that zero is always zero in red return this.x.cmpn(0) === 0 && (this.y.cmp(this.z) === 0 || (this.zOne && this.y.cmp(this.curve.c) === 0)); }; Point.prototype._extDbl = function _extDbl() { // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html // #doubling-dbl-2008-hwcd // 4M + 4S // A = X1^2 var a = this.x.redSqr(); // B = Y1^2 var b = this.y.redSqr(); // C = 2 * Z1^2 var c = this.z.redSqr(); c = c.redIAdd(c); // D = a * A var d = this.curve._mulA(a); // E = (X1 + Y1)^2 - A - B var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); // G = D + B var g = d.redAdd(b); // F = G - C var f = g.redSub(c); // H = D - B var h = d.redSub(b); // X3 = E * F var nx = e.redMul(f); // Y3 = G * H var ny = g.redMul(h); // T3 = E * H var nt = e.redMul(h); // Z3 = F * G var nz = f.redMul(g); return this.curve.point(nx, ny, nz, nt); }; Point.prototype._projDbl = function _projDbl() { // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html // #doubling-dbl-2008-bbjlp // #doubling-dbl-2007-bl // and others // Generally 3M + 4S or 2M + 4S // B = (X1 + Y1)^2 var b = this.x.redAdd(this.y).redSqr(); // C = X1^2 var c = this.x.redSqr(); // D = Y1^2 var d = this.y.redSqr(); var nx; var ny; var nz; var e; var h; var j; if (this.curve.twisted) { // E = a * C e = this.curve._mulA(c); // F = E + D var f = e.redAdd(d); if (this.zOne) { // X3 = (B - C - D) * (F - 2) nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); // Y3 = F * (E - D) ny = f.redMul(e.redSub(d)); // Z3 = F^2 - 2 * F nz = f.redSqr().redSub(f).redSub(f); } else { // H = Z1^2 h = this.z.redSqr(); // J = F - 2 * H j = f.redSub(h).redISub(h); // X3 = (B-C-D)*J nx = b.redSub(c).redISub(d).redMul(j); // Y3 = F * (E - D) ny = f.redMul(e.redSub(d)); // Z3 = F * J nz = f.redMul(j); } } else { // E = C + D e = c.redAdd(d); // H = (c * Z1)^2 h = this.curve._mulC(this.z).redSqr(); // J = E - 2 * H j = e.redSub(h).redSub(h); // X3 = c * (B - E) * J nx = this.curve._mulC(b.redISub(e)).redMul(j); // Y3 = c * E * (C - D) ny = this.curve._mulC(e).redMul(c.redISub(d)); // Z3 = E * J nz = e.redMul(j); } return this.curve.point(nx, ny, nz); }; Point.prototype.dbl = function dbl() { if (this.isInfinity()) return this; // Double in extended coordinates if (this.curve.extended) return this._extDbl(); else return this._projDbl(); }; Point.prototype._extAdd = function _extAdd(p) { // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html // #addition-add-2008-hwcd-3 // 8M // A = (Y1 - X1) * (Y2 - X2) var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); // B = (Y1 + X1) * (Y2 + X2) var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); // C = T1 * k * T2 var c = this.t.redMul(this.curve.dd).redMul(p.t); // D = Z1 * 2 * Z2 var d = this.z.redMul(p.z.redAdd(p.z)); // E = B - A var e = b.redSub(a); // F = D - C var f = d.redSub(c); // G = D + C var g = d.redAdd(c); // H = B + A var h = b.redAdd(a); // X3 = E * F var nx = e.redMul(f); // Y3 = G * H var ny = g.redMul(h); // T3 = E * H var nt = e.redMul(h); // Z3 = F * G var nz = f.redMul(g); return this.curve.point(nx, ny, nz, nt); }; Point.prototype._projAdd = function _projAdd(p) { // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html // #addition-add-2008-bbjlp // #addition-add-2007-bl // 10M + 1S // A = Z1 * Z2 var a = this.z.redMul(p.z); // B = A^2 var b = a.redSqr(); // C = X1 * X2 var c = this.x.redMul(p.x); // D = Y1 * Y2 var d = this.y.redMul(p.y); // E = d * C * D var e = this.curve.d.redMul(c).redMul(d); // F = B - E var f = b.redSub(e); // G = B + E var g = b.redAdd(e); // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); var nx = a.redMul(f).redMul(tmp); var ny; var nz; if (this.curve.twisted) { // Y3 = A * G * (D - a * C) ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); // Z3 = F * G nz = f.redMul(g); } else { // Y3 = A * G * (D - C) ny = a.redMul(g).redMul(d.redSub(c)); // Z3 = c * F * G nz = this.curve._mulC(f).redMul(g); } return this.curve.point(nx, ny, nz); }; Point.prototype.add = function add(p) { if (this.isInfinity()) return p; if (p.isInfinity()) return this; if (this.curve.extended) return this._extAdd(p); else return this._projAdd(p); }; Point.prototype.mul = function mul(k) { if (this._hasDoubles(k)) return this.curve._fixedNafMul(this, k); else return this.curve._wnafMul(this, k); }; Point.prototype.mulAdd = function mulAdd(k1, p, k2) { return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); }; Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); }; Point.prototype.normalize = function normalize() { if (this.zOne) return this; // Normalize coordinates var zi = this.z.redInvm(); this.x = this.x.redMul(zi); this.y = this.y.redMul(zi); if (this.t) this.t = this.t.redMul(zi); this.z = this.curve.one; this.zOne = true; return this; }; Point.prototype.neg = function neg() { return this.curve.point(this.x.redNeg(), this.y, this.z, this.t && this.t.redNeg()); }; Point.prototype.getX = function getX() { this.normalize(); return this.x.fromRed(); }; Point.prototype.getY = function getY() { this.normalize(); return this.y.fromRed(); }; Point.prototype.eq = function eq(other) { return this === other || this.getX().cmp(other.getX()) === 0 && this.getY().cmp(other.getY()) === 0; }; Point.prototype.eqXToP = function eqXToP(x) { var rx = x.toRed(this.curve.red).redMul(this.z); if (this.x.cmp(rx) === 0) return true; var xc = x.clone(); var t = this.curve.redN.redMul(this.z); for (;;) { xc.iadd(this.curve.n); if (xc.cmp(this.curve.p) >= 0) return false; rx.redIAdd(t); if (this.x.cmp(rx) === 0) return true; } }; // Compatibility with BaseCurve Point.prototype.toP = Point.prototype.normalize; Point.prototype.mixedAdd = Point.prototype.add; /***/ }), /***/ 8254: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var curve = exports; curve.base = __webpack_require__(4918); curve.short = __webpack_require__(6673); curve.mont = __webpack_require__(2881); curve.edwards = __webpack_require__(1138); /***/ }), /***/ 2881: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var BN = __webpack_require__(3550); var inherits = __webpack_require__(5717); var Base = __webpack_require__(4918); var utils = __webpack_require__(953); function MontCurve(conf) { Base.call(this, 'mont', conf); this.a = new BN(conf.a, 16).toRed(this.red); this.b = new BN(conf.b, 16).toRed(this.red); this.i4 = new BN(4).toRed(this.red).redInvm(); this.two = new BN(2).toRed(this.red); this.a24 = this.i4.redMul(this.a.redAdd(this.two)); } inherits(MontCurve, Base); module.exports = MontCurve; MontCurve.prototype.validate = function validate(point) { var x = point.normalize().x; var x2 = x.redSqr(); var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); var y = rhs.redSqrt(); return y.redSqr().cmp(rhs) === 0; }; function Point(curve, x, z) { Base.BasePoint.call(this, curve, 'projective'); if (x === null && z === null) { this.x = this.curve.one; this.z = this.curve.zero; } else { this.x = new BN(x, 16); this.z = new BN(z, 16); if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.z.red) this.z = this.z.toRed(this.curve.red); } } inherits(Point, Base.BasePoint); MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { return this.point(utils.toArray(bytes, enc), 1); }; MontCurve.prototype.point = function point(x, z) { return new Point(this, x, z); }; MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { return Point.fromJSON(this, obj); }; Point.prototype.precompute = function precompute() { // No-op }; Point.prototype._encode = function _encode() { return this.getX().toArray('be', this.curve.p.byteLength()); }; Point.fromJSON = function fromJSON(curve, obj) { return new Point(curve, obj[0], obj[1] || curve.one); }; Point.prototype.inspect = function inspect() { if (this.isInfinity()) return ''; return ''; }; Point.prototype.isInfinity = function isInfinity() { // XXX This code assumes that zero is always zero in red return this.z.cmpn(0) === 0; }; Point.prototype.dbl = function dbl() { // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 // 2M + 2S + 4A // A = X1 + Z1 var a = this.x.redAdd(this.z); // AA = A^2 var aa = a.redSqr(); // B = X1 - Z1 var b = this.x.redSub(this.z); // BB = B^2 var bb = b.redSqr(); // C = AA - BB var c = aa.redSub(bb); // X3 = AA * BB var nx = aa.redMul(bb); // Z3 = C * (BB + A24 * C) var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); return this.curve.point(nx, nz); }; Point.prototype.add = function add() { throw new Error('Not supported on Montgomery curve'); }; Point.prototype.diffAdd = function diffAdd(p, diff) { // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 // 4M + 2S + 6A // A = X2 + Z2 var a = this.x.redAdd(this.z); // B = X2 - Z2 var b = this.x.redSub(this.z); // C = X3 + Z3 var c = p.x.redAdd(p.z); // D = X3 - Z3 var d = p.x.redSub(p.z); // DA = D * A var da = d.redMul(a); // CB = C * B var cb = c.redMul(b); // X5 = Z1 * (DA + CB)^2 var nx = diff.z.redMul(da.redAdd(cb).redSqr()); // Z5 = X1 * (DA - CB)^2 var nz = diff.x.redMul(da.redISub(cb).redSqr()); return this.curve.point(nx, nz); }; Point.prototype.mul = function mul(k) { var t = k.clone(); var a = this; // (N / 2) * Q + Q var b = this.curve.point(null, null); // (N / 2) * Q var c = this; // Q for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) bits.push(t.andln(1)); for (var i = bits.length - 1; i >= 0; i--) { if (bits[i] === 0) { // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q a = a.diffAdd(b, c); // N * Q = 2 * ((N / 2) * Q + Q)) b = b.dbl(); } else { // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) b = a.diffAdd(b, c); // N * Q + Q = 2 * ((N / 2) * Q + Q) a = a.dbl(); } } return b; }; Point.prototype.mulAdd = function mulAdd() { throw new Error('Not supported on Montgomery curve'); }; Point.prototype.jumlAdd = function jumlAdd() { throw new Error('Not supported on Montgomery curve'); }; Point.prototype.eq = function eq(other) { return this.getX().cmp(other.getX()) === 0; }; Point.prototype.normalize = function normalize() { this.x = this.x.redMul(this.z.redInvm()); this.z = this.curve.one; return this; }; Point.prototype.getX = function getX() { // Normalize coordinates this.normalize(); return this.x.fromRed(); }; /***/ }), /***/ 6673: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(953); var BN = __webpack_require__(3550); var inherits = __webpack_require__(5717); var Base = __webpack_require__(4918); var assert = utils.assert; function ShortCurve(conf) { Base.call(this, 'short', conf); this.a = new BN(conf.a, 16).toRed(this.red); this.b = new BN(conf.b, 16).toRed(this.red); this.tinv = this.two.redInvm(); this.zeroA = this.a.fromRed().cmpn(0) === 0; this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; // If the curve is endomorphic, precalculate beta and lambda this.endo = this._getEndomorphism(conf); this._endoWnafT1 = new Array(4); this._endoWnafT2 = new Array(4); } inherits(ShortCurve, Base); module.exports = ShortCurve; ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { // No efficient endomorphism if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) return; // Compute beta and lambda, that lambda * P = (beta * Px; Py) var beta; var lambda; if (conf.beta) { beta = new BN(conf.beta, 16).toRed(this.red); } else { var betas = this._getEndoRoots(this.p); // Choose the smallest beta beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; beta = beta.toRed(this.red); } if (conf.lambda) { lambda = new BN(conf.lambda, 16); } else { // Choose the lambda that is matching selected beta var lambdas = this._getEndoRoots(this.n); if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { lambda = lambdas[0]; } else { lambda = lambdas[1]; assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); } } // Get basis vectors, used for balanced length-two representation var basis; if (conf.basis) { basis = conf.basis.map(function(vec) { return { a: new BN(vec.a, 16), b: new BN(vec.b, 16), }; }); } else { basis = this._getEndoBasis(lambda); } return { beta: beta, lambda: lambda, basis: basis, }; }; ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { // Find roots of for x^2 + x + 1 in F // Root = (-1 +- Sqrt(-3)) / 2 // var red = num === this.p ? this.red : BN.mont(num); var tinv = new BN(2).toRed(red).redInvm(); var ntinv = tinv.redNeg(); var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); var l1 = ntinv.redAdd(s).fromRed(); var l2 = ntinv.redSub(s).fromRed(); return [ l1, l2 ]; }; ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { // aprxSqrt >= sqrt(this.n) var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); // 3.74 // Run EGCD, until r(L + 1) < aprxSqrt var u = lambda; var v = this.n.clone(); var x1 = new BN(1); var y1 = new BN(0); var x2 = new BN(0); var y2 = new BN(1); // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) var a0; var b0; // First vector var a1; var b1; // Second vector var a2; var b2; var prevR; var i = 0; var r; var x; while (u.cmpn(0) !== 0) { var q = v.div(u); r = v.sub(q.mul(u)); x = x2.sub(q.mul(x1)); var y = y2.sub(q.mul(y1)); if (!a1 && r.cmp(aprxSqrt) < 0) { a0 = prevR.neg(); b0 = x1; a1 = r.neg(); b1 = x; } else if (a1 && ++i === 2) { break; } prevR = r; v = u; u = r; x2 = x1; x1 = x; y2 = y1; y1 = y; } a2 = r.neg(); b2 = x; var len1 = a1.sqr().add(b1.sqr()); var len2 = a2.sqr().add(b2.sqr()); if (len2.cmp(len1) >= 0) { a2 = a0; b2 = b0; } // Normalize signs if (a1.negative) { a1 = a1.neg(); b1 = b1.neg(); } if (a2.negative) { a2 = a2.neg(); b2 = b2.neg(); } return [ { a: a1, b: b1 }, { a: a2, b: b2 }, ]; }; ShortCurve.prototype._endoSplit = function _endoSplit(k) { var basis = this.endo.basis; var v1 = basis[0]; var v2 = basis[1]; var c1 = v2.b.mul(k).divRound(this.n); var c2 = v1.b.neg().mul(k).divRound(this.n); var p1 = c1.mul(v1.a); var p2 = c2.mul(v2.a); var q1 = c1.mul(v1.b); var q2 = c2.mul(v2.b); // Calculate answer var k1 = k.sub(p1).sub(p2); var k2 = q1.add(q2).neg(); return { k1: k1, k2: k2 }; }; ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { x = new BN(x, 16); if (!x.red) x = x.toRed(this.red); var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); var y = y2.redSqrt(); if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error('invalid point'); // XXX Is there any way to tell if the number is odd without converting it // to non-red form? var isOdd = y.fromRed().isOdd(); if (odd && !isOdd || !odd && isOdd) y = y.redNeg(); return this.point(x, y); }; ShortCurve.prototype.validate = function validate(point) { if (point.inf) return true; var x = point.x; var y = point.y; var ax = this.a.redMul(x); var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); return y.redSqr().redISub(rhs).cmpn(0) === 0; }; ShortCurve.prototype._endoWnafMulAdd = function _endoWnafMulAdd(points, coeffs, jacobianResult) { var npoints = this._endoWnafT1; var ncoeffs = this._endoWnafT2; for (var i = 0; i < points.length; i++) { var split = this._endoSplit(coeffs[i]); var p = points[i]; var beta = p._getBeta(); if (split.k1.negative) { split.k1.ineg(); p = p.neg(true); } if (split.k2.negative) { split.k2.ineg(); beta = beta.neg(true); } npoints[i * 2] = p; npoints[i * 2 + 1] = beta; ncoeffs[i * 2] = split.k1; ncoeffs[i * 2 + 1] = split.k2; } var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); // Clean-up references to points and coefficients for (var j = 0; j < i * 2; j++) { npoints[j] = null; ncoeffs[j] = null; } return res; }; function Point(curve, x, y, isRed) { Base.BasePoint.call(this, curve, 'affine'); if (x === null && y === null) { this.x = null; this.y = null; this.inf = true; } else { this.x = new BN(x, 16); this.y = new BN(y, 16); // Force redgomery representation when loading from JSON if (isRed) { this.x.forceRed(this.curve.red); this.y.forceRed(this.curve.red); } if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); this.inf = false; } } inherits(Point, Base.BasePoint); ShortCurve.prototype.point = function point(x, y, isRed) { return new Point(this, x, y, isRed); }; ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { return Point.fromJSON(this, obj, red); }; Point.prototype._getBeta = function _getBeta() { if (!this.curve.endo) return; var pre = this.precomputed; if (pre && pre.beta) return pre.beta; var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); if (pre) { var curve = this.curve; var endoMul = function(p) { return curve.point(p.x.redMul(curve.endo.beta), p.y); }; pre.beta = beta; beta.precomputed = { beta: null, naf: pre.naf && { wnd: pre.naf.wnd, points: pre.naf.points.map(endoMul), }, doubles: pre.doubles && { step: pre.doubles.step, points: pre.doubles.points.map(endoMul), }, }; } return beta; }; Point.prototype.toJSON = function toJSON() { if (!this.precomputed) return [ this.x, this.y ]; return [ this.x, this.y, this.precomputed && { doubles: this.precomputed.doubles && { step: this.precomputed.doubles.step, points: this.precomputed.doubles.points.slice(1), }, naf: this.precomputed.naf && { wnd: this.precomputed.naf.wnd, points: this.precomputed.naf.points.slice(1), }, } ]; }; Point.fromJSON = function fromJSON(curve, obj, red) { if (typeof obj === 'string') obj = JSON.parse(obj); var res = curve.point(obj[0], obj[1], red); if (!obj[2]) return res; function obj2point(obj) { return curve.point(obj[0], obj[1], red); } var pre = obj[2]; res.precomputed = { beta: null, doubles: pre.doubles && { step: pre.doubles.step, points: [ res ].concat(pre.doubles.points.map(obj2point)), }, naf: pre.naf && { wnd: pre.naf.wnd, points: [ res ].concat(pre.naf.points.map(obj2point)), }, }; return res; }; Point.prototype.inspect = function inspect() { if (this.isInfinity()) return ''; return ''; }; Point.prototype.isInfinity = function isInfinity() { return this.inf; }; Point.prototype.add = function add(p) { // O + P = P if (this.inf) return p; // P + O = P if (p.inf) return this; // P + P = 2P if (this.eq(p)) return this.dbl(); // P + (-P) = O if (this.neg().eq(p)) return this.curve.point(null, null); // P + Q = O if (this.x.cmp(p.x) === 0) return this.curve.point(null, null); var c = this.y.redSub(p.y); if (c.cmpn(0) !== 0) c = c.redMul(this.x.redSub(p.x).redInvm()); var nx = c.redSqr().redISub(this.x).redISub(p.x); var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); return this.curve.point(nx, ny); }; Point.prototype.dbl = function dbl() { if (this.inf) return this; // 2P = O var ys1 = this.y.redAdd(this.y); if (ys1.cmpn(0) === 0) return this.curve.point(null, null); var a = this.curve.a; var x2 = this.x.redSqr(); var dyinv = ys1.redInvm(); var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); var nx = c.redSqr().redISub(this.x.redAdd(this.x)); var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); return this.curve.point(nx, ny); }; Point.prototype.getX = function getX() { return this.x.fromRed(); }; Point.prototype.getY = function getY() { return this.y.fromRed(); }; Point.prototype.mul = function mul(k) { k = new BN(k, 16); if (this.isInfinity()) return this; else if (this._hasDoubles(k)) return this.curve._fixedNafMul(this, k); else if (this.curve.endo) return this.curve._endoWnafMulAdd([ this ], [ k ]); else return this.curve._wnafMul(this, k); }; Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { var points = [ this, p2 ]; var coeffs = [ k1, k2 ]; if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs); else return this.curve._wnafMulAdd(1, points, coeffs, 2); }; Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { var points = [ this, p2 ]; var coeffs = [ k1, k2 ]; if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs, true); else return this.curve._wnafMulAdd(1, points, coeffs, 2, true); }; Point.prototype.eq = function eq(p) { return this === p || this.inf === p.inf && (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); }; Point.prototype.neg = function neg(_precompute) { if (this.inf) return this; var res = this.curve.point(this.x, this.y.redNeg()); if (_precompute && this.precomputed) { var pre = this.precomputed; var negate = function(p) { return p.neg(); }; res.precomputed = { naf: pre.naf && { wnd: pre.naf.wnd, points: pre.naf.points.map(negate), }, doubles: pre.doubles && { step: pre.doubles.step, points: pre.doubles.points.map(negate), }, }; } return res; }; Point.prototype.toJ = function toJ() { if (this.inf) return this.curve.jpoint(null, null, null); var res = this.curve.jpoint(this.x, this.y, this.curve.one); return res; }; function JPoint(curve, x, y, z) { Base.BasePoint.call(this, curve, 'jacobian'); if (x === null && y === null && z === null) { this.x = this.curve.one; this.y = this.curve.one; this.z = new BN(0); } else { this.x = new BN(x, 16); this.y = new BN(y, 16); this.z = new BN(z, 16); } if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); if (!this.z.red) this.z = this.z.toRed(this.curve.red); this.zOne = this.z === this.curve.one; } inherits(JPoint, Base.BasePoint); ShortCurve.prototype.jpoint = function jpoint(x, y, z) { return new JPoint(this, x, y, z); }; JPoint.prototype.toP = function toP() { if (this.isInfinity()) return this.curve.point(null, null); var zinv = this.z.redInvm(); var zinv2 = zinv.redSqr(); var ax = this.x.redMul(zinv2); var ay = this.y.redMul(zinv2).redMul(zinv); return this.curve.point(ax, ay); }; JPoint.prototype.neg = function neg() { return this.curve.jpoint(this.x, this.y.redNeg(), this.z); }; JPoint.prototype.add = function add(p) { // O + P = P if (this.isInfinity()) return p; // P + O = P if (p.isInfinity()) return this; // 12M + 4S + 7A var pz2 = p.z.redSqr(); var z2 = this.z.redSqr(); var u1 = this.x.redMul(pz2); var u2 = p.x.redMul(z2); var s1 = this.y.redMul(pz2.redMul(p.z)); var s2 = p.y.redMul(z2.redMul(this.z)); var h = u1.redSub(u2); var r = s1.redSub(s2); if (h.cmpn(0) === 0) { if (r.cmpn(0) !== 0) return this.curve.jpoint(null, null, null); else return this.dbl(); } var h2 = h.redSqr(); var h3 = h2.redMul(h); var v = u1.redMul(h2); var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); var nz = this.z.redMul(p.z).redMul(h); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.mixedAdd = function mixedAdd(p) { // O + P = P if (this.isInfinity()) return p.toJ(); // P + O = P if (p.isInfinity()) return this; // 8M + 3S + 7A var z2 = this.z.redSqr(); var u1 = this.x; var u2 = p.x.redMul(z2); var s1 = this.y; var s2 = p.y.redMul(z2).redMul(this.z); var h = u1.redSub(u2); var r = s1.redSub(s2); if (h.cmpn(0) === 0) { if (r.cmpn(0) !== 0) return this.curve.jpoint(null, null, null); else return this.dbl(); } var h2 = h.redSqr(); var h3 = h2.redMul(h); var v = u1.redMul(h2); var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); var nz = this.z.redMul(h); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.dblp = function dblp(pow) { if (pow === 0) return this; if (this.isInfinity()) return this; if (!pow) return this.dbl(); var i; if (this.curve.zeroA || this.curve.threeA) { var r = this; for (i = 0; i < pow; i++) r = r.dbl(); return r; } // 1M + 2S + 1A + N * (4S + 5M + 8A) // N = 1 => 6M + 6S + 9A var a = this.curve.a; var tinv = this.curve.tinv; var jx = this.x; var jy = this.y; var jz = this.z; var jz4 = jz.redSqr().redSqr(); // Reuse results var jyd = jy.redAdd(jy); for (i = 0; i < pow; i++) { var jx2 = jx.redSqr(); var jyd2 = jyd.redSqr(); var jyd4 = jyd2.redSqr(); var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); var t1 = jx.redMul(jyd2); var nx = c.redSqr().redISub(t1.redAdd(t1)); var t2 = t1.redISub(nx); var dny = c.redMul(t2); dny = dny.redIAdd(dny).redISub(jyd4); var nz = jyd.redMul(jz); if (i + 1 < pow) jz4 = jz4.redMul(jyd4); jx = nx; jz = nz; jyd = dny; } return this.curve.jpoint(jx, jyd.redMul(tinv), jz); }; JPoint.prototype.dbl = function dbl() { if (this.isInfinity()) return this; if (this.curve.zeroA) return this._zeroDbl(); else if (this.curve.threeA) return this._threeDbl(); else return this._dbl(); }; JPoint.prototype._zeroDbl = function _zeroDbl() { var nx; var ny; var nz; // Z = 1 if (this.zOne) { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html // #doubling-mdbl-2007-bl // 1M + 5S + 14A // XX = X1^2 var xx = this.x.redSqr(); // YY = Y1^2 var yy = this.y.redSqr(); // YYYY = YY^2 var yyyy = yy.redSqr(); // S = 2 * ((X1 + YY)^2 - XX - YYYY) var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); s = s.redIAdd(s); // M = 3 * XX + a; a = 0 var m = xx.redAdd(xx).redIAdd(xx); // T = M ^ 2 - 2*S var t = m.redSqr().redISub(s).redISub(s); // 8 * YYYY var yyyy8 = yyyy.redIAdd(yyyy); yyyy8 = yyyy8.redIAdd(yyyy8); yyyy8 = yyyy8.redIAdd(yyyy8); // X3 = T nx = t; // Y3 = M * (S - T) - 8 * YYYY ny = m.redMul(s.redISub(t)).redISub(yyyy8); // Z3 = 2*Y1 nz = this.y.redAdd(this.y); } else { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html // #doubling-dbl-2009-l // 2M + 5S + 13A // A = X1^2 var a = this.x.redSqr(); // B = Y1^2 var b = this.y.redSqr(); // C = B^2 var c = b.redSqr(); // D = 2 * ((X1 + B)^2 - A - C) var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); d = d.redIAdd(d); // E = 3 * A var e = a.redAdd(a).redIAdd(a); // F = E^2 var f = e.redSqr(); // 8 * C var c8 = c.redIAdd(c); c8 = c8.redIAdd(c8); c8 = c8.redIAdd(c8); // X3 = F - 2 * D nx = f.redISub(d).redISub(d); // Y3 = E * (D - X3) - 8 * C ny = e.redMul(d.redISub(nx)).redISub(c8); // Z3 = 2 * Y1 * Z1 nz = this.y.redMul(this.z); nz = nz.redIAdd(nz); } return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype._threeDbl = function _threeDbl() { var nx; var ny; var nz; // Z = 1 if (this.zOne) { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html // #doubling-mdbl-2007-bl // 1M + 5S + 15A // XX = X1^2 var xx = this.x.redSqr(); // YY = Y1^2 var yy = this.y.redSqr(); // YYYY = YY^2 var yyyy = yy.redSqr(); // S = 2 * ((X1 + YY)^2 - XX - YYYY) var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); s = s.redIAdd(s); // M = 3 * XX + a var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); // T = M^2 - 2 * S var t = m.redSqr().redISub(s).redISub(s); // X3 = T nx = t; // Y3 = M * (S - T) - 8 * YYYY var yyyy8 = yyyy.redIAdd(yyyy); yyyy8 = yyyy8.redIAdd(yyyy8); yyyy8 = yyyy8.redIAdd(yyyy8); ny = m.redMul(s.redISub(t)).redISub(yyyy8); // Z3 = 2 * Y1 nz = this.y.redAdd(this.y); } else { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b // 3M + 5S // delta = Z1^2 var delta = this.z.redSqr(); // gamma = Y1^2 var gamma = this.y.redSqr(); // beta = X1 * gamma var beta = this.x.redMul(gamma); // alpha = 3 * (X1 - delta) * (X1 + delta) var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); alpha = alpha.redAdd(alpha).redIAdd(alpha); // X3 = alpha^2 - 8 * beta var beta4 = beta.redIAdd(beta); beta4 = beta4.redIAdd(beta4); var beta8 = beta4.redAdd(beta4); nx = alpha.redSqr().redISub(beta8); // Z3 = (Y1 + Z1)^2 - gamma - delta nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 var ggamma8 = gamma.redSqr(); ggamma8 = ggamma8.redIAdd(ggamma8); ggamma8 = ggamma8.redIAdd(ggamma8); ggamma8 = ggamma8.redIAdd(ggamma8); ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); } return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype._dbl = function _dbl() { var a = this.curve.a; // 4M + 6S + 10A var jx = this.x; var jy = this.y; var jz = this.z; var jz4 = jz.redSqr().redSqr(); var jx2 = jx.redSqr(); var jy2 = jy.redSqr(); var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); var jxd4 = jx.redAdd(jx); jxd4 = jxd4.redIAdd(jxd4); var t1 = jxd4.redMul(jy2); var nx = c.redSqr().redISub(t1.redAdd(t1)); var t2 = t1.redISub(nx); var jyd8 = jy2.redSqr(); jyd8 = jyd8.redIAdd(jyd8); jyd8 = jyd8.redIAdd(jyd8); jyd8 = jyd8.redIAdd(jyd8); var ny = c.redMul(t2).redISub(jyd8); var nz = jy.redAdd(jy).redMul(jz); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.trpl = function trpl() { if (!this.curve.zeroA) return this.dbl().add(this); // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl // 5M + 10S + ... // XX = X1^2 var xx = this.x.redSqr(); // YY = Y1^2 var yy = this.y.redSqr(); // ZZ = Z1^2 var zz = this.z.redSqr(); // YYYY = YY^2 var yyyy = yy.redSqr(); // M = 3 * XX + a * ZZ2; a = 0 var m = xx.redAdd(xx).redIAdd(xx); // MM = M^2 var mm = m.redSqr(); // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); e = e.redIAdd(e); e = e.redAdd(e).redIAdd(e); e = e.redISub(mm); // EE = E^2 var ee = e.redSqr(); // T = 16*YYYY var t = yyyy.redIAdd(yyyy); t = t.redIAdd(t); t = t.redIAdd(t); t = t.redIAdd(t); // U = (M + E)^2 - MM - EE - T var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); // X3 = 4 * (X1 * EE - 4 * YY * U) var yyu4 = yy.redMul(u); yyu4 = yyu4.redIAdd(yyu4); yyu4 = yyu4.redIAdd(yyu4); var nx = this.x.redMul(ee).redISub(yyu4); nx = nx.redIAdd(nx); nx = nx.redIAdd(nx); // Y3 = 8 * Y1 * (U * (T - U) - E * EE) var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); ny = ny.redIAdd(ny); ny = ny.redIAdd(ny); ny = ny.redIAdd(ny); // Z3 = (Z1 + E)^2 - ZZ - EE var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.mul = function mul(k, kbase) { k = new BN(k, kbase); return this.curve._wnafMul(this, k); }; JPoint.prototype.eq = function eq(p) { if (p.type === 'affine') return this.eq(p.toJ()); if (this === p) return true; // x1 * z2^2 == x2 * z1^2 var z2 = this.z.redSqr(); var pz2 = p.z.redSqr(); if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) return false; // y1 * z2^3 == y2 * z1^3 var z3 = z2.redMul(this.z); var pz3 = pz2.redMul(p.z); return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; }; JPoint.prototype.eqXToP = function eqXToP(x) { var zs = this.z.redSqr(); var rx = x.toRed(this.curve.red).redMul(zs); if (this.x.cmp(rx) === 0) return true; var xc = x.clone(); var t = this.curve.redN.redMul(zs); for (;;) { xc.iadd(this.curve.n); if (xc.cmp(this.curve.p) >= 0) return false; rx.redIAdd(t); if (this.x.cmp(rx) === 0) return true; } }; JPoint.prototype.inspect = function inspect() { if (this.isInfinity()) return ''; return ''; }; JPoint.prototype.isInfinity = function isInfinity() { // XXX This code assumes that zero is always zero in red return this.z.cmpn(0) === 0; }; /***/ }), /***/ 5427: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var curves = exports; var hash = __webpack_require__(3715); var curve = __webpack_require__(8254); var utils = __webpack_require__(953); var assert = utils.assert; function PresetCurve(options) { if (options.type === 'short') this.curve = new curve.short(options); else if (options.type === 'edwards') this.curve = new curve.edwards(options); else this.curve = new curve.mont(options); this.g = this.curve.g; this.n = this.curve.n; this.hash = options.hash; assert(this.g.validate(), 'Invalid curve'); assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); } curves.PresetCurve = PresetCurve; function defineCurve(name, options) { Object.defineProperty(curves, name, { configurable: true, enumerable: true, get: function() { var curve = new PresetCurve(options); Object.defineProperty(curves, name, { configurable: true, enumerable: true, value: curve, }); return curve; }, }); } defineCurve('p192', { type: 'short', prime: 'p192', p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', hash: hash.sha256, gRed: false, g: [ '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811', ], }); defineCurve('p224', { type: 'short', prime: 'p224', p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', hash: hash.sha256, gRed: false, g: [ 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34', ], }); defineCurve('p256', { type: 'short', prime: null, p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', hash: hash.sha256, gRed: false, g: [ '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5', ], }); defineCurve('p384', { type: 'short', prime: null, p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'fffffffe ffffffff 00000000 00000000 ffffffff', a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'fffffffe ffffffff 00000000 00000000 fffffffc', b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', hash: hash.sha384, gRed: false, g: [ 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + '5502f25d bf55296c 3a545e38 72760ab7', '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f', ], }); defineCurve('p521', { type: 'short', prime: null, p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff ffffffff', a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff fffffffc', b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', hash: hash.sha512, gRed: false, g: [ '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + '3fad0761 353c7086 a272c240 88be9476 9fd16650', ], }); defineCurve('curve25519', { type: 'mont', prime: 'p25519', p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', a: '76d06', b: '1', n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', hash: hash.sha256, gRed: false, g: [ '9', ], }); defineCurve('ed25519', { type: 'edwards', prime: 'p25519', p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', a: '-1', c: '1', // -121665 * (121666^(-1)) (mod P) d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', hash: hash.sha256, gRed: false, g: [ '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', // 4/5 '6666666666666666666666666666666666666666666666666666666666666658', ], }); var pre; try { pre = __webpack_require__(1037); } catch (e) { pre = undefined; } defineCurve('secp256k1', { type: 'short', prime: 'k256', p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', a: '0', b: '7', n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', h: '1', hash: hash.sha256, // Precomputed endomorphism beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', basis: [ { a: '3086d221a7d46bcde86c90e49284eb15', b: '-e4437ed6010e88286f547fa90abfe4c3', }, { a: '114ca50f7a8e2f3f657c1108d9d44cfd8', b: '3086d221a7d46bcde86c90e49284eb15', }, ], gRed: false, g: [ '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', pre, ], }); /***/ }), /***/ 7954: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var BN = __webpack_require__(3550); var HmacDRBG = __webpack_require__(2156); var utils = __webpack_require__(953); var curves = __webpack_require__(5427); var rand = __webpack_require__(9931); var assert = utils.assert; var KeyPair = __webpack_require__(1251); var Signature = __webpack_require__(611); function EC(options) { if (!(this instanceof EC)) return new EC(options); // Shortcut `elliptic.ec(curve-name)` if (typeof options === 'string') { assert(Object.prototype.hasOwnProperty.call(curves, options), 'Unknown curve ' + options); options = curves[options]; } // Shortcut for `elliptic.ec(elliptic.curves.curveName)` if (options instanceof curves.PresetCurve) options = { curve: options }; this.curve = options.curve.curve; this.n = this.curve.n; this.nh = this.n.ushrn(1); this.g = this.curve.g; // Point on curve this.g = options.curve.g; this.g.precompute(options.curve.n.bitLength() + 1); // Hash for function for DRBG this.hash = options.hash || options.curve.hash; } module.exports = EC; EC.prototype.keyPair = function keyPair(options) { return new KeyPair(this, options); }; EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { return KeyPair.fromPrivate(this, priv, enc); }; EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { return KeyPair.fromPublic(this, pub, enc); }; EC.prototype.genKeyPair = function genKeyPair(options) { if (!options) options = {}; // Instantiate Hmac_DRBG var drbg = new HmacDRBG({ hash: this.hash, pers: options.pers, persEnc: options.persEnc || 'utf8', entropy: options.entropy || rand(this.hash.hmacStrength), entropyEnc: options.entropy && options.entropyEnc || 'utf8', nonce: this.n.toArray(), }); var bytes = this.n.byteLength(); var ns2 = this.n.sub(new BN(2)); for (;;) { var priv = new BN(drbg.generate(bytes)); if (priv.cmp(ns2) > 0) continue; priv.iaddn(1); return this.keyFromPrivate(priv); } }; EC.prototype._truncateToN = function _truncateToN(msg, truncOnly) { var delta = msg.byteLength() * 8 - this.n.bitLength(); if (delta > 0) msg = msg.ushrn(delta); if (!truncOnly && msg.cmp(this.n) >= 0) return msg.sub(this.n); else return msg; }; EC.prototype.sign = function sign(msg, key, enc, options) { if (typeof enc === 'object') { options = enc; enc = null; } if (!options) options = {}; key = this.keyFromPrivate(key, enc); msg = this._truncateToN(new BN(msg, 16)); // Zero-extend key to provide enough entropy var bytes = this.n.byteLength(); var bkey = key.getPrivate().toArray('be', bytes); // Zero-extend nonce to have the same byte size as N var nonce = msg.toArray('be', bytes); // Instantiate Hmac_DRBG var drbg = new HmacDRBG({ hash: this.hash, entropy: bkey, nonce: nonce, pers: options.pers, persEnc: options.persEnc || 'utf8', }); // Number of bytes to generate var ns1 = this.n.sub(new BN(1)); for (var iter = 0; ; iter++) { var k = options.k ? options.k(iter) : new BN(drbg.generate(this.n.byteLength())); k = this._truncateToN(k, true); if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) continue; var kp = this.g.mul(k); if (kp.isInfinity()) continue; var kpX = kp.getX(); var r = kpX.umod(this.n); if (r.cmpn(0) === 0) continue; var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); s = s.umod(this.n); if (s.cmpn(0) === 0) continue; var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | (kpX.cmp(r) !== 0 ? 2 : 0); // Use complement of `s`, if it is > `n / 2` if (options.canonical && s.cmp(this.nh) > 0) { s = this.n.sub(s); recoveryParam ^= 1; } return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); } }; EC.prototype.verify = function verify(msg, signature, key, enc) { msg = this._truncateToN(new BN(msg, 16)); key = this.keyFromPublic(key, enc); signature = new Signature(signature, 'hex'); // Perform primitive values validation var r = signature.r; var s = signature.s; if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) return false; if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) return false; // Validate signature var sinv = s.invm(this.n); var u1 = sinv.mul(msg).umod(this.n); var u2 = sinv.mul(r).umod(this.n); var p; if (!this.curve._maxwellTrick) { p = this.g.mulAdd(u1, key.getPublic(), u2); if (p.isInfinity()) return false; return p.getX().umod(this.n).cmp(r) === 0; } // NOTE: Greg Maxwell's trick, inspired by: // https://git.io/vad3K p = this.g.jmulAdd(u1, key.getPublic(), u2); if (p.isInfinity()) return false; // Compare `p.x` of Jacobian point with `r`, // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the // inverse of `p.z^2` return p.eqXToP(r); }; EC.prototype.recoverPubKey = function(msg, signature, j, enc) { assert((3 & j) === j, 'The recovery param is more than two bits'); signature = new Signature(signature, enc); var n = this.n; var e = new BN(msg); var r = signature.r; var s = signature.s; // A set LSB signifies that the y-coordinate is odd var isYOdd = j & 1; var isSecondKey = j >> 1; if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) throw new Error('Unable to find sencond key candinate'); // 1.1. Let x = r + jn. if (isSecondKey) r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); else r = this.curve.pointFromX(r, isYOdd); var rInv = signature.r.invm(n); var s1 = n.sub(e).mul(rInv).umod(n); var s2 = s.mul(rInv).umod(n); // 1.6.1 Compute Q = r^-1 (sR - eG) // Q = r^-1 (sR + -eG) return this.g.mulAdd(s1, r, s2); }; EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { signature = new Signature(signature, enc); if (signature.recoveryParam !== null) return signature.recoveryParam; for (var i = 0; i < 4; i++) { var Qprime; try { Qprime = this.recoverPubKey(e, signature, i); } catch (e) { continue; } if (Qprime.eq(Q)) return i; } throw new Error('Unable to find valid recovery factor'); }; /***/ }), /***/ 1251: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var BN = __webpack_require__(3550); var utils = __webpack_require__(953); var assert = utils.assert; function KeyPair(ec, options) { this.ec = ec; this.priv = null; this.pub = null; // KeyPair(ec, { priv: ..., pub: ... }) if (options.priv) this._importPrivate(options.priv, options.privEnc); if (options.pub) this._importPublic(options.pub, options.pubEnc); } module.exports = KeyPair; KeyPair.fromPublic = function fromPublic(ec, pub, enc) { if (pub instanceof KeyPair) return pub; return new KeyPair(ec, { pub: pub, pubEnc: enc, }); }; KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { if (priv instanceof KeyPair) return priv; return new KeyPair(ec, { priv: priv, privEnc: enc, }); }; KeyPair.prototype.validate = function validate() { var pub = this.getPublic(); if (pub.isInfinity()) return { result: false, reason: 'Invalid public key' }; if (!pub.validate()) return { result: false, reason: 'Public key is not a point' }; if (!pub.mul(this.ec.curve.n).isInfinity()) return { result: false, reason: 'Public key * N != O' }; return { result: true, reason: null }; }; KeyPair.prototype.getPublic = function getPublic(compact, enc) { // compact is optional argument if (typeof compact === 'string') { enc = compact; compact = null; } if (!this.pub) this.pub = this.ec.g.mul(this.priv); if (!enc) return this.pub; return this.pub.encode(enc, compact); }; KeyPair.prototype.getPrivate = function getPrivate(enc) { if (enc === 'hex') return this.priv.toString(16, 2); else return this.priv; }; KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { this.priv = new BN(key, enc || 16); // Ensure that the priv won't be bigger than n, otherwise we may fail // in fixed multiplication method this.priv = this.priv.umod(this.ec.curve.n); }; KeyPair.prototype._importPublic = function _importPublic(key, enc) { if (key.x || key.y) { // Montgomery points only have an `x` coordinate. // Weierstrass/Edwards points on the other hand have both `x` and // `y` coordinates. if (this.ec.curve.type === 'mont') { assert(key.x, 'Need x coordinate'); } else if (this.ec.curve.type === 'short' || this.ec.curve.type === 'edwards') { assert(key.x && key.y, 'Need both x and y coordinate'); } this.pub = this.ec.curve.point(key.x, key.y); return; } this.pub = this.ec.curve.decodePoint(key, enc); }; // ECDH KeyPair.prototype.derive = function derive(pub) { if(!pub.validate()) { assert(pub.validate(), 'public point not validated'); } return pub.mul(this.priv).getX(); }; // ECDSA KeyPair.prototype.sign = function sign(msg, enc, options) { return this.ec.sign(msg, this, enc, options); }; KeyPair.prototype.verify = function verify(msg, signature) { return this.ec.verify(msg, signature, this); }; KeyPair.prototype.inspect = function inspect() { return ''; }; /***/ }), /***/ 611: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var BN = __webpack_require__(3550); var utils = __webpack_require__(953); var assert = utils.assert; function Signature(options, enc) { if (options instanceof Signature) return options; if (this._importDER(options, enc)) return; assert(options.r && options.s, 'Signature without r or s'); this.r = new BN(options.r, 16); this.s = new BN(options.s, 16); if (options.recoveryParam === undefined) this.recoveryParam = null; else this.recoveryParam = options.recoveryParam; } module.exports = Signature; function Position() { this.place = 0; } function getLength(buf, p) { var initial = buf[p.place++]; if (!(initial & 0x80)) { return initial; } var octetLen = initial & 0xf; // Indefinite length or overflow if (octetLen === 0 || octetLen > 4) { return false; } var val = 0; for (var i = 0, off = p.place; i < octetLen; i++, off++) { val <<= 8; val |= buf[off]; val >>>= 0; } // Leading zeroes if (val <= 0x7f) { return false; } p.place = off; return val; } function rmPadding(buf) { var i = 0; var len = buf.length - 1; while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { i++; } if (i === 0) { return buf; } return buf.slice(i); } Signature.prototype._importDER = function _importDER(data, enc) { data = utils.toArray(data, enc); var p = new Position(); if (data[p.place++] !== 0x30) { return false; } var len = getLength(data, p); if (len === false) { return false; } if ((len + p.place) !== data.length) { return false; } if (data[p.place++] !== 0x02) { return false; } var rlen = getLength(data, p); if (rlen === false) { return false; } var r = data.slice(p.place, rlen + p.place); p.place += rlen; if (data[p.place++] !== 0x02) { return false; } var slen = getLength(data, p); if (slen === false) { return false; } if (data.length !== slen + p.place) { return false; } var s = data.slice(p.place, slen + p.place); if (r[0] === 0) { if (r[1] & 0x80) { r = r.slice(1); } else { // Leading zeroes return false; } } if (s[0] === 0) { if (s[1] & 0x80) { s = s.slice(1); } else { // Leading zeroes return false; } } this.r = new BN(r); this.s = new BN(s); this.recoveryParam = null; return true; }; function constructLength(arr, len) { if (len < 0x80) { arr.push(len); return; } var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); arr.push(octets | 0x80); while (--octets) { arr.push((len >>> (octets << 3)) & 0xff); } arr.push(len); } Signature.prototype.toDER = function toDER(enc) { var r = this.r.toArray(); var s = this.s.toArray(); // Pad values if (r[0] & 0x80) r = [ 0 ].concat(r); // Pad values if (s[0] & 0x80) s = [ 0 ].concat(s); r = rmPadding(r); s = rmPadding(s); while (!s[0] && !(s[1] & 0x80)) { s = s.slice(1); } var arr = [ 0x02 ]; constructLength(arr, r.length); arr = arr.concat(r); arr.push(0x02); constructLength(arr, s.length); var backHalf = arr.concat(s); var res = [ 0x30 ]; constructLength(res, backHalf.length); res = res.concat(backHalf); return utils.encode(res, enc); }; /***/ }), /***/ 5980: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var hash = __webpack_require__(3715); var curves = __webpack_require__(5427); var utils = __webpack_require__(953); var assert = utils.assert; var parseBytes = utils.parseBytes; var KeyPair = __webpack_require__(9087); var Signature = __webpack_require__(3622); function EDDSA(curve) { assert(curve === 'ed25519', 'only tested with ed25519 so far'); if (!(this instanceof EDDSA)) return new EDDSA(curve); curve = curves[curve].curve; this.curve = curve; this.g = curve.g; this.g.precompute(curve.n.bitLength() + 1); this.pointClass = curve.point().constructor; this.encodingLength = Math.ceil(curve.n.bitLength() / 8); this.hash = hash.sha512; } module.exports = EDDSA; /** * @param {Array|String} message - message bytes * @param {Array|String|KeyPair} secret - secret bytes or a keypair * @returns {Signature} - signature */ EDDSA.prototype.sign = function sign(message, secret) { message = parseBytes(message); var key = this.keyFromSecret(secret); var r = this.hashInt(key.messagePrefix(), message); var R = this.g.mul(r); var Rencoded = this.encodePoint(R); var s_ = this.hashInt(Rencoded, key.pubBytes(), message) .mul(key.priv()); var S = r.add(s_).umod(this.curve.n); return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); }; /** * @param {Array} message - message bytes * @param {Array|String|Signature} sig - sig bytes * @param {Array|String|Point|KeyPair} pub - public key * @returns {Boolean} - true if public key matches sig of message */ EDDSA.prototype.verify = function verify(message, sig, pub) { message = parseBytes(message); sig = this.makeSignature(sig); var key = this.keyFromPublic(pub); var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); var SG = this.g.mul(sig.S()); var RplusAh = sig.R().add(key.pub().mul(h)); return RplusAh.eq(SG); }; EDDSA.prototype.hashInt = function hashInt() { var hash = this.hash(); for (var i = 0; i < arguments.length; i++) hash.update(arguments[i]); return utils.intFromLE(hash.digest()).umod(this.curve.n); }; EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { return KeyPair.fromPublic(this, pub); }; EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { return KeyPair.fromSecret(this, secret); }; EDDSA.prototype.makeSignature = function makeSignature(sig) { if (sig instanceof Signature) return sig; return new Signature(this, sig); }; /** * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 * * EDDSA defines methods for encoding and decoding points and integers. These are * helper convenience methods, that pass along to utility functions implied * parameters. * */ EDDSA.prototype.encodePoint = function encodePoint(point) { var enc = point.getY().toArray('le', this.encodingLength); enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; return enc; }; EDDSA.prototype.decodePoint = function decodePoint(bytes) { bytes = utils.parseBytes(bytes); var lastIx = bytes.length - 1; var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); var xIsOdd = (bytes[lastIx] & 0x80) !== 0; var y = utils.intFromLE(normed); return this.curve.pointFromY(y, xIsOdd); }; EDDSA.prototype.encodeInt = function encodeInt(num) { return num.toArray('le', this.encodingLength); }; EDDSA.prototype.decodeInt = function decodeInt(bytes) { return utils.intFromLE(bytes); }; EDDSA.prototype.isPoint = function isPoint(val) { return val instanceof this.pointClass; }; /***/ }), /***/ 9087: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(953); var assert = utils.assert; var parseBytes = utils.parseBytes; var cachedProperty = utils.cachedProperty; /** * @param {EDDSA} eddsa - instance * @param {Object} params - public/private key parameters * * @param {Array} [params.secret] - secret seed bytes * @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) * @param {Array} [params.pub] - public key point encoded as bytes * */ function KeyPair(eddsa, params) { this.eddsa = eddsa; this._secret = parseBytes(params.secret); if (eddsa.isPoint(params.pub)) this._pub = params.pub; else this._pubBytes = parseBytes(params.pub); } KeyPair.fromPublic = function fromPublic(eddsa, pub) { if (pub instanceof KeyPair) return pub; return new KeyPair(eddsa, { pub: pub }); }; KeyPair.fromSecret = function fromSecret(eddsa, secret) { if (secret instanceof KeyPair) return secret; return new KeyPair(eddsa, { secret: secret }); }; KeyPair.prototype.secret = function secret() { return this._secret; }; cachedProperty(KeyPair, 'pubBytes', function pubBytes() { return this.eddsa.encodePoint(this.pub()); }); cachedProperty(KeyPair, 'pub', function pub() { if (this._pubBytes) return this.eddsa.decodePoint(this._pubBytes); return this.eddsa.g.mul(this.priv()); }); cachedProperty(KeyPair, 'privBytes', function privBytes() { var eddsa = this.eddsa; var hash = this.hash(); var lastIx = eddsa.encodingLength - 1; var a = hash.slice(0, eddsa.encodingLength); a[0] &= 248; a[lastIx] &= 127; a[lastIx] |= 64; return a; }); cachedProperty(KeyPair, 'priv', function priv() { return this.eddsa.decodeInt(this.privBytes()); }); cachedProperty(KeyPair, 'hash', function hash() { return this.eddsa.hash().update(this.secret()).digest(); }); cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { return this.hash().slice(this.eddsa.encodingLength); }); KeyPair.prototype.sign = function sign(message) { assert(this._secret, 'KeyPair can only verify'); return this.eddsa.sign(message, this); }; KeyPair.prototype.verify = function verify(message, sig) { return this.eddsa.verify(message, sig, this); }; KeyPair.prototype.getSecret = function getSecret(enc) { assert(this._secret, 'KeyPair is public only'); return utils.encode(this.secret(), enc); }; KeyPair.prototype.getPublic = function getPublic(enc) { return utils.encode(this.pubBytes(), enc); }; module.exports = KeyPair; /***/ }), /***/ 3622: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var BN = __webpack_require__(3550); var utils = __webpack_require__(953); var assert = utils.assert; var cachedProperty = utils.cachedProperty; var parseBytes = utils.parseBytes; /** * @param {EDDSA} eddsa - eddsa instance * @param {Array|Object} sig - * @param {Array|Point} [sig.R] - R point as Point or bytes * @param {Array|bn} [sig.S] - S scalar as bn or bytes * @param {Array} [sig.Rencoded] - R point encoded * @param {Array} [sig.Sencoded] - S scalar encoded */ function Signature(eddsa, sig) { this.eddsa = eddsa; if (typeof sig !== 'object') sig = parseBytes(sig); if (Array.isArray(sig)) { sig = { R: sig.slice(0, eddsa.encodingLength), S: sig.slice(eddsa.encodingLength), }; } assert(sig.R && sig.S, 'Signature without R or S'); if (eddsa.isPoint(sig.R)) this._R = sig.R; if (sig.S instanceof BN) this._S = sig.S; this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; } cachedProperty(Signature, 'S', function S() { return this.eddsa.decodeInt(this.Sencoded()); }); cachedProperty(Signature, 'R', function R() { return this.eddsa.decodePoint(this.Rencoded()); }); cachedProperty(Signature, 'Rencoded', function Rencoded() { return this.eddsa.encodePoint(this.R()); }); cachedProperty(Signature, 'Sencoded', function Sencoded() { return this.eddsa.encodeInt(this.S()); }); Signature.prototype.toBytes = function toBytes() { return this.Rencoded().concat(this.Sencoded()); }; Signature.prototype.toHex = function toHex() { return utils.encode(this.toBytes(), 'hex').toUpperCase(); }; module.exports = Signature; /***/ }), /***/ 1037: /***/ (function(module) { module.exports = { doubles: { step: 4, points: [ [ 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821', ], [ '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf', ], [ '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695', ], [ '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9', ], [ '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36', ], [ '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f', ], [ 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999', ], [ '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09', ], [ 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d', ], [ 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088', ], [ 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d', ], [ '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8', ], [ '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a', ], [ '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453', ], [ '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160', ], [ '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0', ], [ '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6', ], [ '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589', ], [ '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17', ], [ 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda', ], [ 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd', ], [ '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2', ], [ '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6', ], [ 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f', ], [ '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01', ], [ 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3', ], [ 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f', ], [ 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7', ], [ 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78', ], [ 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1', ], [ '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150', ], [ '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82', ], [ 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc', ], [ '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b', ], [ 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51', ], [ 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45', ], [ 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120', ], [ '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84', ], [ '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d', ], [ '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d', ], [ '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8', ], [ 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8', ], [ '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac', ], [ '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f', ], [ '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962', ], [ 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907', ], [ '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec', ], [ 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d', ], [ 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414', ], [ '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd', ], [ '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0', ], [ 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811', ], [ 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1', ], [ 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c', ], [ '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73', ], [ '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd', ], [ 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405', ], [ '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589', ], [ '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e', ], [ '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27', ], [ 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1', ], [ '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482', ], [ '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945', ], [ 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573', ], [ 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82', ], ], }, naf: { wnd: 7, points: [ [ 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672', ], [ '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6', ], [ '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da', ], [ 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37', ], [ '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b', ], [ 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81', ], [ 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58', ], [ 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77', ], [ '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a', ], [ '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c', ], [ '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67', ], [ '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402', ], [ 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55', ], [ 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482', ], [ '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82', ], [ '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396', ], [ '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49', ], [ '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf', ], [ '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a', ], [ '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7', ], [ 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933', ], [ '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a', ], [ '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6', ], [ 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37', ], [ '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e', ], [ 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6', ], [ 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476', ], [ '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40', ], [ '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61', ], [ '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683', ], [ 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5', ], [ '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b', ], [ 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417', ], [ '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868', ], [ '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a', ], [ 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6', ], [ '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996', ], [ '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e', ], [ 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d', ], [ '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2', ], [ '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e', ], [ '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437', ], [ '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311', ], [ 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4', ], [ '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575', ], [ '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d', ], [ '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d', ], [ 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629', ], [ 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06', ], [ '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374', ], [ '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee', ], [ 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1', ], [ 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b', ], [ '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661', ], [ '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6', ], [ 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e', ], [ '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d', ], [ 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc', ], [ '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4', ], [ '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c', ], [ 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b', ], [ 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913', ], [ '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154', ], [ '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865', ], [ '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc', ], [ '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224', ], [ '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e', ], [ '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6', ], [ '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511', ], [ '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b', ], [ 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2', ], [ '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c', ], [ 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3', ], [ 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d', ], [ 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700', ], [ 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4', ], [ '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196', ], [ '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4', ], [ '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257', ], [ 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13', ], [ 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096', ], [ 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38', ], [ 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f', ], [ '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448', ], [ 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a', ], [ 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4', ], [ '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437', ], [ '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7', ], [ 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d', ], [ 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a', ], [ 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54', ], [ '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77', ], [ 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517', ], [ '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10', ], [ 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125', ], [ 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e', ], [ '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1', ], [ 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2', ], [ 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423', ], [ 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8', ], [ '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758', ], [ '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375', ], [ 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d', ], [ '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec', ], [ '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0', ], [ '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c', ], [ 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4', ], [ '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f', ], [ '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649', ], [ '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826', ], [ '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5', ], [ 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87', ], [ '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b', ], [ 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc', ], [ '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c', ], [ 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f', ], [ 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a', ], [ 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46', ], [ '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f', ], [ '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03', ], [ '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08', ], [ '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8', ], [ '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373', ], [ '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3', ], [ '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8', ], [ '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1', ], [ '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9', ], ], }, }; /***/ }), /***/ 953: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var utils = exports; var BN = __webpack_require__(3550); var minAssert = __webpack_require__(9746); var minUtils = __webpack_require__(4504); utils.assert = minAssert; utils.toArray = minUtils.toArray; utils.zero2 = minUtils.zero2; utils.toHex = minUtils.toHex; utils.encode = minUtils.encode; // Represent num in a w-NAF form function getNAF(num, w, bits) { var naf = new Array(Math.max(num.bitLength(), bits) + 1); naf.fill(0); var ws = 1 << (w + 1); var k = num.clone(); for (var i = 0; i < naf.length; i++) { var z; var mod = k.andln(ws - 1); if (k.isOdd()) { if (mod > (ws >> 1) - 1) z = (ws >> 1) - mod; else z = mod; k.isubn(z); } else { z = 0; } naf[i] = z; k.iushrn(1); } return naf; } utils.getNAF = getNAF; // Represent k1, k2 in a Joint Sparse Form function getJSF(k1, k2) { var jsf = [ [], [], ]; k1 = k1.clone(); k2 = k2.clone(); var d1 = 0; var d2 = 0; var m8; while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { // First phase var m14 = (k1.andln(3) + d1) & 3; var m24 = (k2.andln(3) + d2) & 3; if (m14 === 3) m14 = -1; if (m24 === 3) m24 = -1; var u1; if ((m14 & 1) === 0) { u1 = 0; } else { m8 = (k1.andln(7) + d1) & 7; if ((m8 === 3 || m8 === 5) && m24 === 2) u1 = -m14; else u1 = m14; } jsf[0].push(u1); var u2; if ((m24 & 1) === 0) { u2 = 0; } else { m8 = (k2.andln(7) + d2) & 7; if ((m8 === 3 || m8 === 5) && m14 === 2) u2 = -m24; else u2 = m24; } jsf[1].push(u2); // Second phase if (2 * d1 === u1 + 1) d1 = 1 - d1; if (2 * d2 === u2 + 1) d2 = 1 - d2; k1.iushrn(1); k2.iushrn(1); } return jsf; } utils.getJSF = getJSF; function cachedProperty(obj, name, computer) { var key = '_' + name; obj.prototype[name] = function cachedProperty() { return this[key] !== undefined ? this[key] : this[key] = computer.call(this); }; } utils.cachedProperty = cachedProperty; function parseBytes(bytes) { return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : bytes; } utils.parseBytes = parseBytes; function intFromLE(bytes) { return new BN(bytes, 'hex', 'le'); } utils.intFromLE = intFromLE; /***/ }), /***/ 7187: /***/ (function(module) { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var R = typeof Reflect === 'object' ? Reflect : null var ReflectApply = R && typeof R.apply === 'function' ? R.apply : function ReflectApply(target, receiver, args) { return Function.prototype.apply.call(target, receiver, args); } var ReflectOwnKeys if (R && typeof R.ownKeys === 'function') { ReflectOwnKeys = R.ownKeys } else if (Object.getOwnPropertySymbols) { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target) .concat(Object.getOwnPropertySymbols(target)); }; } else { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target); }; } function ProcessEmitWarning(warning) { if (console && console.warn) console.warn(warning); } var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { return value !== value; } function EventEmitter() { EventEmitter.init.call(this); } module.exports = EventEmitter; module.exports.once = once; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._eventsCount = 0; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. var defaultMaxListeners = 10; function checkListener(listener) { if (typeof listener !== 'function') { throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); } } Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); } defaultMaxListeners = arg; } }); EventEmitter.init = function() { if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) { this._events = Object.create(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); } this._maxListeners = n; return this; }; function _getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return _getMaxListeners(this); }; EventEmitter.prototype.emit = function emit(type) { var args = []; for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); var doError = (type === 'error'); var events = this._events; if (events !== undefined) doError = (doError && events.error === undefined); else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { var er; if (args.length > 0) er = args[0]; if (er instanceof Error) { // Note: The comments on the `throw` lines are intentional, they show // up in Node's output if this results in an unhandled exception. throw er; // Unhandled 'error' event } // At least give some kind of context to the user var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); err.context = er; throw err; // Unhandled 'error' event } var handler = events[type]; if (handler === undefined) return false; if (typeof handler === 'function') { ReflectApply(handler, this, args); } else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; checkListener(listener); events = target._events; if (events === undefined) { events = target._events = Object.create(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener !== undefined) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (existing === undefined) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; // If we've already got an array, just append. } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } // Check for listener leak m = _getMaxListeners(target); if (m > 0 && existing.length > m && !existing.warned) { existing.warned = true; // No error code for this since it is a Warning // eslint-disable-next-line no-restricted-syntax var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + String(type) + ' listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; ProcessEmitWarning(w); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; if (arguments.length === 0) return this.listener.call(this.target); return this.listener.apply(this.target, arguments); } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = onceWrapper.bind(state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { checkListener(listener); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { checkListener(listener); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; checkListener(listener); events = this._events; if (events === undefined) return this; list = events[type]; if (list === undefined) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = Object.create(null); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else { spliceOne(list, position); } if (list.length === 1) events[type] = list[0]; if (events.removeListener !== undefined) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (events === undefined) return this; // not listening for removeListener, no need to emit if (events.removeListener === undefined) { if (arguments.length === 0) { this._events = Object.create(null); this._eventsCount = 0; } else if (events[type] !== undefined) { if (--this._eventsCount === 0) this._events = Object.create(null); else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = Object.create(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners !== undefined) { // LIFO order for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (events === undefined) return []; var evlistener = events[type]; if (evlistener === undefined) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events !== undefined) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener !== undefined) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; }; function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function spliceOne(list, index) { for (; index + 1 < list.length; index++) list[index] = list[index + 1]; list.pop(); } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function once(emitter, name) { return new Promise(function (resolve, reject) { function errorListener(err) { emitter.removeListener(name, resolver); reject(err); } function resolver() { if (typeof emitter.removeListener === 'function') { emitter.removeListener('error', errorListener); } resolve([].slice.call(arguments)); }; eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); if (name !== 'error') { addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); } }); } function addErrorHandlerIfEventEmitter(emitter, handler, flags) { if (typeof emitter.on === 'function') { eventTargetAgnosticAddListener(emitter, 'error', handler, flags); } } function eventTargetAgnosticAddListener(emitter, name, listener, flags) { if (typeof emitter.on === 'function') { if (flags.once) { emitter.once(name, listener); } else { emitter.on(name, listener); } } else if (typeof emitter.addEventListener === 'function') { // EventTarget does not have `error` event semantics like Node // EventEmitters, we do not listen for `error` events here. emitter.addEventListener(name, function wrapListener(arg) { // IE does not have builtin `{ once: true }` support so we // have to do it manually. if (flags.once) { emitter.removeEventListener(name, wrapListener); } listener(arg); }); } else { throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); } } /***/ }), /***/ 3346: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { (function (global, factory) { true ? module.exports = factory() : 0; })(this, (function () { 'use strict'; var toStringFunction = Function.prototype.toString; var create = Object.create, defineProperty = Object.defineProperty, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getOwnPropertyNames = Object.getOwnPropertyNames, getOwnPropertySymbols = Object.getOwnPropertySymbols, getPrototypeOf$1 = Object.getPrototypeOf; var _a = Object.prototype, hasOwnProperty = _a.hasOwnProperty, propertyIsEnumerable = _a.propertyIsEnumerable; var SYMBOL_PROPERTIES = typeof getOwnPropertySymbols === 'function'; var WEAK_MAP = typeof WeakMap === 'function'; /** * @function createCache * * @description * get a new cache object to prevent circular references * * @returns the new cache object */ var createCache = (function () { if (WEAK_MAP) { return function () { return new WeakMap(); }; } var Cache = /** @class */ (function () { function Cache() { this._keys = []; this._values = []; } Cache.prototype.has = function (key) { return !!~this._keys.indexOf(key); }; Cache.prototype.get = function (key) { return this._values[this._keys.indexOf(key)]; }; Cache.prototype.set = function (key, value) { this._keys.push(key); this._values.push(value); }; return Cache; }()); return function () { return new Cache(); }; })(); /** * @function getCleanClone * * @description * get an empty version of the object with the same prototype it has * * @param object the object to build a clean clone from * @param realm the realm the object resides in * @returns the empty cloned object */ var getCleanClone = function (object, realm) { var prototype = object.__proto__ || getPrototypeOf$1(object); if (!prototype) { return create(null); } var Constructor = prototype.constructor; if (Constructor === realm.Object) { return prototype === realm.Object.prototype ? {} : create(prototype); } if (~toStringFunction.call(Constructor).indexOf('[native code]')) { try { return new Constructor(); } catch (_a) { } } return create(prototype); }; /** * @function getObjectCloneLoose * * @description * get a copy of the object based on loose rules, meaning all enumerable keys * and symbols are copied, but property descriptors are not considered * * @param object the object to clone * @param realm the realm the object resides in * @param handleCopy the function that handles copying the object * @returns the copied object */ var getObjectCloneLoose = function (object, realm, handleCopy, cache) { var clone = getCleanClone(object, realm); // set in the cache immediately to be able to reuse the object recursively cache.set(object, clone); for (var key in object) { if (hasOwnProperty.call(object, key)) { clone[key] = handleCopy(object[key], cache); } } if (SYMBOL_PROPERTIES) { var symbols = getOwnPropertySymbols(object); for (var index = 0, length_1 = symbols.length, symbol = void 0; index < length_1; ++index) { symbol = symbols[index]; if (propertyIsEnumerable.call(object, symbol)) { clone[symbol] = handleCopy(object[symbol], cache); } } } return clone; }; /** * @function getObjectCloneStrict * * @description * get a copy of the object based on strict rules, meaning all keys and symbols * are copied based on the original property descriptors * * @param object the object to clone * @param realm the realm the object resides in * @param handleCopy the function that handles copying the object * @returns the copied object */ var getObjectCloneStrict = function (object, realm, handleCopy, cache) { var clone = getCleanClone(object, realm); // set in the cache immediately to be able to reuse the object recursively cache.set(object, clone); var properties = SYMBOL_PROPERTIES ? getOwnPropertyNames(object).concat(getOwnPropertySymbols(object)) : getOwnPropertyNames(object); for (var index = 0, length_2 = properties.length, property = void 0, descriptor = void 0; index < length_2; ++index) { property = properties[index]; if (property !== 'callee' && property !== 'caller') { descriptor = getOwnPropertyDescriptor(object, property); if (descriptor) { // Only clone the value if actually a value, not a getter / setter. if (!descriptor.get && !descriptor.set) { descriptor.value = handleCopy(object[property], cache); } try { defineProperty(clone, property, descriptor); } catch (error) { // Tee above can fail on node in edge cases, so fall back to the loose assignment. clone[property] = descriptor.value; } } else { // In extra edge cases where the property descriptor cannot be retrived, fall back to // the loose assignment. clone[property] = handleCopy(object[property], cache); } } } return clone; }; /** * @function getRegExpFlags * * @description * get the flags to apply to the copied regexp * * @param regExp the regexp to get the flags of * @returns the flags for the regexp */ var getRegExpFlags = function (regExp) { var flags = ''; if (regExp.global) { flags += 'g'; } if (regExp.ignoreCase) { flags += 'i'; } if (regExp.multiline) { flags += 'm'; } if (regExp.unicode) { flags += 'u'; } if (regExp.sticky) { flags += 'y'; } return flags; }; // utils var isArray = Array.isArray; var getPrototypeOf = Object.getPrototypeOf; var GLOBAL_THIS = (function () { if (typeof globalThis !== 'undefined') { return globalThis; } if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof __webpack_require__.g !== 'undefined') { return __webpack_require__.g; } if (console && console.error) { console.error('Unable to locate global object, returning "this".'); } return this; })(); /** * @function copy * * @description * copy an value deeply as much as possible * * If `strict` is applied, then all properties (including non-enumerable ones) * are copied with their original property descriptors on both objects and arrays. * * The value is compared to the global constructors in the `realm` provided, * and the native constructor is always used to ensure that extensions of native * objects (allows in ES2015+) are maintained. * * @param value the value to copy * @param [options] the options for copying with * @param [options.isStrict] should the copy be strict * @param [options.realm] the realm (this) value the value is copied from * @returns the copied value */ function copy(value, options) { // manually coalesced instead of default parameters for performance var isStrict = !!(options && options.isStrict); var realm = (options && options.realm) || GLOBAL_THIS; var getObjectClone = isStrict ? getObjectCloneStrict : getObjectCloneLoose; /** * @function handleCopy * * @description * copy the value recursively based on its type * * @param value the value to copy * @returns the copied value */ var handleCopy = function (value, cache) { if (!value || typeof value !== 'object') { return value; } if (cache.has(value)) { return cache.get(value); } var prototype = value.__proto__ || getPrototypeOf(value); var Constructor = prototype && prototype.constructor; // plain objects if (!Constructor || Constructor === realm.Object) { return getObjectClone(value, realm, handleCopy, cache); } var clone; // arrays if (isArray(value)) { // if strict, include non-standard properties if (isStrict) { return getObjectCloneStrict(value, realm, handleCopy, cache); } clone = new Constructor(); cache.set(value, clone); for (var index = 0, length_1 = value.length; index < length_1; ++index) { clone[index] = handleCopy(value[index], cache); } return clone; } // dates if (value instanceof realm.Date) { return new Constructor(value.getTime()); } // regexps if (value instanceof realm.RegExp) { clone = new Constructor(value.source, value.flags || getRegExpFlags(value)); clone.lastIndex = value.lastIndex; return clone; } // maps if (realm.Map && value instanceof realm.Map) { clone = new Constructor(); cache.set(value, clone); value.forEach(function (value, key) { clone.set(key, handleCopy(value, cache)); }); return clone; } // sets if (realm.Set && value instanceof realm.Set) { clone = new Constructor(); cache.set(value, clone); value.forEach(function (value) { clone.add(handleCopy(value, cache)); }); return clone; } // blobs if (realm.Blob && value instanceof realm.Blob) { return value.slice(0, value.size, value.type); } // buffers (node-only) if (realm.Buffer && realm.Buffer.isBuffer(value)) { clone = realm.Buffer.allocUnsafe ? realm.Buffer.allocUnsafe(value.length) : new Constructor(value.length); cache.set(value, clone); value.copy(clone); return clone; } // arraybuffers / dataviews if (realm.ArrayBuffer) { // dataviews if (realm.ArrayBuffer.isView(value)) { clone = new Constructor(value.buffer.slice(0)); cache.set(value, clone); return clone; } // arraybuffers if (value instanceof realm.ArrayBuffer) { clone = value.slice(0); cache.set(value, clone); return clone; } } // if the value cannot / should not be cloned, don't if ( // promise-like typeof value.then === 'function' || // errors value instanceof Error || // weakmaps (realm.WeakMap && value instanceof realm.WeakMap) || // weaksets (realm.WeakSet && value instanceof realm.WeakSet)) { return value; } // assume anything left is a custom constructor return getObjectClone(value, realm, handleCopy, cache); }; return handleCopy(value, createCache()); } // Adding reference to allow usage in CommonJS libraries compiled using TSC, which // expects there to be a default property on the exported value. See // [#37](https://github.com/planttheidea/fast-copy/issues/37) for details. copy.default = copy; /** * @function strictCopy * * @description * copy the value with `strict` option pre-applied * * @param value the value to copy * @param [options] the options for copying with * @param [options.realm] the realm (this) value the value is copied from * @returns the copied value */ copy.strict = function strictCopy(value, options) { return copy(value, { isStrict: true, realm: options ? options.realm : void 0, }); }; return copy; })); //# sourceMappingURL=fast-copy.js.map /***/ }), /***/ 4029: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var isCallable = __webpack_require__(5320); var toStr = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var forEachArray = function forEachArray(array, iterator, receiver) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { if (receiver == null) { iterator(array[i], i, array); } else { iterator.call(receiver, array[i], i, array); } } } }; var forEachString = function forEachString(string, iterator, receiver) { for (var i = 0, len = string.length; i < len; i++) { // no such thing as a sparse string. if (receiver == null) { iterator(string.charAt(i), i, string); } else { iterator.call(receiver, string.charAt(i), i, string); } } }; var forEachObject = function forEachObject(object, iterator, receiver) { for (var k in object) { if (hasOwnProperty.call(object, k)) { if (receiver == null) { iterator(object[k], k, object); } else { iterator.call(receiver, object[k], k, object); } } } }; var forEach = function forEach(list, iterator, thisArg) { if (!isCallable(iterator)) { throw new TypeError('iterator must be a function'); } var receiver; if (arguments.length >= 3) { receiver = thisArg; } if (toStr.call(list) === '[object Array]') { forEachArray(list, iterator, receiver); } else if (typeof list === 'string') { forEachString(list, iterator, receiver); } else { forEachObject(list, iterator, receiver); } }; module.exports = forEach; /***/ }), /***/ 7648: /***/ (function(module) { "use strict"; /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var slice = Array.prototype.slice; var toStr = Object.prototype.toString; var funcType = '[object Function]'; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push('$' + i); } bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; /***/ }), /***/ 8612: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var implementation = __webpack_require__(7648); module.exports = Function.prototype.bind || implementation; /***/ }), /***/ 4977: /***/ (function(module) { "use strict"; module.exports = createRBTree var RED = 0 var BLACK = 1 function RBNode(color, key, value, left, right, count) { this._color = color this.key = key this.value = value this.left = left this.right = right this._count = count } function cloneNode(node) { return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count) } function repaint(color, node) { return new RBNode(color, node.key, node.value, node.left, node.right, node._count) } function recount(node) { node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0) } function RedBlackTree(compare, root) { this._compare = compare this.root = root } var proto = RedBlackTree.prototype Object.defineProperty(proto, "keys", { get: function() { var result = [] this.forEach(function(k,v) { result.push(k) }) return result } }) Object.defineProperty(proto, "values", { get: function() { var result = [] this.forEach(function(k,v) { result.push(v) }) return result } }) //Returns the number of nodes in the tree Object.defineProperty(proto, "length", { get: function() { if(this.root) { return this.root._count } return 0 } }) //Insert a new item into the tree proto.insert = function(key, value) { var cmp = this._compare //Find point to insert new node at var n = this.root var n_stack = [] var d_stack = [] while(n) { var d = cmp(key, n.key) n_stack.push(n) d_stack.push(d) if(d <= 0) { n = n.left } else { n = n.right } } //Rebuild path to leaf node n_stack.push(new RBNode(RED, key, value, null, null, 1)) for(var s=n_stack.length-2; s>=0; --s) { var n = n_stack[s] if(d_stack[s] <= 0) { n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1) } else { n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1) } } //Rebalance tree using rotations //console.log("start insert", key, d_stack) for(var s=n_stack.length-1; s>1; --s) { var p = n_stack[s-1] var n = n_stack[s] if(p._color === BLACK || n._color === BLACK) { break } var pp = n_stack[s-2] if(pp.left === p) { if(p.left === n) { var y = pp.right if(y && y._color === RED) { //console.log("LLr") p._color = BLACK pp.right = repaint(BLACK, y) pp._color = RED s -= 1 } else { //console.log("LLb") pp._color = RED pp.left = p.right p._color = BLACK p.right = pp n_stack[s-2] = p n_stack[s-1] = n recount(pp) recount(p) if(s >= 3) { var ppp = n_stack[s-3] if(ppp.left === pp) { ppp.left = p } else { ppp.right = p } } break } } else { var y = pp.right if(y && y._color === RED) { //console.log("LRr") p._color = BLACK pp.right = repaint(BLACK, y) pp._color = RED s -= 1 } else { //console.log("LRb") p.right = n.left pp._color = RED pp.left = n.right n._color = BLACK n.left = p n.right = pp n_stack[s-2] = n n_stack[s-1] = p recount(pp) recount(p) recount(n) if(s >= 3) { var ppp = n_stack[s-3] if(ppp.left === pp) { ppp.left = n } else { ppp.right = n } } break } } } else { if(p.right === n) { var y = pp.left if(y && y._color === RED) { //console.log("RRr", y.key) p._color = BLACK pp.left = repaint(BLACK, y) pp._color = RED s -= 1 } else { //console.log("RRb") pp._color = RED pp.right = p.left p._color = BLACK p.left = pp n_stack[s-2] = p n_stack[s-1] = n recount(pp) recount(p) if(s >= 3) { var ppp = n_stack[s-3] if(ppp.right === pp) { ppp.right = p } else { ppp.left = p } } break } } else { var y = pp.left if(y && y._color === RED) { //console.log("RLr") p._color = BLACK pp.left = repaint(BLACK, y) pp._color = RED s -= 1 } else { //console.log("RLb") p.left = n.right pp._color = RED pp.right = n.left n._color = BLACK n.right = p n.left = pp n_stack[s-2] = n n_stack[s-1] = p recount(pp) recount(p) recount(n) if(s >= 3) { var ppp = n_stack[s-3] if(ppp.right === pp) { ppp.right = n } else { ppp.left = n } } break } } } } //Return new tree n_stack[0]._color = BLACK return new RedBlackTree(cmp, n_stack[0]) } //Visit all nodes inorder function doVisitFull(visit, node) { if(node.left) { var v = doVisitFull(visit, node.left) if(v) { return v } } var v = visit(node.key, node.value) if(v) { return v } if(node.right) { return doVisitFull(visit, node.right) } } //Visit half nodes in order function doVisitHalf(lo, compare, visit, node) { var l = compare(lo, node.key) if(l <= 0) { if(node.left) { var v = doVisitHalf(lo, compare, visit, node.left) if(v) { return v } } var v = visit(node.key, node.value) if(v) { return v } } if(node.right) { return doVisitHalf(lo, compare, visit, node.right) } } //Visit all nodes within a range function doVisit(lo, hi, compare, visit, node) { var l = compare(lo, node.key) var h = compare(hi, node.key) var v if(l <= 0) { if(node.left) { v = doVisit(lo, hi, compare, visit, node.left) if(v) { return v } } if(h > 0) { v = visit(node.key, node.value) if(v) { return v } } } if(h > 0 && node.right) { return doVisit(lo, hi, compare, visit, node.right) } } proto.forEach = function rbTreeForEach(visit, lo, hi) { if(!this.root) { return } switch(arguments.length) { case 1: return doVisitFull(visit, this.root) break case 2: return doVisitHalf(lo, this._compare, visit, this.root) break case 3: if(this._compare(lo, hi) >= 0) { return } return doVisit(lo, hi, this._compare, visit, this.root) break } } //First item in list Object.defineProperty(proto, "begin", { get: function() { var stack = [] var n = this.root while(n) { stack.push(n) n = n.left } return new RedBlackTreeIterator(this, stack) } }) //Last item in list Object.defineProperty(proto, "end", { get: function() { var stack = [] var n = this.root while(n) { stack.push(n) n = n.right } return new RedBlackTreeIterator(this, stack) } }) //Find the ith item in the tree proto.at = function(idx) { if(idx < 0) { return new RedBlackTreeIterator(this, []) } var n = this.root var stack = [] while(true) { stack.push(n) if(n.left) { if(idx < n.left._count) { n = n.left continue } idx -= n.left._count } if(!idx) { return new RedBlackTreeIterator(this, stack) } idx -= 1 if(n.right) { if(idx >= n.right._count) { break } n = n.right } else { break } } return new RedBlackTreeIterator(this, []) } proto.ge = function(key) { var cmp = this._compare var n = this.root var stack = [] var last_ptr = 0 while(n) { var d = cmp(key, n.key) stack.push(n) if(d <= 0) { last_ptr = stack.length } if(d <= 0) { n = n.left } else { n = n.right } } stack.length = last_ptr return new RedBlackTreeIterator(this, stack) } proto.gt = function(key) { var cmp = this._compare var n = this.root var stack = [] var last_ptr = 0 while(n) { var d = cmp(key, n.key) stack.push(n) if(d < 0) { last_ptr = stack.length } if(d < 0) { n = n.left } else { n = n.right } } stack.length = last_ptr return new RedBlackTreeIterator(this, stack) } proto.lt = function(key) { var cmp = this._compare var n = this.root var stack = [] var last_ptr = 0 while(n) { var d = cmp(key, n.key) stack.push(n) if(d > 0) { last_ptr = stack.length } if(d <= 0) { n = n.left } else { n = n.right } } stack.length = last_ptr return new RedBlackTreeIterator(this, stack) } proto.le = function(key) { var cmp = this._compare var n = this.root var stack = [] var last_ptr = 0 while(n) { var d = cmp(key, n.key) stack.push(n) if(d >= 0) { last_ptr = stack.length } if(d < 0) { n = n.left } else { n = n.right } } stack.length = last_ptr return new RedBlackTreeIterator(this, stack) } //Finds the item with key if it exists proto.find = function(key) { var cmp = this._compare var n = this.root var stack = [] while(n) { var d = cmp(key, n.key) stack.push(n) if(d === 0) { return new RedBlackTreeIterator(this, stack) } if(d <= 0) { n = n.left } else { n = n.right } } return new RedBlackTreeIterator(this, []) } //Removes item with key from tree proto.remove = function(key) { var iter = this.find(key) if(iter) { return iter.remove() } return this } //Returns the item at `key` proto.get = function(key) { var cmp = this._compare var n = this.root while(n) { var d = cmp(key, n.key) if(d === 0) { return n.value } if(d <= 0) { n = n.left } else { n = n.right } } return } //Iterator for red black tree function RedBlackTreeIterator(tree, stack) { this.tree = tree this._stack = stack } var iproto = RedBlackTreeIterator.prototype //Test if iterator is valid Object.defineProperty(iproto, "valid", { get: function() { return this._stack.length > 0 } }) //Node of the iterator Object.defineProperty(iproto, "node", { get: function() { if(this._stack.length > 0) { return this._stack[this._stack.length-1] } return null }, enumerable: true }) //Makes a copy of an iterator iproto.clone = function() { return new RedBlackTreeIterator(this.tree, this._stack.slice()) } //Swaps two nodes function swapNode(n, v) { n.key = v.key n.value = v.value n.left = v.left n.right = v.right n._color = v._color n._count = v._count } //Fix up a double black node in a tree function fixDoubleBlack(stack) { var n, p, s, z for(var i=stack.length-1; i>=0; --i) { n = stack[i] if(i === 0) { n._color = BLACK return } //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key) p = stack[i-1] if(p.left === n) { //console.log("left child") s = p.right if(s.right && s.right._color === RED) { //console.log("case 1: right sibling child red") s = p.right = cloneNode(s) z = s.right = cloneNode(s.right) p.right = s.left s.left = p s.right = z s._color = p._color n._color = BLACK p._color = BLACK z._color = BLACK recount(p) recount(s) if(i > 1) { var pp = stack[i-2] if(pp.left === p) { pp.left = s } else { pp.right = s } } stack[i-1] = s return } else if(s.left && s.left._color === RED) { //console.log("case 1: left sibling child red") s = p.right = cloneNode(s) z = s.left = cloneNode(s.left) p.right = z.left s.left = z.right z.left = p z.right = s z._color = p._color p._color = BLACK s._color = BLACK n._color = BLACK recount(p) recount(s) recount(z) if(i > 1) { var pp = stack[i-2] if(pp.left === p) { pp.left = z } else { pp.right = z } } stack[i-1] = z return } if(s._color === BLACK) { if(p._color === RED) { //console.log("case 2: black sibling, red parent", p.right.value) p._color = BLACK p.right = repaint(RED, s) return } else { //console.log("case 2: black sibling, black parent", p.right.value) p.right = repaint(RED, s) continue } } else { //console.log("case 3: red sibling") s = cloneNode(s) p.right = s.left s.left = p s._color = p._color p._color = RED recount(p) recount(s) if(i > 1) { var pp = stack[i-2] if(pp.left === p) { pp.left = s } else { pp.right = s } } stack[i-1] = s stack[i] = p if(i+1 < stack.length) { stack[i+1] = n } else { stack.push(n) } i = i+2 } } else { //console.log("right child") s = p.left if(s.left && s.left._color === RED) { //console.log("case 1: left sibling child red", p.value, p._color) s = p.left = cloneNode(s) z = s.left = cloneNode(s.left) p.left = s.right s.right = p s.left = z s._color = p._color n._color = BLACK p._color = BLACK z._color = BLACK recount(p) recount(s) if(i > 1) { var pp = stack[i-2] if(pp.right === p) { pp.right = s } else { pp.left = s } } stack[i-1] = s return } else if(s.right && s.right._color === RED) { //console.log("case 1: right sibling child red") s = p.left = cloneNode(s) z = s.right = cloneNode(s.right) p.left = z.right s.right = z.left z.right = p z.left = s z._color = p._color p._color = BLACK s._color = BLACK n._color = BLACK recount(p) recount(s) recount(z) if(i > 1) { var pp = stack[i-2] if(pp.right === p) { pp.right = z } else { pp.left = z } } stack[i-1] = z return } if(s._color === BLACK) { if(p._color === RED) { //console.log("case 2: black sibling, red parent") p._color = BLACK p.left = repaint(RED, s) return } else { //console.log("case 2: black sibling, black parent") p.left = repaint(RED, s) continue } } else { //console.log("case 3: red sibling") s = cloneNode(s) p.left = s.right s.right = p s._color = p._color p._color = RED recount(p) recount(s) if(i > 1) { var pp = stack[i-2] if(pp.right === p) { pp.right = s } else { pp.left = s } } stack[i-1] = s stack[i] = p if(i+1 < stack.length) { stack[i+1] = n } else { stack.push(n) } i = i+2 } } } } //Removes item at iterator from tree iproto.remove = function() { var stack = this._stack if(stack.length === 0) { return this.tree } //First copy path to node var cstack = new Array(stack.length) var n = stack[stack.length-1] cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count) for(var i=stack.length-2; i>=0; --i) { var n = stack[i] if(n.left === stack[i+1]) { cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) } else { cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) } } //Get node n = cstack[cstack.length-1] //console.log("start remove: ", n.value) //If not leaf, then swap with previous node if(n.left && n.right) { //console.log("moving to leaf") //First walk to previous leaf var split = cstack.length n = n.left while(n.right) { cstack.push(n) n = n.right } //Copy path to leaf var v = cstack[split-1] cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count)) cstack[split-1].key = n.key cstack[split-1].value = n.value //Fix up stack for(var i=cstack.length-2; i>=split; --i) { n = cstack[i] cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) } cstack[split-1].left = cstack[split] } //console.log("stack=", cstack.map(function(v) { return v.value })) //Remove leaf node n = cstack[cstack.length-1] if(n._color === RED) { //Easy case: removing red leaf //console.log("RED leaf") var p = cstack[cstack.length-2] if(p.left === n) { p.left = null } else if(p.right === n) { p.right = null } cstack.pop() for(var i=0; i 0) { return this._stack[this._stack.length-1].key } return }, enumerable: true }) //Returns value Object.defineProperty(iproto, "value", { get: function() { if(this._stack.length > 0) { return this._stack[this._stack.length-1].value } return }, enumerable: true }) //Returns the position of this iterator in the sorted list Object.defineProperty(iproto, "index", { get: function() { var idx = 0 var stack = this._stack if(stack.length === 0) { var r = this.tree.root if(r) { return r._count } return 0 } else if(stack[stack.length-1].left) { idx = stack[stack.length-1].left._count } for(var s=stack.length-2; s>=0; --s) { if(stack[s+1] === stack[s].right) { ++idx if(stack[s].left) { idx += stack[s].left._count } } } return idx }, enumerable: true }) //Advances iterator to next element in list iproto.next = function() { var stack = this._stack if(stack.length === 0) { return } var n = stack[stack.length-1] if(n.right) { n = n.right while(n) { stack.push(n) n = n.left } } else { stack.pop() while(stack.length > 0 && stack[stack.length-1].right === n) { n = stack[stack.length-1] stack.pop() } } } //Checks if iterator is at end of tree Object.defineProperty(iproto, "hasNext", { get: function() { var stack = this._stack if(stack.length === 0) { return false } if(stack[stack.length-1].right) { return true } for(var s=stack.length-1; s>0; --s) { if(stack[s-1].left === stack[s]) { return true } } return false } }) //Update value iproto.update = function(value) { var stack = this._stack if(stack.length === 0) { throw new Error("Can't update empty node!") } var cstack = new Array(stack.length) var n = stack[stack.length-1] cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count) for(var i=stack.length-2; i>=0; --i) { n = stack[i] if(n.left === stack[i+1]) { cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) } else { cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) } } return new RedBlackTree(this.tree._compare, cstack[0]) } //Moves iterator backward one element iproto.prev = function() { var stack = this._stack if(stack.length === 0) { return } var n = stack[stack.length-1] if(n.left) { n = n.left while(n) { stack.push(n) n = n.right } } else { stack.pop() while(stack.length > 0 && stack[stack.length-1].left === n) { n = stack[stack.length-1] stack.pop() } } } //Checks if iterator is at start of tree Object.defineProperty(iproto, "hasPrev", { get: function() { var stack = this._stack if(stack.length === 0) { return false } if(stack[stack.length-1].left) { return true } for(var s=stack.length-1; s>0; --s) { if(stack[s-1].right === stack[s]) { return true } } return false } }) //Default comparison function function defaultCompare(a, b) { if(a < b) { return -1 } if(a > b) { return 1 } return 0 } //Build a tree function createRBTree(compare) { return new RedBlackTree(compare || defaultCompare, null) } /***/ }), /***/ 210: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var undefined; var $SyntaxError = SyntaxError; var $Function = Function; var $TypeError = TypeError; // eslint-disable-next-line consistent-return var getEvalledConstructor = function (expressionSyntax) { try { return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); } catch (e) {} }; var $gOPD = Object.getOwnPropertyDescriptor; if ($gOPD) { try { $gOPD({}, ''); } catch (e) { $gOPD = null; // this is IE 8, which has a broken gOPD } } var throwTypeError = function () { throw new $TypeError(); }; var ThrowTypeError = $gOPD ? (function () { try { // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties arguments.callee; // IE 8 does not throw here return throwTypeError; } catch (calleeThrows) { try { // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') return $gOPD(arguments, 'callee').get; } catch (gOPDthrows) { return throwTypeError; } } }()) : throwTypeError; var hasSymbols = __webpack_require__(1405)(); var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto var needsEval = {}; var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); var INTRINSICS = { '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, '%Array%': Array, '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, '%AsyncFromSyncIteratorPrototype%': undefined, '%AsyncFunction%': needsEval, '%AsyncGenerator%': needsEval, '%AsyncGeneratorFunction%': needsEval, '%AsyncIteratorPrototype%': needsEval, '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, '%Boolean%': Boolean, '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, '%Date%': Date, '%decodeURI%': decodeURI, '%decodeURIComponent%': decodeURIComponent, '%encodeURI%': encodeURI, '%encodeURIComponent%': encodeURIComponent, '%Error%': Error, '%eval%': eval, // eslint-disable-line no-eval '%EvalError%': EvalError, '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, '%Function%': $Function, '%GeneratorFunction%': needsEval, '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, '%isFinite%': isFinite, '%isNaN%': isNaN, '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, '%JSON%': typeof JSON === 'object' ? JSON : undefined, '%Map%': typeof Map === 'undefined' ? undefined : Map, '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), '%Math%': Math, '%Number%': Number, '%Object%': Object, '%parseFloat%': parseFloat, '%parseInt%': parseInt, '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, '%RangeError%': RangeError, '%ReferenceError%': ReferenceError, '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, '%RegExp%': RegExp, '%Set%': typeof Set === 'undefined' ? undefined : Set, '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, '%String%': String, '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, '%Symbol%': hasSymbols ? Symbol : undefined, '%SyntaxError%': $SyntaxError, '%ThrowTypeError%': ThrowTypeError, '%TypedArray%': TypedArray, '%TypeError%': $TypeError, '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, '%URIError%': URIError, '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet }; var doEval = function doEval(name) { var value; if (name === '%AsyncFunction%') { value = getEvalledConstructor('async function () {}'); } else if (name === '%GeneratorFunction%') { value = getEvalledConstructor('function* () {}'); } else if (name === '%AsyncGeneratorFunction%') { value = getEvalledConstructor('async function* () {}'); } else if (name === '%AsyncGenerator%') { var fn = doEval('%AsyncGeneratorFunction%'); if (fn) { value = fn.prototype; } } else if (name === '%AsyncIteratorPrototype%') { var gen = doEval('%AsyncGenerator%'); if (gen) { value = getProto(gen.prototype); } } INTRINSICS[name] = value; return value; }; var LEGACY_ALIASES = { '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], '%ArrayPrototype%': ['Array', 'prototype'], '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], '%ArrayProto_values%': ['Array', 'prototype', 'values'], '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], '%BooleanPrototype%': ['Boolean', 'prototype'], '%DataViewPrototype%': ['DataView', 'prototype'], '%DatePrototype%': ['Date', 'prototype'], '%ErrorPrototype%': ['Error', 'prototype'], '%EvalErrorPrototype%': ['EvalError', 'prototype'], '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], '%FunctionPrototype%': ['Function', 'prototype'], '%Generator%': ['GeneratorFunction', 'prototype'], '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], '%JSONParse%': ['JSON', 'parse'], '%JSONStringify%': ['JSON', 'stringify'], '%MapPrototype%': ['Map', 'prototype'], '%NumberPrototype%': ['Number', 'prototype'], '%ObjectPrototype%': ['Object', 'prototype'], '%ObjProto_toString%': ['Object', 'prototype', 'toString'], '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], '%PromisePrototype%': ['Promise', 'prototype'], '%PromiseProto_then%': ['Promise', 'prototype', 'then'], '%Promise_all%': ['Promise', 'all'], '%Promise_reject%': ['Promise', 'reject'], '%Promise_resolve%': ['Promise', 'resolve'], '%RangeErrorPrototype%': ['RangeError', 'prototype'], '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], '%RegExpPrototype%': ['RegExp', 'prototype'], '%SetPrototype%': ['Set', 'prototype'], '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], '%StringPrototype%': ['String', 'prototype'], '%SymbolPrototype%': ['Symbol', 'prototype'], '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], '%TypedArrayPrototype%': ['TypedArray', 'prototype'], '%TypeErrorPrototype%': ['TypeError', 'prototype'], '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], '%URIErrorPrototype%': ['URIError', 'prototype'], '%WeakMapPrototype%': ['WeakMap', 'prototype'], '%WeakSetPrototype%': ['WeakSet', 'prototype'] }; var bind = __webpack_require__(8612); var hasOwn = __webpack_require__(7642); var $concat = bind.call(Function.call, Array.prototype.concat); var $spliceApply = bind.call(Function.apply, Array.prototype.splice); var $replace = bind.call(Function.call, String.prototype.replace); var $strSlice = bind.call(Function.call, String.prototype.slice); var $exec = bind.call(Function.call, RegExp.prototype.exec); /* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ var stringToPath = function stringToPath(string) { var first = $strSlice(string, 0, 1); var last = $strSlice(string, -1); if (first === '%' && last !== '%') { throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); } else if (last === '%' && first !== '%') { throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); } var result = []; $replace(string, rePropName, function (match, number, quote, subString) { result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; }); return result; }; /* end adaptation */ var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { var intrinsicName = name; var alias; if (hasOwn(LEGACY_ALIASES, intrinsicName)) { alias = LEGACY_ALIASES[intrinsicName]; intrinsicName = '%' + alias[0] + '%'; } if (hasOwn(INTRINSICS, intrinsicName)) { var value = INTRINSICS[intrinsicName]; if (value === needsEval) { value = doEval(intrinsicName); } if (typeof value === 'undefined' && !allowMissing) { throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); } return { alias: alias, name: intrinsicName, value: value }; } throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); }; module.exports = function GetIntrinsic(name, allowMissing) { if (typeof name !== 'string' || name.length === 0) { throw new $TypeError('intrinsic name must be a non-empty string'); } if (arguments.length > 1 && typeof allowMissing !== 'boolean') { throw new $TypeError('"allowMissing" argument must be a boolean'); } if ($exec(/^%?[^%]*%?$/g, name) === null) { throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); } var parts = stringToPath(name); var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); var intrinsicRealName = intrinsic.name; var value = intrinsic.value; var skipFurtherCaching = false; var alias = intrinsic.alias; if (alias) { intrinsicBaseName = alias[0]; $spliceApply(parts, $concat([0, 1], alias)); } for (var i = 1, isOwn = true; i < parts.length; i += 1) { var part = parts[i]; var first = $strSlice(part, 0, 1); var last = $strSlice(part, -1); if ( ( (first === '"' || first === "'" || first === '`') || (last === '"' || last === "'" || last === '`') ) && first !== last ) { throw new $SyntaxError('property names with quotes must have matching quotes'); } if (part === 'constructor' || !isOwn) { skipFurtherCaching = true; } intrinsicBaseName += '.' + part; intrinsicRealName = '%' + intrinsicBaseName + '%'; if (hasOwn(INTRINSICS, intrinsicRealName)) { value = INTRINSICS[intrinsicRealName]; } else if (value != null) { if (!(part in value)) { if (!allowMissing) { throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); } return void undefined; } if ($gOPD && (i + 1) >= parts.length) { var desc = $gOPD(value, part); isOwn = !!desc; // By convention, when a data property is converted to an accessor // property to emulate a data property that does not suffer from // the override mistake, that accessor's getter is marked with // an `originalValue` property. Here, when we detect this, we // uphold the illusion by pretending to see that original data // property, i.e., returning the value rather than the getter // itself. if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { value = desc.get; } else { value = value[part]; } } else { isOwn = hasOwn(value, part); value = value[part]; } if (isOwn && !skipFurtherCaching) { INTRINSICS[intrinsicRealName] = value; } } } return value; }; /***/ }), /***/ 1405: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var origSymbol = typeof Symbol !== 'undefined' && Symbol; var hasSymbolSham = __webpack_require__(5419); module.exports = function hasNativeSymbols() { if (typeof origSymbol !== 'function') { return false; } if (typeof Symbol !== 'function') { return false; } if (typeof origSymbol('foo') !== 'symbol') { return false; } if (typeof Symbol('bar') !== 'symbol') { return false; } return hasSymbolSham(); }; /***/ }), /***/ 5419: /***/ (function(module) { "use strict"; /* eslint complexity: [2, 18], max-statements: [2, 33] */ module.exports = function hasSymbols() { if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } if (typeof Symbol.iterator === 'symbol') { return true; } var obj = {}; var sym = Symbol('test'); var symObj = Object(sym); if (typeof sym === 'string') { return false; } if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } // temp disabled per https://github.com/ljharb/object.assign/issues/17 // if (sym instanceof Symbol) { return false; } // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 // if (!(symObj instanceof Symbol)) { return false; } // if (typeof Symbol.prototype.toString !== 'function') { return false; } // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } var symVal = 42; obj[sym] = symVal; for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } var syms = Object.getOwnPropertySymbols(obj); if (syms.length !== 1 || syms[0] !== sym) { return false; } if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } if (typeof Object.getOwnPropertyDescriptor === 'function') { var descriptor = Object.getOwnPropertyDescriptor(obj, sym); if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } } return true; }; /***/ }), /***/ 6410: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var hasSymbols = __webpack_require__(5419); module.exports = function hasToStringTagShams() { return hasSymbols() && !!Symbol.toStringTag; }; /***/ }), /***/ 7642: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var bind = __webpack_require__(8612); module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); /***/ }), /***/ 3715: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { var hash = exports; hash.utils = __webpack_require__(6436); hash.common = __webpack_require__(5772); hash.sha = __webpack_require__(9041); hash.ripemd = __webpack_require__(2949); hash.hmac = __webpack_require__(2344); // Proxy hash functions to the main object hash.sha1 = hash.sha.sha1; hash.sha256 = hash.sha.sha256; hash.sha224 = hash.sha.sha224; hash.sha384 = hash.sha.sha384; hash.sha512 = hash.sha.sha512; hash.ripemd160 = hash.ripemd.ripemd160; /***/ }), /***/ 5772: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(6436); var assert = __webpack_require__(9746); function BlockHash() { this.pending = null; this.pendingTotal = 0; this.blockSize = this.constructor.blockSize; this.outSize = this.constructor.outSize; this.hmacStrength = this.constructor.hmacStrength; this.padLength = this.constructor.padLength / 8; this.endian = 'big'; this._delta8 = this.blockSize / 8; this._delta32 = this.blockSize / 32; } exports.BlockHash = BlockHash; BlockHash.prototype.update = function update(msg, enc) { // Convert message to array, pad it, and join into 32bit blocks msg = utils.toArray(msg, enc); if (!this.pending) this.pending = msg; else this.pending = this.pending.concat(msg); this.pendingTotal += msg.length; // Enough data, try updating if (this.pending.length >= this._delta8) { msg = this.pending; // Process pending data in blocks var r = msg.length % this._delta8; this.pending = msg.slice(msg.length - r, msg.length); if (this.pending.length === 0) this.pending = null; msg = utils.join32(msg, 0, msg.length - r, this.endian); for (var i = 0; i < msg.length; i += this._delta32) this._update(msg, i, i + this._delta32); } return this; }; BlockHash.prototype.digest = function digest(enc) { this.update(this._pad()); assert(this.pending === null); return this._digest(enc); }; BlockHash.prototype._pad = function pad() { var len = this.pendingTotal; var bytes = this._delta8; var k = bytes - ((len + this.padLength) % bytes); var res = new Array(k + this.padLength); res[0] = 0x80; for (var i = 1; i < k; i++) res[i] = 0; // Append length len <<= 3; if (this.endian === 'big') { for (var t = 8; t < this.padLength; t++) res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = (len >>> 24) & 0xff; res[i++] = (len >>> 16) & 0xff; res[i++] = (len >>> 8) & 0xff; res[i++] = len & 0xff; } else { res[i++] = len & 0xff; res[i++] = (len >>> 8) & 0xff; res[i++] = (len >>> 16) & 0xff; res[i++] = (len >>> 24) & 0xff; res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = 0; for (t = 8; t < this.padLength; t++) res[i++] = 0; } return res; }; /***/ }), /***/ 2344: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(6436); var assert = __webpack_require__(9746); function Hmac(hash, key, enc) { if (!(this instanceof Hmac)) return new Hmac(hash, key, enc); this.Hash = hash; this.blockSize = hash.blockSize / 8; this.outSize = hash.outSize / 8; this.inner = null; this.outer = null; this._init(utils.toArray(key, enc)); } module.exports = Hmac; Hmac.prototype._init = function init(key) { // Shorten key, if needed if (key.length > this.blockSize) key = new this.Hash().update(key).digest(); assert(key.length <= this.blockSize); // Add padding to key for (var i = key.length; i < this.blockSize; i++) key.push(0); for (i = 0; i < key.length; i++) key[i] ^= 0x36; this.inner = new this.Hash().update(key); // 0x36 ^ 0x5c = 0x6a for (i = 0; i < key.length; i++) key[i] ^= 0x6a; this.outer = new this.Hash().update(key); }; Hmac.prototype.update = function update(msg, enc) { this.inner.update(msg, enc); return this; }; Hmac.prototype.digest = function digest(enc) { this.outer.update(this.inner.digest()); return this.outer.digest(enc); }; /***/ }), /***/ 2949: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(6436); var common = __webpack_require__(5772); var rotl32 = utils.rotl32; var sum32 = utils.sum32; var sum32_3 = utils.sum32_3; var sum32_4 = utils.sum32_4; var BlockHash = common.BlockHash; function RIPEMD160() { if (!(this instanceof RIPEMD160)) return new RIPEMD160(); BlockHash.call(this); this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; this.endian = 'little'; } utils.inherits(RIPEMD160, BlockHash); exports.ripemd160 = RIPEMD160; RIPEMD160.blockSize = 512; RIPEMD160.outSize = 160; RIPEMD160.hmacStrength = 192; RIPEMD160.padLength = 64; RIPEMD160.prototype._update = function update(msg, start) { var A = this.h[0]; var B = this.h[1]; var C = this.h[2]; var D = this.h[3]; var E = this.h[4]; var Ah = A; var Bh = B; var Ch = C; var Dh = D; var Eh = E; for (var j = 0; j < 80; j++) { var T = sum32( rotl32( sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), s[j]), E); A = E; E = D; D = rotl32(C, 10); C = B; B = T; T = sum32( rotl32( sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), sh[j]), Eh); Ah = Eh; Eh = Dh; Dh = rotl32(Ch, 10); Ch = Bh; Bh = T; } T = sum32_3(this.h[1], C, Dh); this.h[1] = sum32_3(this.h[2], D, Eh); this.h[2] = sum32_3(this.h[3], E, Ah); this.h[3] = sum32_3(this.h[4], A, Bh); this.h[4] = sum32_3(this.h[0], B, Ch); this.h[0] = T; }; RIPEMD160.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h, 'little'); else return utils.split32(this.h, 'little'); }; function f(j, x, y, z) { if (j <= 15) return x ^ y ^ z; else if (j <= 31) return (x & y) | ((~x) & z); else if (j <= 47) return (x | (~y)) ^ z; else if (j <= 63) return (x & z) | (y & (~z)); else return x ^ (y | (~z)); } function K(j) { if (j <= 15) return 0x00000000; else if (j <= 31) return 0x5a827999; else if (j <= 47) return 0x6ed9eba1; else if (j <= 63) return 0x8f1bbcdc; else return 0xa953fd4e; } function Kh(j) { if (j <= 15) return 0x50a28be6; else if (j <= 31) return 0x5c4dd124; else if (j <= 47) return 0x6d703ef3; else if (j <= 63) return 0x7a6d76e9; else return 0x00000000; } var r = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 ]; var rh = [ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 ]; var s = [ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]; var sh = [ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]; /***/ }), /***/ 9041: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; exports.sha1 = __webpack_require__(4761); exports.sha224 = __webpack_require__(799); exports.sha256 = __webpack_require__(9344); exports.sha384 = __webpack_require__(772); exports.sha512 = __webpack_require__(5900); /***/ }), /***/ 4761: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(6436); var common = __webpack_require__(5772); var shaCommon = __webpack_require__(7038); var rotl32 = utils.rotl32; var sum32 = utils.sum32; var sum32_5 = utils.sum32_5; var ft_1 = shaCommon.ft_1; var BlockHash = common.BlockHash; var sha1_K = [ 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 ]; function SHA1() { if (!(this instanceof SHA1)) return new SHA1(); BlockHash.call(this); this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; this.W = new Array(80); } utils.inherits(SHA1, BlockHash); module.exports = SHA1; SHA1.blockSize = 512; SHA1.outSize = 160; SHA1.hmacStrength = 80; SHA1.padLength = 64; SHA1.prototype._update = function _update(msg, start) { var W = this.W; for (var i = 0; i < 16; i++) W[i] = msg[start + i]; for(; i < W.length; i++) W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); var a = this.h[0]; var b = this.h[1]; var c = this.h[2]; var d = this.h[3]; var e = this.h[4]; for (i = 0; i < W.length; i++) { var s = ~~(i / 20); var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); e = d; d = c; c = rotl32(b, 30); b = a; a = t; } this.h[0] = sum32(this.h[0], a); this.h[1] = sum32(this.h[1], b); this.h[2] = sum32(this.h[2], c); this.h[3] = sum32(this.h[3], d); this.h[4] = sum32(this.h[4], e); }; SHA1.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h, 'big'); else return utils.split32(this.h, 'big'); }; /***/ }), /***/ 799: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(6436); var SHA256 = __webpack_require__(9344); function SHA224() { if (!(this instanceof SHA224)) return new SHA224(); SHA256.call(this); this.h = [ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; } utils.inherits(SHA224, SHA256); module.exports = SHA224; SHA224.blockSize = 512; SHA224.outSize = 224; SHA224.hmacStrength = 192; SHA224.padLength = 64; SHA224.prototype._digest = function digest(enc) { // Just truncate output if (enc === 'hex') return utils.toHex32(this.h.slice(0, 7), 'big'); else return utils.split32(this.h.slice(0, 7), 'big'); }; /***/ }), /***/ 9344: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(6436); var common = __webpack_require__(5772); var shaCommon = __webpack_require__(7038); var assert = __webpack_require__(9746); var sum32 = utils.sum32; var sum32_4 = utils.sum32_4; var sum32_5 = utils.sum32_5; var ch32 = shaCommon.ch32; var maj32 = shaCommon.maj32; var s0_256 = shaCommon.s0_256; var s1_256 = shaCommon.s1_256; var g0_256 = shaCommon.g0_256; var g1_256 = shaCommon.g1_256; var BlockHash = common.BlockHash; var sha256_K = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; function SHA256() { if (!(this instanceof SHA256)) return new SHA256(); BlockHash.call(this); this.h = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; this.k = sha256_K; this.W = new Array(64); } utils.inherits(SHA256, BlockHash); module.exports = SHA256; SHA256.blockSize = 512; SHA256.outSize = 256; SHA256.hmacStrength = 192; SHA256.padLength = 64; SHA256.prototype._update = function _update(msg, start) { var W = this.W; for (var i = 0; i < 16; i++) W[i] = msg[start + i]; for (; i < W.length; i++) W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); var a = this.h[0]; var b = this.h[1]; var c = this.h[2]; var d = this.h[3]; var e = this.h[4]; var f = this.h[5]; var g = this.h[6]; var h = this.h[7]; assert(this.k.length === W.length); for (i = 0; i < W.length; i++) { var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); var T2 = sum32(s0_256(a), maj32(a, b, c)); h = g; g = f; f = e; e = sum32(d, T1); d = c; c = b; b = a; a = sum32(T1, T2); } this.h[0] = sum32(this.h[0], a); this.h[1] = sum32(this.h[1], b); this.h[2] = sum32(this.h[2], c); this.h[3] = sum32(this.h[3], d); this.h[4] = sum32(this.h[4], e); this.h[5] = sum32(this.h[5], f); this.h[6] = sum32(this.h[6], g); this.h[7] = sum32(this.h[7], h); }; SHA256.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h, 'big'); else return utils.split32(this.h, 'big'); }; /***/ }), /***/ 772: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(6436); var SHA512 = __webpack_require__(5900); function SHA384() { if (!(this instanceof SHA384)) return new SHA384(); SHA512.call(this); this.h = [ 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939, 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4 ]; } utils.inherits(SHA384, SHA512); module.exports = SHA384; SHA384.blockSize = 1024; SHA384.outSize = 384; SHA384.hmacStrength = 192; SHA384.padLength = 128; SHA384.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h.slice(0, 12), 'big'); else return utils.split32(this.h.slice(0, 12), 'big'); }; /***/ }), /***/ 5900: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(6436); var common = __webpack_require__(5772); var assert = __webpack_require__(9746); var rotr64_hi = utils.rotr64_hi; var rotr64_lo = utils.rotr64_lo; var shr64_hi = utils.shr64_hi; var shr64_lo = utils.shr64_lo; var sum64 = utils.sum64; var sum64_hi = utils.sum64_hi; var sum64_lo = utils.sum64_lo; var sum64_4_hi = utils.sum64_4_hi; var sum64_4_lo = utils.sum64_4_lo; var sum64_5_hi = utils.sum64_5_hi; var sum64_5_lo = utils.sum64_5_lo; var BlockHash = common.BlockHash; var sha512_K = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ]; function SHA512() { if (!(this instanceof SHA512)) return new SHA512(); BlockHash.call(this); this.h = [ 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179 ]; this.k = sha512_K; this.W = new Array(160); } utils.inherits(SHA512, BlockHash); module.exports = SHA512; SHA512.blockSize = 1024; SHA512.outSize = 512; SHA512.hmacStrength = 192; SHA512.padLength = 128; SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { var W = this.W; // 32 x 32bit words for (var i = 0; i < 32; i++) W[i] = msg[start + i]; for (; i < W.length; i += 2) { var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); var c1_hi = W[i - 14]; // i - 7 var c1_lo = W[i - 13]; var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); var c3_hi = W[i - 32]; // i - 16 var c3_lo = W[i - 31]; W[i] = sum64_4_hi( c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo); W[i + 1] = sum64_4_lo( c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo); } }; SHA512.prototype._update = function _update(msg, start) { this._prepareBlock(msg, start); var W = this.W; var ah = this.h[0]; var al = this.h[1]; var bh = this.h[2]; var bl = this.h[3]; var ch = this.h[4]; var cl = this.h[5]; var dh = this.h[6]; var dl = this.h[7]; var eh = this.h[8]; var el = this.h[9]; var fh = this.h[10]; var fl = this.h[11]; var gh = this.h[12]; var gl = this.h[13]; var hh = this.h[14]; var hl = this.h[15]; assert(this.k.length === W.length); for (var i = 0; i < W.length; i += 2) { var c0_hi = hh; var c0_lo = hl; var c1_hi = s1_512_hi(eh, el); var c1_lo = s1_512_lo(eh, el); var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); var c3_hi = this.k[i]; var c3_lo = this.k[i + 1]; var c4_hi = W[i]; var c4_lo = W[i + 1]; var T1_hi = sum64_5_hi( c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo); var T1_lo = sum64_5_lo( c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo); c0_hi = s0_512_hi(ah, al); c0_lo = s0_512_lo(ah, al); c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; eh = sum64_hi(dh, dl, T1_hi, T1_lo); el = sum64_lo(dl, dl, T1_hi, T1_lo); dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); } sum64(this.h, 0, ah, al); sum64(this.h, 2, bh, bl); sum64(this.h, 4, ch, cl); sum64(this.h, 6, dh, dl); sum64(this.h, 8, eh, el); sum64(this.h, 10, fh, fl); sum64(this.h, 12, gh, gl); sum64(this.h, 14, hh, hl); }; SHA512.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h, 'big'); else return utils.split32(this.h, 'big'); }; function ch64_hi(xh, xl, yh, yl, zh) { var r = (xh & yh) ^ ((~xh) & zh); if (r < 0) r += 0x100000000; return r; } function ch64_lo(xh, xl, yh, yl, zh, zl) { var r = (xl & yl) ^ ((~xl) & zl); if (r < 0) r += 0x100000000; return r; } function maj64_hi(xh, xl, yh, yl, zh) { var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); if (r < 0) r += 0x100000000; return r; } function maj64_lo(xh, xl, yh, yl, zh, zl) { var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); if (r < 0) r += 0x100000000; return r; } function s0_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 28); var c1_hi = rotr64_hi(xl, xh, 2); // 34 var c2_hi = rotr64_hi(xl, xh, 7); // 39 var r = c0_hi ^ c1_hi ^ c2_hi; if (r < 0) r += 0x100000000; return r; } function s0_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 28); var c1_lo = rotr64_lo(xl, xh, 2); // 34 var c2_lo = rotr64_lo(xl, xh, 7); // 39 var r = c0_lo ^ c1_lo ^ c2_lo; if (r < 0) r += 0x100000000; return r; } function s1_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 14); var c1_hi = rotr64_hi(xh, xl, 18); var c2_hi = rotr64_hi(xl, xh, 9); // 41 var r = c0_hi ^ c1_hi ^ c2_hi; if (r < 0) r += 0x100000000; return r; } function s1_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 14); var c1_lo = rotr64_lo(xh, xl, 18); var c2_lo = rotr64_lo(xl, xh, 9); // 41 var r = c0_lo ^ c1_lo ^ c2_lo; if (r < 0) r += 0x100000000; return r; } function g0_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 1); var c1_hi = rotr64_hi(xh, xl, 8); var c2_hi = shr64_hi(xh, xl, 7); var r = c0_hi ^ c1_hi ^ c2_hi; if (r < 0) r += 0x100000000; return r; } function g0_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 1); var c1_lo = rotr64_lo(xh, xl, 8); var c2_lo = shr64_lo(xh, xl, 7); var r = c0_lo ^ c1_lo ^ c2_lo; if (r < 0) r += 0x100000000; return r; } function g1_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 19); var c1_hi = rotr64_hi(xl, xh, 29); // 61 var c2_hi = shr64_hi(xh, xl, 6); var r = c0_hi ^ c1_hi ^ c2_hi; if (r < 0) r += 0x100000000; return r; } function g1_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 19); var c1_lo = rotr64_lo(xl, xh, 29); // 61 var c2_lo = shr64_lo(xh, xl, 6); var r = c0_lo ^ c1_lo ^ c2_lo; if (r < 0) r += 0x100000000; return r; } /***/ }), /***/ 7038: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(6436); var rotr32 = utils.rotr32; function ft_1(s, x, y, z) { if (s === 0) return ch32(x, y, z); if (s === 1 || s === 3) return p32(x, y, z); if (s === 2) return maj32(x, y, z); } exports.ft_1 = ft_1; function ch32(x, y, z) { return (x & y) ^ ((~x) & z); } exports.ch32 = ch32; function maj32(x, y, z) { return (x & y) ^ (x & z) ^ (y & z); } exports.maj32 = maj32; function p32(x, y, z) { return x ^ y ^ z; } exports.p32 = p32; function s0_256(x) { return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); } exports.s0_256 = s0_256; function s1_256(x) { return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); } exports.s1_256 = s1_256; function g0_256(x) { return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); } exports.g0_256 = g0_256; function g1_256(x) { return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); } exports.g1_256 = g1_256; /***/ }), /***/ 6436: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var assert = __webpack_require__(9746); var inherits = __webpack_require__(5717); exports.inherits = inherits; function isSurrogatePair(msg, i) { if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { return false; } if (i < 0 || i + 1 >= msg.length) { return false; } return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00; } function toArray(msg, enc) { if (Array.isArray(msg)) return msg.slice(); if (!msg) return []; var res = []; if (typeof msg === 'string') { if (!enc) { // Inspired by stringToUtf8ByteArray() in closure-library by Google // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143 // Apache License 2.0 // https://github.com/google/closure-library/blob/master/LICENSE var p = 0; for (var i = 0; i < msg.length; i++) { var c = msg.charCodeAt(i); if (c < 128) { res[p++] = c; } else if (c < 2048) { res[p++] = (c >> 6) | 192; res[p++] = (c & 63) | 128; } else if (isSurrogatePair(msg, i)) { c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF); res[p++] = (c >> 18) | 240; res[p++] = ((c >> 12) & 63) | 128; res[p++] = ((c >> 6) & 63) | 128; res[p++] = (c & 63) | 128; } else { res[p++] = (c >> 12) | 224; res[p++] = ((c >> 6) & 63) | 128; res[p++] = (c & 63) | 128; } } } else if (enc === 'hex') { msg = msg.replace(/[^a-z0-9]+/ig, ''); if (msg.length % 2 !== 0) msg = '0' + msg; for (i = 0; i < msg.length; i += 2) res.push(parseInt(msg[i] + msg[i + 1], 16)); } } else { for (i = 0; i < msg.length; i++) res[i] = msg[i] | 0; } return res; } exports.toArray = toArray; function toHex(msg) { var res = ''; for (var i = 0; i < msg.length; i++) res += zero2(msg[i].toString(16)); return res; } exports.toHex = toHex; function htonl(w) { var res = (w >>> 24) | ((w >>> 8) & 0xff00) | ((w << 8) & 0xff0000) | ((w & 0xff) << 24); return res >>> 0; } exports.htonl = htonl; function toHex32(msg, endian) { var res = ''; for (var i = 0; i < msg.length; i++) { var w = msg[i]; if (endian === 'little') w = htonl(w); res += zero8(w.toString(16)); } return res; } exports.toHex32 = toHex32; function zero2(word) { if (word.length === 1) return '0' + word; else return word; } exports.zero2 = zero2; function zero8(word) { if (word.length === 7) return '0' + word; else if (word.length === 6) return '00' + word; else if (word.length === 5) return '000' + word; else if (word.length === 4) return '0000' + word; else if (word.length === 3) return '00000' + word; else if (word.length === 2) return '000000' + word; else if (word.length === 1) return '0000000' + word; else return word; } exports.zero8 = zero8; function join32(msg, start, end, endian) { var len = end - start; assert(len % 4 === 0); var res = new Array(len / 4); for (var i = 0, k = start; i < res.length; i++, k += 4) { var w; if (endian === 'big') w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; else w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; res[i] = w >>> 0; } return res; } exports.join32 = join32; function split32(msg, endian) { var res = new Array(msg.length * 4); for (var i = 0, k = 0; i < msg.length; i++, k += 4) { var m = msg[i]; if (endian === 'big') { res[k] = m >>> 24; res[k + 1] = (m >>> 16) & 0xff; res[k + 2] = (m >>> 8) & 0xff; res[k + 3] = m & 0xff; } else { res[k + 3] = m >>> 24; res[k + 2] = (m >>> 16) & 0xff; res[k + 1] = (m >>> 8) & 0xff; res[k] = m & 0xff; } } return res; } exports.split32 = split32; function rotr32(w, b) { return (w >>> b) | (w << (32 - b)); } exports.rotr32 = rotr32; function rotl32(w, b) { return (w << b) | (w >>> (32 - b)); } exports.rotl32 = rotl32; function sum32(a, b) { return (a + b) >>> 0; } exports.sum32 = sum32; function sum32_3(a, b, c) { return (a + b + c) >>> 0; } exports.sum32_3 = sum32_3; function sum32_4(a, b, c, d) { return (a + b + c + d) >>> 0; } exports.sum32_4 = sum32_4; function sum32_5(a, b, c, d, e) { return (a + b + c + d + e) >>> 0; } exports.sum32_5 = sum32_5; function sum64(buf, pos, ah, al) { var bh = buf[pos]; var bl = buf[pos + 1]; var lo = (al + bl) >>> 0; var hi = (lo < al ? 1 : 0) + ah + bh; buf[pos] = hi >>> 0; buf[pos + 1] = lo; } exports.sum64 = sum64; function sum64_hi(ah, al, bh, bl) { var lo = (al + bl) >>> 0; var hi = (lo < al ? 1 : 0) + ah + bh; return hi >>> 0; } exports.sum64_hi = sum64_hi; function sum64_lo(ah, al, bh, bl) { var lo = al + bl; return lo >>> 0; } exports.sum64_lo = sum64_lo; function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { var carry = 0; var lo = al; lo = (lo + bl) >>> 0; carry += lo < al ? 1 : 0; lo = (lo + cl) >>> 0; carry += lo < cl ? 1 : 0; lo = (lo + dl) >>> 0; carry += lo < dl ? 1 : 0; var hi = ah + bh + ch + dh + carry; return hi >>> 0; } exports.sum64_4_hi = sum64_4_hi; function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { var lo = al + bl + cl + dl; return lo >>> 0; } exports.sum64_4_lo = sum64_4_lo; function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var carry = 0; var lo = al; lo = (lo + bl) >>> 0; carry += lo < al ? 1 : 0; lo = (lo + cl) >>> 0; carry += lo < cl ? 1 : 0; lo = (lo + dl) >>> 0; carry += lo < dl ? 1 : 0; lo = (lo + el) >>> 0; carry += lo < el ? 1 : 0; var hi = ah + bh + ch + dh + eh + carry; return hi >>> 0; } exports.sum64_5_hi = sum64_5_hi; function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var lo = al + bl + cl + dl + el; return lo >>> 0; } exports.sum64_5_lo = sum64_5_lo; function rotr64_hi(ah, al, num) { var r = (al << (32 - num)) | (ah >>> num); return r >>> 0; } exports.rotr64_hi = rotr64_hi; function rotr64_lo(ah, al, num) { var r = (ah << (32 - num)) | (al >>> num); return r >>> 0; } exports.rotr64_lo = rotr64_lo; function shr64_hi(ah, al, num) { return ah >>> num; } exports.shr64_hi = shr64_hi; function shr64_lo(ah, al, num) { var r = (ah << (32 - num)) | (al >>> num); return r >>> 0; } exports.shr64_lo = shr64_lo; /***/ }), /***/ 2156: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var hash = __webpack_require__(3715); var utils = __webpack_require__(4504); var assert = __webpack_require__(9746); function HmacDRBG(options) { if (!(this instanceof HmacDRBG)) return new HmacDRBG(options); this.hash = options.hash; this.predResist = !!options.predResist; this.outLen = this.hash.outSize; this.minEntropy = options.minEntropy || this.hash.hmacStrength; this._reseed = null; this.reseedInterval = null; this.K = null; this.V = null; var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex'); var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex'); var pers = utils.toArray(options.pers, options.persEnc || 'hex'); assert(entropy.length >= (this.minEntropy / 8), 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); this._init(entropy, nonce, pers); } module.exports = HmacDRBG; HmacDRBG.prototype._init = function init(entropy, nonce, pers) { var seed = entropy.concat(nonce).concat(pers); this.K = new Array(this.outLen / 8); this.V = new Array(this.outLen / 8); for (var i = 0; i < this.V.length; i++) { this.K[i] = 0x00; this.V[i] = 0x01; } this._update(seed); this._reseed = 1; this.reseedInterval = 0x1000000000000; // 2^48 }; HmacDRBG.prototype._hmac = function hmac() { return new hash.hmac(this.hash, this.K); }; HmacDRBG.prototype._update = function update(seed) { var kmac = this._hmac() .update(this.V) .update([ 0x00 ]); if (seed) kmac = kmac.update(seed); this.K = kmac.digest(); this.V = this._hmac().update(this.V).digest(); if (!seed) return; this.K = this._hmac() .update(this.V) .update([ 0x01 ]) .update(seed) .digest(); this.V = this._hmac().update(this.V).digest(); }; HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { // Optional entropy enc if (typeof entropyEnc !== 'string') { addEnc = add; add = entropyEnc; entropyEnc = null; } entropy = utils.toArray(entropy, entropyEnc); add = utils.toArray(add, addEnc); assert(entropy.length >= (this.minEntropy / 8), 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); this._update(entropy.concat(add || [])); this._reseed = 1; }; HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { if (this._reseed > this.reseedInterval) throw new Error('Reseed is required'); // Optional encoding if (typeof enc !== 'string') { addEnc = add; add = enc; enc = null; } // Optional additional data if (add) { add = utils.toArray(add, addEnc || 'hex'); this._update(add); } var temp = []; while (temp.length < len) { this.V = this._hmac().update(this.V).digest(); temp = temp.concat(this.V); } var res = temp.slice(0, len); this._update(add); this._reseed++; return utils.encode(res, enc); }; /***/ }), /***/ 645: /***/ (function(__unused_webpack_module, exports) { /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = ((value * c) - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } /***/ }), /***/ 5717: /***/ (function(module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }) } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } } /***/ }), /***/ 2584: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var hasToStringTag = __webpack_require__(6410)(); var callBound = __webpack_require__(1924); var $toString = callBound('Object.prototype.toString'); var isStandardArguments = function isArguments(value) { if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { return false; } return $toString(value) === '[object Arguments]'; }; var isLegacyArguments = function isArguments(value) { if (isStandardArguments(value)) { return true; } return value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && $toString(value) !== '[object Array]' && $toString(value.callee) === '[object Function]'; }; var supportsStandardArguments = (function () { return isStandardArguments(arguments); }()); isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; /***/ }), /***/ 5320: /***/ (function(module) { "use strict"; var fnToStr = Function.prototype.toString; var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply; var badArrayLike; var isCallableMarker; if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') { try { badArrayLike = Object.defineProperty({}, 'length', { get: function () { throw isCallableMarker; } }); isCallableMarker = {}; // eslint-disable-next-line no-throw-literal reflectApply(function () { throw 42; }, null, badArrayLike); } catch (_) { if (_ !== isCallableMarker) { reflectApply = null; } } } else { reflectApply = null; } var constructorRegex = /^\s*class\b/; var isES6ClassFn = function isES6ClassFunction(value) { try { var fnStr = fnToStr.call(value); return constructorRegex.test(fnStr); } catch (e) { return false; // not a function } }; var tryFunctionObject = function tryFunctionToStr(value) { try { if (isES6ClassFn(value)) { return false; } fnToStr.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var fnClass = '[object Function]'; var genClass = '[object GeneratorFunction]'; var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag` /* globals document: false */ var documentDotAll = typeof document === 'object' && typeof document.all === 'undefined' && document.all !== undefined ? document.all : {}; module.exports = reflectApply ? function isCallable(value) { if (value === documentDotAll) { return true; } if (!value) { return false; } if (typeof value !== 'function' && typeof value !== 'object') { return false; } if (typeof value === 'function' && !value.prototype) { return true; } try { reflectApply(value, null, badArrayLike); } catch (e) { if (e !== isCallableMarker) { return false; } } return !isES6ClassFn(value); } : function isCallable(value) { if (value === documentDotAll) { return true; } if (!value) { return false; } if (typeof value !== 'function' && typeof value !== 'object') { return false; } if (typeof value === 'function' && !value.prototype) { return true; } if (hasToStringTag) { return tryFunctionObject(value); } if (isES6ClassFn(value)) { return false; } var strClass = toStr.call(value); return strClass === fnClass || strClass === genClass; }; /***/ }), /***/ 8662: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var toStr = Object.prototype.toString; var fnToStr = Function.prototype.toString; var isFnRegex = /^\s*(?:function)?\*/; var hasToStringTag = __webpack_require__(6410)(); var getProto = Object.getPrototypeOf; var getGeneratorFunc = function () { // eslint-disable-line consistent-return if (!hasToStringTag) { return false; } try { return Function('return function*() {}')(); } catch (e) { } }; var GeneratorFunction; module.exports = function isGeneratorFunction(fn) { if (typeof fn !== 'function') { return false; } if (isFnRegex.test(fnToStr.call(fn))) { return true; } if (!hasToStringTag) { var str = toStr.call(fn); return str === '[object GeneratorFunction]'; } if (!getProto) { return false; } if (typeof GeneratorFunction === 'undefined') { var generatorFunc = getGeneratorFunc(); GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; } return getProto(fn) === GeneratorFunction; }; /***/ }), /***/ 5692: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var forEach = __webpack_require__(4029); var availableTypedArrays = __webpack_require__(3083); var callBound = __webpack_require__(1924); var $toString = callBound('Object.prototype.toString'); var hasToStringTag = __webpack_require__(6410)(); var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; var typedArrays = availableTypedArrays(); var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { for (var i = 0; i < array.length; i += 1) { if (array[i] === value) { return i; } } return -1; }; var $slice = callBound('String.prototype.slice'); var toStrTags = {}; var gOPD = __webpack_require__(882); var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); if (hasToStringTag && gOPD && getPrototypeOf) { forEach(typedArrays, function (typedArray) { var arr = new g[typedArray](); if (Symbol.toStringTag in arr) { var proto = getPrototypeOf(arr); var descriptor = gOPD(proto, Symbol.toStringTag); if (!descriptor) { var superProto = getPrototypeOf(proto); descriptor = gOPD(superProto, Symbol.toStringTag); } toStrTags[typedArray] = descriptor.get; } }); } var tryTypedArrays = function tryAllTypedArrays(value) { var anyTrue = false; forEach(toStrTags, function (getter, typedArray) { if (!anyTrue) { try { anyTrue = getter.call(value) === typedArray; } catch (e) { /**/ } } }); return anyTrue; }; module.exports = function isTypedArray(value) { if (!value || typeof value !== 'object') { return false; } if (!hasToStringTag || !(Symbol.toStringTag in value)) { var tag = $slice($toString(value), 8, -1); return $indexOf(typedArrays, tag) > -1; } if (!gOPD) { return false; } return tryTypedArrays(value); }; /***/ }), /***/ 2023: /***/ (function(module, exports, __webpack_require__) { /* provided dependency */ var process = __webpack_require__(3454); var __WEBPACK_AMD_DEFINE_RESULT__;/** * [js-sha256]{@link https://github.com/emn178/js-sha256} * * @version 0.9.0 * @author Chen, Yi-Cyuan [emn178@gmail.com] * @copyright Chen, Yi-Cyuan 2014-2017 * @license MIT */ /*jslint bitwise: true */ (function () { 'use strict'; var ERROR = 'input is invalid type'; var WINDOW = typeof window === 'object'; var root = WINDOW ? window : {}; if (root.JS_SHA256_NO_WINDOW) { WINDOW = false; } var WEB_WORKER = !WINDOW && typeof self === 'object'; var NODE_JS = !root.JS_SHA256_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; if (NODE_JS) { root = __webpack_require__.g; } else if (WEB_WORKER) { root = self; } var COMMON_JS = !root.JS_SHA256_NO_COMMON_JS && "object" === 'object' && module.exports; var AMD = true && __webpack_require__.amdO; var ARRAY_BUFFER = !root.JS_SHA256_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined'; var HEX_CHARS = '0123456789abcdef'.split(''); var EXTRA = [-2147483648, 8388608, 32768, 128]; var SHIFT = [24, 16, 8, 0]; var K = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; var OUTPUT_TYPES = ['hex', 'array', 'digest', 'arrayBuffer']; var blocks = []; if (root.JS_SHA256_NO_NODE_JS || !Array.isArray) { Array.isArray = function (obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; } if (ARRAY_BUFFER && (root.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { ArrayBuffer.isView = function (obj) { return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer; }; } var createOutputMethod = function (outputType, is224) { return function (message) { return new Sha256(is224, true).update(message)[outputType](); }; }; var createMethod = function (is224) { var method = createOutputMethod('hex', is224); if (NODE_JS) { method = nodeWrap(method, is224); } method.create = function () { return new Sha256(is224); }; method.update = function (message) { return method.create().update(message); }; for (var i = 0; i < OUTPUT_TYPES.length; ++i) { var type = OUTPUT_TYPES[i]; method[type] = createOutputMethod(type, is224); } return method; }; var nodeWrap = function (method, is224) { var crypto = eval("require('crypto')"); var Buffer = eval("require('buffer').Buffer"); var algorithm = is224 ? 'sha224' : 'sha256'; var nodeMethod = function (message) { if (typeof message === 'string') { return crypto.createHash(algorithm).update(message, 'utf8').digest('hex'); } else { if (message === null || message === undefined) { throw new Error(ERROR); } else if (message.constructor === ArrayBuffer) { message = new Uint8Array(message); } } if (Array.isArray(message) || ArrayBuffer.isView(message) || message.constructor === Buffer) { return crypto.createHash(algorithm).update(new Buffer(message)).digest('hex'); } else { return method(message); } }; return nodeMethod; }; var createHmacOutputMethod = function (outputType, is224) { return function (key, message) { return new HmacSha256(key, is224, true).update(message)[outputType](); }; }; var createHmacMethod = function (is224) { var method = createHmacOutputMethod('hex', is224); method.create = function (key) { return new HmacSha256(key, is224); }; method.update = function (key, message) { return method.create(key).update(message); }; for (var i = 0; i < OUTPUT_TYPES.length; ++i) { var type = OUTPUT_TYPES[i]; method[type] = createHmacOutputMethod(type, is224); } return method; }; function Sha256(is224, sharedMemory) { if (sharedMemory) { blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; this.blocks = blocks; } else { this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; } if (is224) { this.h0 = 0xc1059ed8; this.h1 = 0x367cd507; this.h2 = 0x3070dd17; this.h3 = 0xf70e5939; this.h4 = 0xffc00b31; this.h5 = 0x68581511; this.h6 = 0x64f98fa7; this.h7 = 0xbefa4fa4; } else { // 256 this.h0 = 0x6a09e667; this.h1 = 0xbb67ae85; this.h2 = 0x3c6ef372; this.h3 = 0xa54ff53a; this.h4 = 0x510e527f; this.h5 = 0x9b05688c; this.h6 = 0x1f83d9ab; this.h7 = 0x5be0cd19; } this.block = this.start = this.bytes = this.hBytes = 0; this.finalized = this.hashed = false; this.first = true; this.is224 = is224; } Sha256.prototype.update = function (message) { if (this.finalized) { return; } var notString, type = typeof message; if (type !== 'string') { if (type === 'object') { if (message === null) { throw new Error(ERROR); } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { message = new Uint8Array(message); } else if (!Array.isArray(message)) { if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { throw new Error(ERROR); } } } else { throw new Error(ERROR); } notString = true; } var code, index = 0, i, length = message.length, blocks = this.blocks; while (index < length) { if (this.hashed) { this.hashed = false; blocks[0] = this.block; blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; } if (notString) { for (i = this.start; index < length && i < 64; ++index) { blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; } } else { for (i = this.start; index < length && i < 64; ++index) { code = message.charCodeAt(index); if (code < 0x80) { blocks[i >> 2] |= code << SHIFT[i++ & 3]; } else if (code < 0x800) { blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else if (code < 0xd800 || code >= 0xe000) { blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else { code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } } } this.lastByteIndex = i; this.bytes += i - this.start; if (i >= 64) { this.block = blocks[16]; this.start = i - 64; this.hash(); this.hashed = true; } else { this.start = i; } } if (this.bytes > 4294967295) { this.hBytes += this.bytes / 4294967296 << 0; this.bytes = this.bytes % 4294967296; } return this; }; Sha256.prototype.finalize = function () { if (this.finalized) { return; } this.finalized = true; var blocks = this.blocks, i = this.lastByteIndex; blocks[16] = this.block; blocks[i >> 2] |= EXTRA[i & 3]; this.block = blocks[16]; if (i >= 56) { if (!this.hashed) { this.hash(); } blocks[0] = this.block; blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; } blocks[14] = this.hBytes << 3 | this.bytes >>> 29; blocks[15] = this.bytes << 3; this.hash(); }; Sha256.prototype.hash = function () { var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, h = this.h7, blocks = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; for (j = 16; j < 64; ++j) { // rightrotate t1 = blocks[j - 15]; s0 = ((t1 >>> 7) | (t1 << 25)) ^ ((t1 >>> 18) | (t1 << 14)) ^ (t1 >>> 3); t1 = blocks[j - 2]; s1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10); blocks[j] = blocks[j - 16] + s0 + blocks[j - 7] + s1 << 0; } bc = b & c; for (j = 0; j < 64; j += 4) { if (this.first) { if (this.is224) { ab = 300032; t1 = blocks[0] - 1413257819; h = t1 - 150054599 << 0; d = t1 + 24177077 << 0; } else { ab = 704751109; t1 = blocks[0] - 210244248; h = t1 - 1521486534 << 0; d = t1 + 143694565 << 0; } this.first = false; } else { s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); ab = a & b; maj = ab ^ (a & c) ^ bc; ch = (e & f) ^ (~e & g); t1 = h + s1 + ch + K[j] + blocks[j]; t2 = s0 + maj; h = d + t1 << 0; d = t1 + t2 << 0; } s0 = ((d >>> 2) | (d << 30)) ^ ((d >>> 13) | (d << 19)) ^ ((d >>> 22) | (d << 10)); s1 = ((h >>> 6) | (h << 26)) ^ ((h >>> 11) | (h << 21)) ^ ((h >>> 25) | (h << 7)); da = d & a; maj = da ^ (d & b) ^ ab; ch = (h & e) ^ (~h & f); t1 = g + s1 + ch + K[j + 1] + blocks[j + 1]; t2 = s0 + maj; g = c + t1 << 0; c = t1 + t2 << 0; s0 = ((c >>> 2) | (c << 30)) ^ ((c >>> 13) | (c << 19)) ^ ((c >>> 22) | (c << 10)); s1 = ((g >>> 6) | (g << 26)) ^ ((g >>> 11) | (g << 21)) ^ ((g >>> 25) | (g << 7)); cd = c & d; maj = cd ^ (c & a) ^ da; ch = (g & h) ^ (~g & e); t1 = f + s1 + ch + K[j + 2] + blocks[j + 2]; t2 = s0 + maj; f = b + t1 << 0; b = t1 + t2 << 0; s0 = ((b >>> 2) | (b << 30)) ^ ((b >>> 13) | (b << 19)) ^ ((b >>> 22) | (b << 10)); s1 = ((f >>> 6) | (f << 26)) ^ ((f >>> 11) | (f << 21)) ^ ((f >>> 25) | (f << 7)); bc = b & c; maj = bc ^ (b & d) ^ cd; ch = (f & g) ^ (~f & h); t1 = e + s1 + ch + K[j + 3] + blocks[j + 3]; t2 = s0 + maj; e = a + t1 << 0; a = t1 + t2 << 0; } this.h0 = this.h0 + a << 0; this.h1 = this.h1 + b << 0; this.h2 = this.h2 + c << 0; this.h3 = this.h3 + d << 0; this.h4 = this.h4 + e << 0; this.h5 = this.h5 + f << 0; this.h6 = this.h6 + g << 0; this.h7 = this.h7 + h << 0; }; Sha256.prototype.hex = function () { this.finalize(); var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; var hex = HEX_CHARS[(h0 >> 28) & 0x0F] + HEX_CHARS[(h0 >> 24) & 0x0F] + HEX_CHARS[(h0 >> 20) & 0x0F] + HEX_CHARS[(h0 >> 16) & 0x0F] + HEX_CHARS[(h0 >> 12) & 0x0F] + HEX_CHARS[(h0 >> 8) & 0x0F] + HEX_CHARS[(h0 >> 4) & 0x0F] + HEX_CHARS[h0 & 0x0F] + HEX_CHARS[(h1 >> 28) & 0x0F] + HEX_CHARS[(h1 >> 24) & 0x0F] + HEX_CHARS[(h1 >> 20) & 0x0F] + HEX_CHARS[(h1 >> 16) & 0x0F] + HEX_CHARS[(h1 >> 12) & 0x0F] + HEX_CHARS[(h1 >> 8) & 0x0F] + HEX_CHARS[(h1 >> 4) & 0x0F] + HEX_CHARS[h1 & 0x0F] + HEX_CHARS[(h2 >> 28) & 0x0F] + HEX_CHARS[(h2 >> 24) & 0x0F] + HEX_CHARS[(h2 >> 20) & 0x0F] + HEX_CHARS[(h2 >> 16) & 0x0F] + HEX_CHARS[(h2 >> 12) & 0x0F] + HEX_CHARS[(h2 >> 8) & 0x0F] + HEX_CHARS[(h2 >> 4) & 0x0F] + HEX_CHARS[h2 & 0x0F] + HEX_CHARS[(h3 >> 28) & 0x0F] + HEX_CHARS[(h3 >> 24) & 0x0F] + HEX_CHARS[(h3 >> 20) & 0x0F] + HEX_CHARS[(h3 >> 16) & 0x0F] + HEX_CHARS[(h3 >> 12) & 0x0F] + HEX_CHARS[(h3 >> 8) & 0x0F] + HEX_CHARS[(h3 >> 4) & 0x0F] + HEX_CHARS[h3 & 0x0F] + HEX_CHARS[(h4 >> 28) & 0x0F] + HEX_CHARS[(h4 >> 24) & 0x0F] + HEX_CHARS[(h4 >> 20) & 0x0F] + HEX_CHARS[(h4 >> 16) & 0x0F] + HEX_CHARS[(h4 >> 12) & 0x0F] + HEX_CHARS[(h4 >> 8) & 0x0F] + HEX_CHARS[(h4 >> 4) & 0x0F] + HEX_CHARS[h4 & 0x0F] + HEX_CHARS[(h5 >> 28) & 0x0F] + HEX_CHARS[(h5 >> 24) & 0x0F] + HEX_CHARS[(h5 >> 20) & 0x0F] + HEX_CHARS[(h5 >> 16) & 0x0F] + HEX_CHARS[(h5 >> 12) & 0x0F] + HEX_CHARS[(h5 >> 8) & 0x0F] + HEX_CHARS[(h5 >> 4) & 0x0F] + HEX_CHARS[h5 & 0x0F] + HEX_CHARS[(h6 >> 28) & 0x0F] + HEX_CHARS[(h6 >> 24) & 0x0F] + HEX_CHARS[(h6 >> 20) & 0x0F] + HEX_CHARS[(h6 >> 16) & 0x0F] + HEX_CHARS[(h6 >> 12) & 0x0F] + HEX_CHARS[(h6 >> 8) & 0x0F] + HEX_CHARS[(h6 >> 4) & 0x0F] + HEX_CHARS[h6 & 0x0F]; if (!this.is224) { hex += HEX_CHARS[(h7 >> 28) & 0x0F] + HEX_CHARS[(h7 >> 24) & 0x0F] + HEX_CHARS[(h7 >> 20) & 0x0F] + HEX_CHARS[(h7 >> 16) & 0x0F] + HEX_CHARS[(h7 >> 12) & 0x0F] + HEX_CHARS[(h7 >> 8) & 0x0F] + HEX_CHARS[(h7 >> 4) & 0x0F] + HEX_CHARS[h7 & 0x0F]; } return hex; }; Sha256.prototype.toString = Sha256.prototype.hex; Sha256.prototype.digest = function () { this.finalize(); var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; var arr = [ (h0 >> 24) & 0xFF, (h0 >> 16) & 0xFF, (h0 >> 8) & 0xFF, h0 & 0xFF, (h1 >> 24) & 0xFF, (h1 >> 16) & 0xFF, (h1 >> 8) & 0xFF, h1 & 0xFF, (h2 >> 24) & 0xFF, (h2 >> 16) & 0xFF, (h2 >> 8) & 0xFF, h2 & 0xFF, (h3 >> 24) & 0xFF, (h3 >> 16) & 0xFF, (h3 >> 8) & 0xFF, h3 & 0xFF, (h4 >> 24) & 0xFF, (h4 >> 16) & 0xFF, (h4 >> 8) & 0xFF, h4 & 0xFF, (h5 >> 24) & 0xFF, (h5 >> 16) & 0xFF, (h5 >> 8) & 0xFF, h5 & 0xFF, (h6 >> 24) & 0xFF, (h6 >> 16) & 0xFF, (h6 >> 8) & 0xFF, h6 & 0xFF ]; if (!this.is224) { arr.push((h7 >> 24) & 0xFF, (h7 >> 16) & 0xFF, (h7 >> 8) & 0xFF, h7 & 0xFF); } return arr; }; Sha256.prototype.array = Sha256.prototype.digest; Sha256.prototype.arrayBuffer = function () { this.finalize(); var buffer = new ArrayBuffer(this.is224 ? 28 : 32); var dataView = new DataView(buffer); dataView.setUint32(0, this.h0); dataView.setUint32(4, this.h1); dataView.setUint32(8, this.h2); dataView.setUint32(12, this.h3); dataView.setUint32(16, this.h4); dataView.setUint32(20, this.h5); dataView.setUint32(24, this.h6); if (!this.is224) { dataView.setUint32(28, this.h7); } return buffer; }; function HmacSha256(key, is224, sharedMemory) { var i, type = typeof key; if (type === 'string') { var bytes = [], length = key.length, index = 0, code; for (i = 0; i < length; ++i) { code = key.charCodeAt(i); if (code < 0x80) { bytes[index++] = code; } else if (code < 0x800) { bytes[index++] = (0xc0 | (code >> 6)); bytes[index++] = (0x80 | (code & 0x3f)); } else if (code < 0xd800 || code >= 0xe000) { bytes[index++] = (0xe0 | (code >> 12)); bytes[index++] = (0x80 | ((code >> 6) & 0x3f)); bytes[index++] = (0x80 | (code & 0x3f)); } else { code = 0x10000 + (((code & 0x3ff) << 10) | (key.charCodeAt(++i) & 0x3ff)); bytes[index++] = (0xf0 | (code >> 18)); bytes[index++] = (0x80 | ((code >> 12) & 0x3f)); bytes[index++] = (0x80 | ((code >> 6) & 0x3f)); bytes[index++] = (0x80 | (code & 0x3f)); } } key = bytes; } else { if (type === 'object') { if (key === null) { throw new Error(ERROR); } else if (ARRAY_BUFFER && key.constructor === ArrayBuffer) { key = new Uint8Array(key); } else if (!Array.isArray(key)) { if (!ARRAY_BUFFER || !ArrayBuffer.isView(key)) { throw new Error(ERROR); } } } else { throw new Error(ERROR); } } if (key.length > 64) { key = (new Sha256(is224, true)).update(key).array(); } var oKeyPad = [], iKeyPad = []; for (i = 0; i < 64; ++i) { var b = key[i] || 0; oKeyPad[i] = 0x5c ^ b; iKeyPad[i] = 0x36 ^ b; } Sha256.call(this, is224, sharedMemory); this.update(iKeyPad); this.oKeyPad = oKeyPad; this.inner = true; this.sharedMemory = sharedMemory; } HmacSha256.prototype = new Sha256(); HmacSha256.prototype.finalize = function () { Sha256.prototype.finalize.call(this); if (this.inner) { this.inner = false; var innerHash = this.array(); Sha256.call(this, this.is224, this.sharedMemory); this.update(this.oKeyPad); this.update(innerHash); Sha256.prototype.finalize.call(this); } }; var exports = createMethod(); exports.sha256 = exports; exports.sha224 = createMethod(true); exports.sha256.hmac = createHmacMethod(); exports.sha224.hmac = createHmacMethod(true); if (COMMON_JS) { module.exports = exports; } else { root.sha256 = exports.sha256; root.sha224 = exports.sha224; if (AMD) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return exports; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } } })(); /***/ }), /***/ 3434: /***/ (function(module, exports, __webpack_require__) { /* provided dependency */ var process = __webpack_require__(3454); var __WEBPACK_AMD_DEFINE_RESULT__;/* * [js-sha512]{@link https://github.com/emn178/js-sha512} * * @version 0.8.0 * @author Chen, Yi-Cyuan [emn178@gmail.com] * @copyright Chen, Yi-Cyuan 2014-2018 * @license MIT */ /*jslint bitwise: true */ (function () { 'use strict'; var INPUT_ERROR = 'input is invalid type'; var FINALIZE_ERROR = 'finalize already called'; var WINDOW = typeof window === 'object'; var root = WINDOW ? window : {}; if (root.JS_SHA512_NO_WINDOW) { WINDOW = false; } var WEB_WORKER = !WINDOW && typeof self === 'object'; var NODE_JS = !root.JS_SHA512_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; if (NODE_JS) { root = __webpack_require__.g; } else if (WEB_WORKER) { root = self; } var COMMON_JS = !root.JS_SHA512_NO_COMMON_JS && "object" === 'object' && module.exports; var AMD = true && __webpack_require__.amdO; var ARRAY_BUFFER = !root.JS_SHA512_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined'; var HEX_CHARS = '0123456789abcdef'.split(''); var EXTRA = [-2147483648, 8388608, 32768, 128]; var SHIFT = [24, 16, 8, 0]; var K = [ 0x428A2F98, 0xD728AE22, 0x71374491, 0x23EF65CD, 0xB5C0FBCF, 0xEC4D3B2F, 0xE9B5DBA5, 0x8189DBBC, 0x3956C25B, 0xF348B538, 0x59F111F1, 0xB605D019, 0x923F82A4, 0xAF194F9B, 0xAB1C5ED5, 0xDA6D8118, 0xD807AA98, 0xA3030242, 0x12835B01, 0x45706FBE, 0x243185BE, 0x4EE4B28C, 0x550C7DC3, 0xD5FFB4E2, 0x72BE5D74, 0xF27B896F, 0x80DEB1FE, 0x3B1696B1, 0x9BDC06A7, 0x25C71235, 0xC19BF174, 0xCF692694, 0xE49B69C1, 0x9EF14AD2, 0xEFBE4786, 0x384F25E3, 0x0FC19DC6, 0x8B8CD5B5, 0x240CA1CC, 0x77AC9C65, 0x2DE92C6F, 0x592B0275, 0x4A7484AA, 0x6EA6E483, 0x5CB0A9DC, 0xBD41FBD4, 0x76F988DA, 0x831153B5, 0x983E5152, 0xEE66DFAB, 0xA831C66D, 0x2DB43210, 0xB00327C8, 0x98FB213F, 0xBF597FC7, 0xBEEF0EE4, 0xC6E00BF3, 0x3DA88FC2, 0xD5A79147, 0x930AA725, 0x06CA6351, 0xE003826F, 0x14292967, 0x0A0E6E70, 0x27B70A85, 0x46D22FFC, 0x2E1B2138, 0x5C26C926, 0x4D2C6DFC, 0x5AC42AED, 0x53380D13, 0x9D95B3DF, 0x650A7354, 0x8BAF63DE, 0x766A0ABB, 0x3C77B2A8, 0x81C2C92E, 0x47EDAEE6, 0x92722C85, 0x1482353B, 0xA2BFE8A1, 0x4CF10364, 0xA81A664B, 0xBC423001, 0xC24B8B70, 0xD0F89791, 0xC76C51A3, 0x0654BE30, 0xD192E819, 0xD6EF5218, 0xD6990624, 0x5565A910, 0xF40E3585, 0x5771202A, 0x106AA070, 0x32BBD1B8, 0x19A4C116, 0xB8D2D0C8, 0x1E376C08, 0x5141AB53, 0x2748774C, 0xDF8EEB99, 0x34B0BCB5, 0xE19B48A8, 0x391C0CB3, 0xC5C95A63, 0x4ED8AA4A, 0xE3418ACB, 0x5B9CCA4F, 0x7763E373, 0x682E6FF3, 0xD6B2B8A3, 0x748F82EE, 0x5DEFB2FC, 0x78A5636F, 0x43172F60, 0x84C87814, 0xA1F0AB72, 0x8CC70208, 0x1A6439EC, 0x90BEFFFA, 0x23631E28, 0xA4506CEB, 0xDE82BDE9, 0xBEF9A3F7, 0xB2C67915, 0xC67178F2, 0xE372532B, 0xCA273ECE, 0xEA26619C, 0xD186B8C7, 0x21C0C207, 0xEADA7DD6, 0xCDE0EB1E, 0xF57D4F7F, 0xEE6ED178, 0x06F067AA, 0x72176FBA, 0x0A637DC5, 0xA2C898A6, 0x113F9804, 0xBEF90DAE, 0x1B710B35, 0x131C471B, 0x28DB77F5, 0x23047D84, 0x32CAAB7B, 0x40C72493, 0x3C9EBE0A, 0x15C9BEBC, 0x431D67C4, 0x9C100D4C, 0x4CC5D4BE, 0xCB3E42B6, 0x597F299C, 0xFC657E2A, 0x5FCB6FAB, 0x3AD6FAEC, 0x6C44198C, 0x4A475817 ]; var OUTPUT_TYPES = ['hex', 'array', 'digest', 'arrayBuffer']; var blocks = []; if (root.JS_SHA512_NO_NODE_JS || !Array.isArray) { Array.isArray = function (obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; } if (ARRAY_BUFFER && (root.JS_SHA512_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { ArrayBuffer.isView = function (obj) { return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer; }; } var createOutputMethod = function (outputType, bits) { return function (message) { return new Sha512(bits, true).update(message)[outputType](); }; }; var createMethod = function (bits) { var method = createOutputMethod('hex', bits); method.create = function () { return new Sha512(bits); }; method.update = function (message) { return method.create().update(message); }; for (var i = 0; i < OUTPUT_TYPES.length; ++i) { var type = OUTPUT_TYPES[i]; method[type] = createOutputMethod(type, bits); } return method; }; var createHmacOutputMethod = function (outputType, bits) { return function (key, message) { return new HmacSha512(key, bits, true).update(message)[outputType](); }; }; var createHmacMethod = function (bits) { var method = createHmacOutputMethod('hex', bits); method.create = function (key) { return new HmacSha512(key, bits); }; method.update = function (key, message) { return method.create(key).update(message); }; for (var i = 0; i < OUTPUT_TYPES.length; ++i) { var type = OUTPUT_TYPES[i]; method[type] = createHmacOutputMethod(type, bits); } return method; }; function Sha512(bits, sharedMemory) { if (sharedMemory) { blocks[0] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = blocks[16] = blocks[17] = blocks[18] = blocks[19] = blocks[20] = blocks[21] = blocks[22] = blocks[23] = blocks[24] = blocks[25] = blocks[26] = blocks[27] = blocks[28] = blocks[29] = blocks[30] = blocks[31] = blocks[32] = 0; this.blocks = blocks; } else { this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; } if (bits == 384) { this.h0h = 0xCBBB9D5D; this.h0l = 0xC1059ED8; this.h1h = 0x629A292A; this.h1l = 0x367CD507; this.h2h = 0x9159015A; this.h2l = 0x3070DD17; this.h3h = 0x152FECD8; this.h3l = 0xF70E5939; this.h4h = 0x67332667; this.h4l = 0xFFC00B31; this.h5h = 0x8EB44A87; this.h5l = 0x68581511; this.h6h = 0xDB0C2E0D; this.h6l = 0x64F98FA7; this.h7h = 0x47B5481D; this.h7l = 0xBEFA4FA4; } else if (bits == 256) { this.h0h = 0x22312194; this.h0l = 0xFC2BF72C; this.h1h = 0x9F555FA3; this.h1l = 0xC84C64C2; this.h2h = 0x2393B86B; this.h2l = 0x6F53B151; this.h3h = 0x96387719; this.h3l = 0x5940EABD; this.h4h = 0x96283EE2; this.h4l = 0xA88EFFE3; this.h5h = 0xBE5E1E25; this.h5l = 0x53863992; this.h6h = 0x2B0199FC; this.h6l = 0x2C85B8AA; this.h7h = 0x0EB72DDC; this.h7l = 0x81C52CA2; } else if (bits == 224) { this.h0h = 0x8C3D37C8; this.h0l = 0x19544DA2; this.h1h = 0x73E19966; this.h1l = 0x89DCD4D6; this.h2h = 0x1DFAB7AE; this.h2l = 0x32FF9C82; this.h3h = 0x679DD514; this.h3l = 0x582F9FCF; this.h4h = 0x0F6D2B69; this.h4l = 0x7BD44DA8; this.h5h = 0x77E36F73; this.h5l = 0x04C48942; this.h6h = 0x3F9D85A8; this.h6l = 0x6A1D36C8; this.h7h = 0x1112E6AD; this.h7l = 0x91D692A1; } else { // 512 this.h0h = 0x6A09E667; this.h0l = 0xF3BCC908; this.h1h = 0xBB67AE85; this.h1l = 0x84CAA73B; this.h2h = 0x3C6EF372; this.h2l = 0xFE94F82B; this.h3h = 0xA54FF53A; this.h3l = 0x5F1D36F1; this.h4h = 0x510E527F; this.h4l = 0xADE682D1; this.h5h = 0x9B05688C; this.h5l = 0x2B3E6C1F; this.h6h = 0x1F83D9AB; this.h6l = 0xFB41BD6B; this.h7h = 0x5BE0CD19; this.h7l = 0x137E2179; } this.bits = bits; this.block = this.start = this.bytes = this.hBytes = 0; this.finalized = this.hashed = false; } Sha512.prototype.update = function (message) { if (this.finalized) { throw new Error(FINALIZE_ERROR); } var notString, type = typeof message; if (type !== 'string') { if (type === 'object') { if (message === null) { throw new Error(INPUT_ERROR); } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { message = new Uint8Array(message); } else if (!Array.isArray(message)) { if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { throw new Error(INPUT_ERROR); } } } else { throw new Error(INPUT_ERROR); } notString = true; } var code, index = 0, i, length = message.length, blocks = this.blocks; while (index < length) { if (this.hashed) { this.hashed = false; blocks[0] = this.block; blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = blocks[16] = blocks[17] = blocks[18] = blocks[19] = blocks[20] = blocks[21] = blocks[22] = blocks[23] = blocks[24] = blocks[25] = blocks[26] = blocks[27] = blocks[28] = blocks[29] = blocks[30] = blocks[31] = blocks[32] = 0; } if(notString) { for (i = this.start; index < length && i < 128; ++index) { blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; } } else { for (i = this.start; index < length && i < 128; ++index) { code = message.charCodeAt(index); if (code < 0x80) { blocks[i >> 2] |= code << SHIFT[i++ & 3]; } else if (code < 0x800) { blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else if (code < 0xd800 || code >= 0xe000) { blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else { code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } } } this.lastByteIndex = i; this.bytes += i - this.start; if (i >= 128) { this.block = blocks[32]; this.start = i - 128; this.hash(); this.hashed = true; } else { this.start = i; } } if (this.bytes > 4294967295) { this.hBytes += this.bytes / 4294967296 << 0; this.bytes = this.bytes % 4294967296; } return this; }; Sha512.prototype.finalize = function () { if (this.finalized) { return; } this.finalized = true; var blocks = this.blocks, i = this.lastByteIndex; blocks[32] = this.block; blocks[i >> 2] |= EXTRA[i & 3]; this.block = blocks[32]; if (i >= 112) { if (!this.hashed) { this.hash(); } blocks[0] = this.block; blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = blocks[16] = blocks[17] = blocks[18] = blocks[19] = blocks[20] = blocks[21] = blocks[22] = blocks[23] = blocks[24] = blocks[25] = blocks[26] = blocks[27] = blocks[28] = blocks[29] = blocks[30] = blocks[31] = blocks[32] = 0; } blocks[30] = this.hBytes << 3 | this.bytes >>> 29; blocks[31] = this.bytes << 3; this.hash(); }; Sha512.prototype.hash = function () { var h0h = this.h0h, h0l = this.h0l, h1h = this.h1h, h1l = this.h1l, h2h = this.h2h, h2l = this.h2l, h3h = this.h3h, h3l = this.h3l, h4h = this.h4h, h4l = this.h4l, h5h = this.h5h, h5l = this.h5l, h6h = this.h6h, h6l = this.h6l, h7h = this.h7h, h7l = this.h7l, blocks = this.blocks, j, s0h, s0l, s1h, s1l, c1, c2, c3, c4, abh, abl, dah, dal, cdh, cdl, bch, bcl, majh, majl, t1h, t1l, t2h, t2l, chh, chl; for (j = 32; j < 160; j += 2) { t1h = blocks[j - 30]; t1l = blocks[j - 29]; s0h = ((t1h >>> 1) | (t1l << 31)) ^ ((t1h >>> 8) | (t1l << 24)) ^ (t1h >>> 7); s0l = ((t1l >>> 1) | (t1h << 31)) ^ ((t1l >>> 8) | (t1h << 24)) ^ ((t1l >>> 7) | t1h << 25); t1h = blocks[j - 4]; t1l = blocks[j - 3]; s1h = ((t1h >>> 19) | (t1l << 13)) ^ ((t1l >>> 29) | (t1h << 3)) ^ (t1h >>> 6); s1l = ((t1l >>> 19) | (t1h << 13)) ^ ((t1h >>> 29) | (t1l << 3)) ^ ((t1l >>> 6) | t1h << 26); t1h = blocks[j - 32]; t1l = blocks[j - 31]; t2h = blocks[j - 14]; t2l = blocks[j - 13]; c1 = (t2l & 0xFFFF) + (t1l & 0xFFFF) + (s0l & 0xFFFF) + (s1l & 0xFFFF); c2 = (t2l >>> 16) + (t1l >>> 16) + (s0l >>> 16) + (s1l >>> 16) + (c1 >>> 16); c3 = (t2h & 0xFFFF) + (t1h & 0xFFFF) + (s0h & 0xFFFF) + (s1h & 0xFFFF) + (c2 >>> 16); c4 = (t2h >>> 16) + (t1h >>> 16) + (s0h >>> 16) + (s1h >>> 16) + (c3 >>> 16); blocks[j] = (c4 << 16) | (c3 & 0xFFFF); blocks[j + 1] = (c2 << 16) | (c1 & 0xFFFF); } var ah = h0h, al = h0l, bh = h1h, bl = h1l, ch = h2h, cl = h2l, dh = h3h, dl = h3l, eh = h4h, el = h4l, fh = h5h, fl = h5l, gh = h6h, gl = h6l, hh = h7h, hl = h7l; bch = bh & ch; bcl = bl & cl; for (j = 0; j < 160; j += 8) { s0h = ((ah >>> 28) | (al << 4)) ^ ((al >>> 2) | (ah << 30)) ^ ((al >>> 7) | (ah << 25)); s0l = ((al >>> 28) | (ah << 4)) ^ ((ah >>> 2) | (al << 30)) ^ ((ah >>> 7) | (al << 25)); s1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((el >>> 9) | (eh << 23)); s1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((eh >>> 9) | (el << 23)); abh = ah & bh; abl = al & bl; majh = abh ^ (ah & ch) ^ bch; majl = abl ^ (al & cl) ^ bcl; chh = (eh & fh) ^ (~eh & gh); chl = (el & fl) ^ (~el & gl); t1h = blocks[j]; t1l = blocks[j + 1]; t2h = K[j]; t2l = K[j + 1]; c1 = (t2l & 0xFFFF) + (t1l & 0xFFFF) + (chl & 0xFFFF) + (s1l & 0xFFFF) + (hl & 0xFFFF); c2 = (t2l >>> 16) + (t1l >>> 16) + (chl >>> 16) + (s1l >>> 16) + (hl >>> 16) + (c1 >>> 16); c3 = (t2h & 0xFFFF) + (t1h & 0xFFFF) + (chh & 0xFFFF) + (s1h & 0xFFFF) + (hh & 0xFFFF) + (c2 >>> 16); c4 = (t2h >>> 16) + (t1h >>> 16) + (chh >>> 16) + (s1h >>> 16) + (hh >>> 16) + (c3 >>> 16); t1h = (c4 << 16) | (c3 & 0xFFFF); t1l = (c2 << 16) | (c1 & 0xFFFF); c1 = (majl & 0xFFFF) + (s0l & 0xFFFF); c2 = (majl >>> 16) + (s0l >>> 16) + (c1 >>> 16); c3 = (majh & 0xFFFF) + (s0h & 0xFFFF) + (c2 >>> 16); c4 = (majh >>> 16) + (s0h >>> 16) + (c3 >>> 16); t2h = (c4 << 16) | (c3 & 0xFFFF); t2l = (c2 << 16) | (c1 & 0xFFFF); c1 = (dl & 0xFFFF) + (t1l & 0xFFFF); c2 = (dl >>> 16) + (t1l >>> 16) + (c1 >>> 16); c3 = (dh & 0xFFFF) + (t1h & 0xFFFF) + (c2 >>> 16); c4 = (dh >>> 16) + (t1h >>> 16) + (c3 >>> 16); hh = (c4 << 16) | (c3 & 0xFFFF); hl = (c2 << 16) | (c1 & 0xFFFF); c1 = (t2l & 0xFFFF) + (t1l & 0xFFFF); c2 = (t2l >>> 16) + (t1l >>> 16) + (c1 >>> 16); c3 = (t2h & 0xFFFF) + (t1h & 0xFFFF) + (c2 >>> 16); c4 = (t2h >>> 16) + (t1h >>> 16) + (c3 >>> 16); dh = (c4 << 16) | (c3 & 0xFFFF); dl = (c2 << 16) | (c1 & 0xFFFF); s0h = ((dh >>> 28) | (dl << 4)) ^ ((dl >>> 2) | (dh << 30)) ^ ((dl >>> 7) | (dh << 25)); s0l = ((dl >>> 28) | (dh << 4)) ^ ((dh >>> 2) | (dl << 30)) ^ ((dh >>> 7) | (dl << 25)); s1h = ((hh >>> 14) | (hl << 18)) ^ ((hh >>> 18) | (hl << 14)) ^ ((hl >>> 9) | (hh << 23)); s1l = ((hl >>> 14) | (hh << 18)) ^ ((hl >>> 18) | (hh << 14)) ^ ((hh >>> 9) | (hl << 23)); dah = dh & ah; dal = dl & al; majh = dah ^ (dh & bh) ^ abh; majl = dal ^ (dl & bl) ^ abl; chh = (hh & eh) ^ (~hh & fh); chl = (hl & el) ^ (~hl & fl); t1h = blocks[j + 2]; t1l = blocks[j + 3]; t2h = K[j + 2]; t2l = K[j + 3]; c1 = (t2l & 0xFFFF) + (t1l & 0xFFFF) + (chl & 0xFFFF) + (s1l & 0xFFFF) + (gl & 0xFFFF); c2 = (t2l >>> 16) + (t1l >>> 16) + (chl >>> 16) + (s1l >>> 16) + (gl >>> 16) + (c1 >>> 16); c3 = (t2h & 0xFFFF) + (t1h & 0xFFFF) + (chh & 0xFFFF) + (s1h & 0xFFFF) + (gh & 0xFFFF) + (c2 >>> 16); c4 = (t2h >>> 16) + (t1h >>> 16) + (chh >>> 16) + (s1h >>> 16) + (gh >>> 16) + (c3 >>> 16); t1h = (c4 << 16) | (c3 & 0xFFFF); t1l = (c2 << 16) | (c1 & 0xFFFF); c1 = (majl & 0xFFFF) + (s0l & 0xFFFF); c2 = (majl >>> 16) + (s0l >>> 16) + (c1 >>> 16); c3 = (majh & 0xFFFF) + (s0h & 0xFFFF) + (c2 >>> 16); c4 = (majh >>> 16) + (s0h >>> 16) + (c3 >>> 16); t2h = (c4 << 16) | (c3 & 0xFFFF); t2l = (c2 << 16) | (c1 & 0xFFFF); c1 = (cl & 0xFFFF) + (t1l & 0xFFFF); c2 = (cl >>> 16) + (t1l >>> 16) + (c1 >>> 16); c3 = (ch & 0xFFFF) + (t1h & 0xFFFF) + (c2 >>> 16); c4 = (ch >>> 16) + (t1h >>> 16) + (c3 >>> 16); gh = (c4 << 16) | (c3 & 0xFFFF); gl = (c2 << 16) | (c1 & 0xFFFF); c1 = (t2l & 0xFFFF) + (t1l & 0xFFFF); c2 = (t2l >>> 16) + (t1l >>> 16) + (c1 >>> 16); c3 = (t2h & 0xFFFF) + (t1h & 0xFFFF) + (c2 >>> 16); c4 = (t2h >>> 16) + (t1h >>> 16) + (c3 >>> 16); ch = (c4 << 16) | (c3 & 0xFFFF); cl = (c2 << 16) | (c1 & 0xFFFF); s0h = ((ch >>> 28) | (cl << 4)) ^ ((cl >>> 2) | (ch << 30)) ^ ((cl >>> 7) | (ch << 25)); s0l = ((cl >>> 28) | (ch << 4)) ^ ((ch >>> 2) | (cl << 30)) ^ ((ch >>> 7) | (cl << 25)); s1h = ((gh >>> 14) | (gl << 18)) ^ ((gh >>> 18) | (gl << 14)) ^ ((gl >>> 9) | (gh << 23)); s1l = ((gl >>> 14) | (gh << 18)) ^ ((gl >>> 18) | (gh << 14)) ^ ((gh >>> 9) | (gl << 23)); cdh = ch & dh; cdl = cl & dl; majh = cdh ^ (ch & ah) ^ dah; majl = cdl ^ (cl & al) ^ dal; chh = (gh & hh) ^ (~gh & eh); chl = (gl & hl) ^ (~gl & el); t1h = blocks[j + 4]; t1l = blocks[j + 5]; t2h = K[j + 4]; t2l = K[j + 5]; c1 = (t2l & 0xFFFF) + (t1l & 0xFFFF) + (chl & 0xFFFF) + (s1l & 0xFFFF) + (fl & 0xFFFF); c2 = (t2l >>> 16) + (t1l >>> 16) + (chl >>> 16) + (s1l >>> 16) + (fl >>> 16) + (c1 >>> 16); c3 = (t2h & 0xFFFF) + (t1h & 0xFFFF) + (chh & 0xFFFF) + (s1h & 0xFFFF) + (fh & 0xFFFF) + (c2 >>> 16); c4 = (t2h >>> 16) + (t1h >>> 16) + (chh >>> 16) + (s1h >>> 16) + (fh >>> 16) + (c3 >>> 16); t1h = (c4 << 16) | (c3 & 0xFFFF); t1l = (c2 << 16) | (c1 & 0xFFFF); c1 = (majl & 0xFFFF) + (s0l & 0xFFFF); c2 = (majl >>> 16) + (s0l >>> 16) + (c1 >>> 16); c3 = (majh & 0xFFFF) + (s0h & 0xFFFF) + (c2 >>> 16); c4 = (majh >>> 16) + (s0h >>> 16) + (c3 >>> 16); t2h = (c4 << 16) | (c3 & 0xFFFF); t2l = (c2 << 16) | (c1 & 0xFFFF); c1 = (bl & 0xFFFF) + (t1l & 0xFFFF); c2 = (bl >>> 16) + (t1l >>> 16) + (c1 >>> 16); c3 = (bh & 0xFFFF) + (t1h & 0xFFFF) + (c2 >>> 16); c4 = (bh >>> 16) + (t1h >>> 16) + (c3 >>> 16); fh = (c4 << 16) | (c3 & 0xFFFF); fl = (c2 << 16) | (c1 & 0xFFFF); c1 = (t2l & 0xFFFF) + (t1l & 0xFFFF); c2 = (t2l >>> 16) + (t1l >>> 16) + (c1 >>> 16); c3 = (t2h & 0xFFFF) + (t1h & 0xFFFF) + (c2 >>> 16); c4 = (t2h >>> 16) + (t1h >>> 16) + (c3 >>> 16); bh = (c4 << 16) | (c3 & 0xFFFF); bl = (c2 << 16) | (c1 & 0xFFFF); s0h = ((bh >>> 28) | (bl << 4)) ^ ((bl >>> 2) | (bh << 30)) ^ ((bl >>> 7) | (bh << 25)); s0l = ((bl >>> 28) | (bh << 4)) ^ ((bh >>> 2) | (bl << 30)) ^ ((bh >>> 7) | (bl << 25)); s1h = ((fh >>> 14) | (fl << 18)) ^ ((fh >>> 18) | (fl << 14)) ^ ((fl >>> 9) | (fh << 23)); s1l = ((fl >>> 14) | (fh << 18)) ^ ((fl >>> 18) | (fh << 14)) ^ ((fh >>> 9) | (fl << 23)); bch = bh & ch; bcl = bl & cl; majh = bch ^ (bh & dh) ^ cdh; majl = bcl ^ (bl & dl) ^ cdl; chh = (fh & gh) ^ (~fh & hh); chl = (fl & gl) ^ (~fl & hl); t1h = blocks[j + 6]; t1l = blocks[j + 7]; t2h = K[j + 6]; t2l = K[j + 7]; c1 = (t2l & 0xFFFF) + (t1l & 0xFFFF) + (chl & 0xFFFF) + (s1l & 0xFFFF) + (el & 0xFFFF); c2 = (t2l >>> 16) + (t1l >>> 16) + (chl >>> 16) + (s1l >>> 16) + (el >>> 16) + (c1 >>> 16); c3 = (t2h & 0xFFFF) + (t1h & 0xFFFF) + (chh & 0xFFFF) + (s1h & 0xFFFF) + (eh & 0xFFFF) + (c2 >>> 16); c4 = (t2h >>> 16) + (t1h >>> 16) + (chh >>> 16) + (s1h >>> 16) + (eh >>> 16) + (c3 >>> 16); t1h = (c4 << 16) | (c3 & 0xFFFF); t1l = (c2 << 16) | (c1 & 0xFFFF); c1 = (majl & 0xFFFF) + (s0l & 0xFFFF); c2 = (majl >>> 16) + (s0l >>> 16) + (c1 >>> 16); c3 = (majh & 0xFFFF) + (s0h & 0xFFFF) + (c2 >>> 16); c4 = (majh >>> 16) + (s0h >>> 16) + (c3 >>> 16); t2h = (c4 << 16) | (c3 & 0xFFFF); t2l = (c2 << 16) | (c1 & 0xFFFF); c1 = (al & 0xFFFF) + (t1l & 0xFFFF); c2 = (al >>> 16) + (t1l >>> 16) + (c1 >>> 16); c3 = (ah & 0xFFFF) + (t1h & 0xFFFF) + (c2 >>> 16); c4 = (ah >>> 16) + (t1h >>> 16) + (c3 >>> 16); eh = (c4 << 16) | (c3 & 0xFFFF); el = (c2 << 16) | (c1 & 0xFFFF); c1 = (t2l & 0xFFFF) + (t1l & 0xFFFF); c2 = (t2l >>> 16) + (t1l >>> 16) + (c1 >>> 16); c3 = (t2h & 0xFFFF) + (t1h & 0xFFFF) + (c2 >>> 16); c4 = (t2h >>> 16) + (t1h >>> 16) + (c3 >>> 16); ah = (c4 << 16) | (c3 & 0xFFFF); al = (c2 << 16) | (c1 & 0xFFFF); } c1 = (h0l & 0xFFFF) + (al & 0xFFFF); c2 = (h0l >>> 16) + (al >>> 16) + (c1 >>> 16); c3 = (h0h & 0xFFFF) + (ah & 0xFFFF) + (c2 >>> 16); c4 = (h0h >>> 16) + (ah >>> 16) + (c3 >>> 16); this.h0h = (c4 << 16) | (c3 & 0xFFFF); this.h0l = (c2 << 16) | (c1 & 0xFFFF); c1 = (h1l & 0xFFFF) + (bl & 0xFFFF); c2 = (h1l >>> 16) + (bl >>> 16) + (c1 >>> 16); c3 = (h1h & 0xFFFF) + (bh & 0xFFFF) + (c2 >>> 16); c4 = (h1h >>> 16) + (bh >>> 16) + (c3 >>> 16); this.h1h = (c4 << 16) | (c3 & 0xFFFF); this.h1l = (c2 << 16) | (c1 & 0xFFFF); c1 = (h2l & 0xFFFF) + (cl & 0xFFFF); c2 = (h2l >>> 16) + (cl >>> 16) + (c1 >>> 16); c3 = (h2h & 0xFFFF) + (ch & 0xFFFF) + (c2 >>> 16); c4 = (h2h >>> 16) + (ch >>> 16) + (c3 >>> 16); this.h2h = (c4 << 16) | (c3 & 0xFFFF); this.h2l = (c2 << 16) | (c1 & 0xFFFF); c1 = (h3l & 0xFFFF) + (dl & 0xFFFF); c2 = (h3l >>> 16) + (dl >>> 16) + (c1 >>> 16); c3 = (h3h & 0xFFFF) + (dh & 0xFFFF) + (c2 >>> 16); c4 = (h3h >>> 16) + (dh >>> 16) + (c3 >>> 16); this.h3h = (c4 << 16) | (c3 & 0xFFFF); this.h3l = (c2 << 16) | (c1 & 0xFFFF); c1 = (h4l & 0xFFFF) + (el & 0xFFFF); c2 = (h4l >>> 16) + (el >>> 16) + (c1 >>> 16); c3 = (h4h & 0xFFFF) + (eh & 0xFFFF) + (c2 >>> 16); c4 = (h4h >>> 16) + (eh >>> 16) + (c3 >>> 16); this.h4h = (c4 << 16) | (c3 & 0xFFFF); this.h4l = (c2 << 16) | (c1 & 0xFFFF); c1 = (h5l & 0xFFFF) + (fl & 0xFFFF); c2 = (h5l >>> 16) + (fl >>> 16) + (c1 >>> 16); c3 = (h5h & 0xFFFF) + (fh & 0xFFFF) + (c2 >>> 16); c4 = (h5h >>> 16) + (fh >>> 16) + (c3 >>> 16); this.h5h = (c4 << 16) | (c3 & 0xFFFF); this.h5l = (c2 << 16) | (c1 & 0xFFFF); c1 = (h6l & 0xFFFF) + (gl & 0xFFFF); c2 = (h6l >>> 16) + (gl >>> 16) + (c1 >>> 16); c3 = (h6h & 0xFFFF) + (gh & 0xFFFF) + (c2 >>> 16); c4 = (h6h >>> 16) + (gh >>> 16) + (c3 >>> 16); this.h6h = (c4 << 16) | (c3 & 0xFFFF); this.h6l = (c2 << 16) | (c1 & 0xFFFF); c1 = (h7l & 0xFFFF) + (hl & 0xFFFF); c2 = (h7l >>> 16) + (hl >>> 16) + (c1 >>> 16); c3 = (h7h & 0xFFFF) + (hh & 0xFFFF) + (c2 >>> 16); c4 = (h7h >>> 16) + (hh >>> 16) + (c3 >>> 16); this.h7h = (c4 << 16) | (c3 & 0xFFFF); this.h7l = (c2 << 16) | (c1 & 0xFFFF); }; Sha512.prototype.hex = function () { this.finalize(); var h0h = this.h0h, h0l = this.h0l, h1h = this.h1h, h1l = this.h1l, h2h = this.h2h, h2l = this.h2l, h3h = this.h3h, h3l = this.h3l, h4h = this.h4h, h4l = this.h4l, h5h = this.h5h, h5l = this.h5l, h6h = this.h6h, h6l = this.h6l, h7h = this.h7h, h7l = this.h7l, bits = this.bits; var hex = HEX_CHARS[(h0h >> 28) & 0x0F] + HEX_CHARS[(h0h >> 24) & 0x0F] + HEX_CHARS[(h0h >> 20) & 0x0F] + HEX_CHARS[(h0h >> 16) & 0x0F] + HEX_CHARS[(h0h >> 12) & 0x0F] + HEX_CHARS[(h0h >> 8) & 0x0F] + HEX_CHARS[(h0h >> 4) & 0x0F] + HEX_CHARS[h0h & 0x0F] + HEX_CHARS[(h0l >> 28) & 0x0F] + HEX_CHARS[(h0l >> 24) & 0x0F] + HEX_CHARS[(h0l >> 20) & 0x0F] + HEX_CHARS[(h0l >> 16) & 0x0F] + HEX_CHARS[(h0l >> 12) & 0x0F] + HEX_CHARS[(h0l >> 8) & 0x0F] + HEX_CHARS[(h0l >> 4) & 0x0F] + HEX_CHARS[h0l & 0x0F] + HEX_CHARS[(h1h >> 28) & 0x0F] + HEX_CHARS[(h1h >> 24) & 0x0F] + HEX_CHARS[(h1h >> 20) & 0x0F] + HEX_CHARS[(h1h >> 16) & 0x0F] + HEX_CHARS[(h1h >> 12) & 0x0F] + HEX_CHARS[(h1h >> 8) & 0x0F] + HEX_CHARS[(h1h >> 4) & 0x0F] + HEX_CHARS[h1h & 0x0F] + HEX_CHARS[(h1l >> 28) & 0x0F] + HEX_CHARS[(h1l >> 24) & 0x0F] + HEX_CHARS[(h1l >> 20) & 0x0F] + HEX_CHARS[(h1l >> 16) & 0x0F] + HEX_CHARS[(h1l >> 12) & 0x0F] + HEX_CHARS[(h1l >> 8) & 0x0F] + HEX_CHARS[(h1l >> 4) & 0x0F] + HEX_CHARS[h1l & 0x0F] + HEX_CHARS[(h2h >> 28) & 0x0F] + HEX_CHARS[(h2h >> 24) & 0x0F] + HEX_CHARS[(h2h >> 20) & 0x0F] + HEX_CHARS[(h2h >> 16) & 0x0F] + HEX_CHARS[(h2h >> 12) & 0x0F] + HEX_CHARS[(h2h >> 8) & 0x0F] + HEX_CHARS[(h2h >> 4) & 0x0F] + HEX_CHARS[h2h & 0x0F] + HEX_CHARS[(h2l >> 28) & 0x0F] + HEX_CHARS[(h2l >> 24) & 0x0F] + HEX_CHARS[(h2l >> 20) & 0x0F] + HEX_CHARS[(h2l >> 16) & 0x0F] + HEX_CHARS[(h2l >> 12) & 0x0F] + HEX_CHARS[(h2l >> 8) & 0x0F] + HEX_CHARS[(h2l >> 4) & 0x0F] + HEX_CHARS[h2l & 0x0F] + HEX_CHARS[(h3h >> 28) & 0x0F] + HEX_CHARS[(h3h >> 24) & 0x0F] + HEX_CHARS[(h3h >> 20) & 0x0F] + HEX_CHARS[(h3h >> 16) & 0x0F] + HEX_CHARS[(h3h >> 12) & 0x0F] + HEX_CHARS[(h3h >> 8) & 0x0F] + HEX_CHARS[(h3h >> 4) & 0x0F] + HEX_CHARS[h3h & 0x0F]; if (bits >= 256) { hex += HEX_CHARS[(h3l >> 28) & 0x0F] + HEX_CHARS[(h3l >> 24) & 0x0F] + HEX_CHARS[(h3l >> 20) & 0x0F] + HEX_CHARS[(h3l >> 16) & 0x0F] + HEX_CHARS[(h3l >> 12) & 0x0F] + HEX_CHARS[(h3l >> 8) & 0x0F] + HEX_CHARS[(h3l >> 4) & 0x0F] + HEX_CHARS[h3l & 0x0F]; } if (bits >= 384) { hex += HEX_CHARS[(h4h >> 28) & 0x0F] + HEX_CHARS[(h4h >> 24) & 0x0F] + HEX_CHARS[(h4h >> 20) & 0x0F] + HEX_CHARS[(h4h >> 16) & 0x0F] + HEX_CHARS[(h4h >> 12) & 0x0F] + HEX_CHARS[(h4h >> 8) & 0x0F] + HEX_CHARS[(h4h >> 4) & 0x0F] + HEX_CHARS[h4h & 0x0F] + HEX_CHARS[(h4l >> 28) & 0x0F] + HEX_CHARS[(h4l >> 24) & 0x0F] + HEX_CHARS[(h4l >> 20) & 0x0F] + HEX_CHARS[(h4l >> 16) & 0x0F] + HEX_CHARS[(h4l >> 12) & 0x0F] + HEX_CHARS[(h4l >> 8) & 0x0F] + HEX_CHARS[(h4l >> 4) & 0x0F] + HEX_CHARS[h4l & 0x0F] + HEX_CHARS[(h5h >> 28) & 0x0F] + HEX_CHARS[(h5h >> 24) & 0x0F] + HEX_CHARS[(h5h >> 20) & 0x0F] + HEX_CHARS[(h5h >> 16) & 0x0F] + HEX_CHARS[(h5h >> 12) & 0x0F] + HEX_CHARS[(h5h >> 8) & 0x0F] + HEX_CHARS[(h5h >> 4) & 0x0F] + HEX_CHARS[h5h & 0x0F] + HEX_CHARS[(h5l >> 28) & 0x0F] + HEX_CHARS[(h5l >> 24) & 0x0F] + HEX_CHARS[(h5l >> 20) & 0x0F] + HEX_CHARS[(h5l >> 16) & 0x0F] + HEX_CHARS[(h5l >> 12) & 0x0F] + HEX_CHARS[(h5l >> 8) & 0x0F] + HEX_CHARS[(h5l >> 4) & 0x0F] + HEX_CHARS[h5l & 0x0F]; } if (bits == 512) { hex += HEX_CHARS[(h6h >> 28) & 0x0F] + HEX_CHARS[(h6h >> 24) & 0x0F] + HEX_CHARS[(h6h >> 20) & 0x0F] + HEX_CHARS[(h6h >> 16) & 0x0F] + HEX_CHARS[(h6h >> 12) & 0x0F] + HEX_CHARS[(h6h >> 8) & 0x0F] + HEX_CHARS[(h6h >> 4) & 0x0F] + HEX_CHARS[h6h & 0x0F] + HEX_CHARS[(h6l >> 28) & 0x0F] + HEX_CHARS[(h6l >> 24) & 0x0F] + HEX_CHARS[(h6l >> 20) & 0x0F] + HEX_CHARS[(h6l >> 16) & 0x0F] + HEX_CHARS[(h6l >> 12) & 0x0F] + HEX_CHARS[(h6l >> 8) & 0x0F] + HEX_CHARS[(h6l >> 4) & 0x0F] + HEX_CHARS[h6l & 0x0F] + HEX_CHARS[(h7h >> 28) & 0x0F] + HEX_CHARS[(h7h >> 24) & 0x0F] + HEX_CHARS[(h7h >> 20) & 0x0F] + HEX_CHARS[(h7h >> 16) & 0x0F] + HEX_CHARS[(h7h >> 12) & 0x0F] + HEX_CHARS[(h7h >> 8) & 0x0F] + HEX_CHARS[(h7h >> 4) & 0x0F] + HEX_CHARS[h7h & 0x0F] + HEX_CHARS[(h7l >> 28) & 0x0F] + HEX_CHARS[(h7l >> 24) & 0x0F] + HEX_CHARS[(h7l >> 20) & 0x0F] + HEX_CHARS[(h7l >> 16) & 0x0F] + HEX_CHARS[(h7l >> 12) & 0x0F] + HEX_CHARS[(h7l >> 8) & 0x0F] + HEX_CHARS[(h7l >> 4) & 0x0F] + HEX_CHARS[h7l & 0x0F]; } return hex; }; Sha512.prototype.toString = Sha512.prototype.hex; Sha512.prototype.digest = function () { this.finalize(); var h0h = this.h0h, h0l = this.h0l, h1h = this.h1h, h1l = this.h1l, h2h = this.h2h, h2l = this.h2l, h3h = this.h3h, h3l = this.h3l, h4h = this.h4h, h4l = this.h4l, h5h = this.h5h, h5l = this.h5l, h6h = this.h6h, h6l = this.h6l, h7h = this.h7h, h7l = this.h7l, bits = this.bits; var arr = [ (h0h >> 24) & 0xFF, (h0h >> 16) & 0xFF, (h0h >> 8) & 0xFF, h0h & 0xFF, (h0l >> 24) & 0xFF, (h0l >> 16) & 0xFF, (h0l >> 8) & 0xFF, h0l & 0xFF, (h1h >> 24) & 0xFF, (h1h >> 16) & 0xFF, (h1h >> 8) & 0xFF, h1h & 0xFF, (h1l >> 24) & 0xFF, (h1l >> 16) & 0xFF, (h1l >> 8) & 0xFF, h1l & 0xFF, (h2h >> 24) & 0xFF, (h2h >> 16) & 0xFF, (h2h >> 8) & 0xFF, h2h & 0xFF, (h2l >> 24) & 0xFF, (h2l >> 16) & 0xFF, (h2l >> 8) & 0xFF, h2l & 0xFF, (h3h >> 24) & 0xFF, (h3h >> 16) & 0xFF, (h3h >> 8) & 0xFF, h3h & 0xFF ]; if (bits >= 256) { arr.push((h3l >> 24) & 0xFF, (h3l >> 16) & 0xFF, (h3l >> 8) & 0xFF, h3l & 0xFF); } if (bits >= 384) { arr.push( (h4h >> 24) & 0xFF, (h4h >> 16) & 0xFF, (h4h >> 8) & 0xFF, h4h & 0xFF, (h4l >> 24) & 0xFF, (h4l >> 16) & 0xFF, (h4l >> 8) & 0xFF, h4l & 0xFF, (h5h >> 24) & 0xFF, (h5h >> 16) & 0xFF, (h5h >> 8) & 0xFF, h5h & 0xFF, (h5l >> 24) & 0xFF, (h5l >> 16) & 0xFF, (h5l >> 8) & 0xFF, h5l & 0xFF ); } if (bits == 512) { arr.push( (h6h >> 24) & 0xFF, (h6h >> 16) & 0xFF, (h6h >> 8) & 0xFF, h6h & 0xFF, (h6l >> 24) & 0xFF, (h6l >> 16) & 0xFF, (h6l >> 8) & 0xFF, h6l & 0xFF, (h7h >> 24) & 0xFF, (h7h >> 16) & 0xFF, (h7h >> 8) & 0xFF, h7h & 0xFF, (h7l >> 24) & 0xFF, (h7l >> 16) & 0xFF, (h7l >> 8) & 0xFF, h7l & 0xFF ); } return arr; }; Sha512.prototype.array = Sha512.prototype.digest; Sha512.prototype.arrayBuffer = function () { this.finalize(); var bits = this.bits; var buffer = new ArrayBuffer(bits / 8); var dataView = new DataView(buffer); dataView.setUint32(0, this.h0h); dataView.setUint32(4, this.h0l); dataView.setUint32(8, this.h1h); dataView.setUint32(12, this.h1l); dataView.setUint32(16, this.h2h); dataView.setUint32(20, this.h2l); dataView.setUint32(24, this.h3h); if (bits >= 256) { dataView.setUint32(28, this.h3l); } if (bits >= 384) { dataView.setUint32(32, this.h4h); dataView.setUint32(36, this.h4l); dataView.setUint32(40, this.h5h); dataView.setUint32(44, this.h5l); } if (bits == 512) { dataView.setUint32(48, this.h6h); dataView.setUint32(52, this.h6l); dataView.setUint32(56, this.h7h); dataView.setUint32(60, this.h7l); } return buffer; }; Sha512.prototype.clone = function () { var hash = new Sha512(this.bits, false); this.copyTo(hash); return hash; }; Sha512.prototype.copyTo = function (hash) { var i = 0, attrs = [ 'h0h', 'h0l', 'h1h', 'h1l', 'h2h', 'h2l', 'h3h', 'h3l', 'h4h', 'h4l', 'h5h', 'h5l', 'h6h', 'h6l', 'h7h', 'h7l', 'start', 'bytes', 'hBytes', 'finalized', 'hashed', 'lastByteIndex' ]; for (i = 0; i < attrs.length; ++i) { hash[attrs[i]] = this[attrs[i]]; } for (i = 0; i < this.blocks.length; ++i) { hash.blocks[i] = this.blocks[i]; } }; function HmacSha512(key, bits, sharedMemory) { var notString, type = typeof key; if (type !== 'string') { if (type === 'object') { if (key === null) { throw new Error(INPUT_ERROR); } else if (ARRAY_BUFFER && key.constructor === ArrayBuffer) { key = new Uint8Array(key); } else if (!Array.isArray(key)) { if (!ARRAY_BUFFER || !ArrayBuffer.isView(key)) { throw new Error(INPUT_ERROR); } } } else { throw new Error(INPUT_ERROR); } notString = true; } var length = key.length; if (!notString) { var bytes = [], length = key.length, index = 0, code; for (var i = 0; i < length; ++i) { code = key.charCodeAt(i); if (code < 0x80) { bytes[index++] = code; } else if (code < 0x800) { bytes[index++] = (0xc0 | (code >> 6)); bytes[index++] = (0x80 | (code & 0x3f)); } else if (code < 0xd800 || code >= 0xe000) { bytes[index++] = (0xe0 | (code >> 12)); bytes[index++] = (0x80 | ((code >> 6) & 0x3f)); bytes[index++] = (0x80 | (code & 0x3f)); } else { code = 0x10000 + (((code & 0x3ff) << 10) | (key.charCodeAt(++i) & 0x3ff)); bytes[index++] = (0xf0 | (code >> 18)); bytes[index++] = (0x80 | ((code >> 12) & 0x3f)); bytes[index++] = (0x80 | ((code >> 6) & 0x3f)); bytes[index++] = (0x80 | (code & 0x3f)); } } key = bytes; } if (key.length > 128) { key = (new Sha512(bits, true)).update(key).array(); } var oKeyPad = [], iKeyPad = []; for (var i = 0; i < 128; ++i) { var b = key[i] || 0; oKeyPad[i] = 0x5c ^ b; iKeyPad[i] = 0x36 ^ b; } Sha512.call(this, bits, sharedMemory); this.update(iKeyPad); this.oKeyPad = oKeyPad; this.inner = true; this.sharedMemory = sharedMemory; } HmacSha512.prototype = new Sha512(); HmacSha512.prototype.finalize = function () { Sha512.prototype.finalize.call(this); if (this.inner) { this.inner = false; var innerHash = this.array(); Sha512.call(this, this.bits, this.sharedMemory); this.update(this.oKeyPad); this.update(innerHash); Sha512.prototype.finalize.call(this); } }; HmacSha512.prototype.clone = function () { var hash = new HmacSha512([], this.bits, false); this.copyTo(hash); hash.inner = this.inner; for (var i = 0; i < this.oKeyPad.length; ++i) { hash.oKeyPad[i] = this.oKeyPad[i]; } return hash; }; var exports = createMethod(512); exports.sha512 = exports; exports.sha384 = createMethod(384); exports.sha512_256 = createMethod(256); exports.sha512_224 = createMethod(224); exports.sha512.hmac = createHmacMethod(512); exports.sha384.hmac = createHmacMethod(384); exports.sha512_256.hmac = createHmacMethod(256); exports.sha512_224.hmac = createHmacMethod(224); if (COMMON_JS) { module.exports = exports; } else { root.sha512 = exports.sha512; root.sha384 = exports.sha384; root.sha512_256 = exports.sha512_256; root.sha512_224 = exports.sha512_224; if (AMD) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return exports; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } } })(); /***/ }), /***/ 5548: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { exports.unsigned = __webpack_require__(6922) exports.signed = __webpack_require__(4927) /***/ }), /***/ 4927: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { const Bn = __webpack_require__(3550) const Pipe = __webpack_require__(3533) module.exports = { encode, decode, write, read, readBn } function read (stream) { return readBn(stream).toString() } function readBn (stream) { const num = new Bn(0) let shift = 0 let byt while (true) { byt = stream.read(1)[0] num.ior(new Bn(byt & 0x7f).shln(shift)) shift += 7 if (byt >> 7 === 0) { break } } // sign extend if negitive if (byt & 0x40) { num.setn(shift) } return num.fromTwos(shift) } function write (number, stream) { let num = new Bn(number) const isNeg = num.isNeg() if (isNeg) { // add 8 bits for padding num = num.toTwos(num.bitLength() + 8) } while (true) { const i = num.maskn(7).toNumber() num.ishrn(7) if ((isNegOne(num) && (i & 0x40) !== 0) || (num.isZero() && (i & 0x40) === 0)) { stream.write([i]) break } else { stream.write([i | 0x80]) } } function isNegOne (num) { return isNeg && num.toString(2).indexOf('0') < 0 } } /** * LEB128 encodeds an interger * @param {String|Number} num * @return {Buffer} */ function encode (num) { const stream = new Pipe() write(num, stream) return stream.buffer } /** * decodes a LEB128 encoded interger * @param {Buffer} buffer * @return {String} */ function decode (buffer) { const stream = new Pipe(buffer) return read(stream) } /***/ }), /***/ 6922: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { const Bn = __webpack_require__(3550) const Pipe = __webpack_require__(3533) module.exports = { encode, decode, read, readBn, write } function read (stream) { return readBn(stream).toString() } function readBn (stream) { const num = new Bn(0) let shift = 0 let byt while (true) { byt = stream.read(1)[0] num.ior(new Bn(byt & 0x7f).shln(shift)) if (byt >> 7 === 0) { break } else { shift += 7 } } return num } function write (number, stream) { const num = new Bn(number) while (true) { const i = num.maskn(7).toNumber() num.ishrn(7) if (num.isZero()) { stream.write([i]) break } else { stream.write([i | 0x80]) } } } /** * LEB128 encodeds an interger * @param {String|Number} num * @return {Buffer} */ function encode (num) { const stream = new Pipe() write(num, stream) return stream.buffer } /** * decodes a LEB128 encoded interger * @param {Buffer} buffer * @return {String} */ function decode (buffer) { const stream = new Pipe(buffer) return read(stream) } /***/ }), /***/ 1675: /***/ (function(__unused_webpack_module, exports) { "use strict"; exports.supports = function supports (...manifests) { const manifest = manifests.reduce((acc, m) => Object.assign(acc, m), {}) return Object.assign(manifest, { snapshots: manifest.snapshots || false, permanence: manifest.permanence || false, seek: manifest.seek || false, clear: manifest.clear || false, getMany: manifest.getMany || false, keyIterator: manifest.keyIterator || false, valueIterator: manifest.valueIterator || false, iteratorNextv: manifest.iteratorNextv || false, iteratorAll: manifest.iteratorAll || false, status: manifest.status || false, createIfMissing: manifest.createIfMissing || false, errorIfExists: manifest.errorIfExists || false, deferredOpen: manifest.deferredOpen || false, promises: manifest.promises || false, streams: manifest.streams || false, encodings: Object.assign({}, manifest.encodings), events: Object.assign({}, manifest.events), additionalMethods: Object.assign({}, manifest.additionalMethods) }) } /***/ }), /***/ 8499: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const ModuleError = __webpack_require__(4473) const encodings = __webpack_require__(8002) const { Encoding } = __webpack_require__(8266) const { BufferFormat, ViewFormat, UTF8Format } = __webpack_require__(2376) const kFormats = Symbol('formats') const kEncodings = Symbol('encodings') const validFormats = new Set(['buffer', 'view', 'utf8']) /** @template T */ class Transcoder { /** * @param {Array<'buffer'|'view'|'utf8'>} formats */ constructor (formats) { if (!Array.isArray(formats)) { throw new TypeError("The first argument 'formats' must be an array") } else if (!formats.every(f => validFormats.has(f))) { // Note: we only only support aliases in key- and valueEncoding options (where we already did) throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'") } /** @type {Map, Encoding>} */ this[kEncodings] = new Map() this[kFormats] = new Set(formats) // Register encodings (done early in order to populate encodings()) for (const k in encodings) { try { this.encoding(k) } catch (err) { /* istanbul ignore if: assertion */ if (err.code !== 'LEVEL_ENCODING_NOT_SUPPORTED') throw err } } } /** * @returns {Array>} */ encodings () { return Array.from(new Set(this[kEncodings].values())) } /** * @param {string|MixedEncoding} encoding * @returns {Encoding} */ encoding (encoding) { let resolved = this[kEncodings].get(encoding) if (resolved === undefined) { if (typeof encoding === 'string' && encoding !== '') { resolved = lookup[encoding] if (!resolved) { throw new ModuleError(`Encoding '${encoding}' is not found`, { code: 'LEVEL_ENCODING_NOT_FOUND' }) } } else if (typeof encoding !== 'object' || encoding === null) { throw new TypeError("First argument 'encoding' must be a string or object") } else { resolved = from(encoding) } const { name, format } = resolved if (!this[kFormats].has(format)) { if (this[kFormats].has('view')) { resolved = resolved.createViewTranscoder() } else if (this[kFormats].has('buffer')) { resolved = resolved.createBufferTranscoder() } else if (this[kFormats].has('utf8')) { resolved = resolved.createUTF8Transcoder() } else { throw new ModuleError(`Encoding '${name}' cannot be transcoded`, { code: 'LEVEL_ENCODING_NOT_SUPPORTED' }) } } for (const k of [encoding, name, resolved.name, resolved.commonName]) { this[kEncodings].set(k, resolved) } } return resolved } } exports.Transcoder = Transcoder /** * @param {MixedEncoding} options * @returns {Encoding} */ function from (options) { if (options instanceof Encoding) { return options } // Loosely typed for ecosystem compatibility const maybeType = 'type' in options && typeof options.type === 'string' ? options.type : undefined const name = options.name || maybeType || `anonymous-${anonymousCount++}` switch (detectFormat(options)) { case 'view': return new ViewFormat({ ...options, name }) case 'utf8': return new UTF8Format({ ...options, name }) case 'buffer': return new BufferFormat({ ...options, name }) default: { throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'") } } } /** * If format is not provided, fallback to detecting `level-codec` * or `multiformats` encodings, else assume a format of buffer. * @param {MixedEncoding} options * @returns {string} */ function detectFormat (options) { if ('format' in options && options.format !== undefined) { return options.format } else if ('buffer' in options && typeof options.buffer === 'boolean') { return options.buffer ? 'buffer' : 'utf8' // level-codec } else if ('code' in options && Number.isInteger(options.code)) { return 'view' // multiformats } else { return 'buffer' } } /** * @typedef {import('./lib/encoding').MixedEncoding} MixedEncoding * @template TIn, TFormat, TOut */ /** * @type {Object.>} */ const aliases = { binary: encodings.buffer, 'utf-8': encodings.utf8 } /** * @type {Object.>} */ const lookup = { ...encodings, ...aliases } let anonymousCount = 0 /***/ }), /***/ 8266: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const ModuleError = __webpack_require__(4473) const formats = new Set(['buffer', 'view', 'utf8']) /** * @template TIn, TFormat, TOut * @abstract */ class Encoding { /** * @param {IEncoding} options */ constructor (options) { /** @type {(data: TIn) => TFormat} */ this.encode = options.encode || this.encode /** @type {(data: TFormat) => TOut} */ this.decode = options.decode || this.decode /** @type {string} */ this.name = options.name || this.name /** @type {string} */ this.format = options.format || this.format if (typeof this.encode !== 'function') { throw new TypeError("The 'encode' property must be a function") } if (typeof this.decode !== 'function') { throw new TypeError("The 'decode' property must be a function") } this.encode = this.encode.bind(this) this.decode = this.decode.bind(this) if (typeof this.name !== 'string' || this.name === '') { throw new TypeError("The 'name' property must be a string") } if (typeof this.format !== 'string' || !formats.has(this.format)) { throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'") } if (options.createViewTranscoder) { this.createViewTranscoder = options.createViewTranscoder } if (options.createBufferTranscoder) { this.createBufferTranscoder = options.createBufferTranscoder } if (options.createUTF8Transcoder) { this.createUTF8Transcoder = options.createUTF8Transcoder } } get commonName () { return /** @type {string} */ (this.name.split('+')[0]) } /** @return {BufferFormat} */ createBufferTranscoder () { throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'buffer'`, { code: 'LEVEL_ENCODING_NOT_SUPPORTED' }) } /** @return {ViewFormat} */ createViewTranscoder () { throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'view'`, { code: 'LEVEL_ENCODING_NOT_SUPPORTED' }) } /** @return {UTF8Format} */ createUTF8Transcoder () { throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'utf8'`, { code: 'LEVEL_ENCODING_NOT_SUPPORTED' }) } } exports.Encoding = Encoding /** * @typedef {import('./encoding').IEncoding} IEncoding * @template TIn, TFormat, TOut */ /** * @typedef {import('./formats').BufferFormat} BufferFormat * @template TIn, TOut */ /** * @typedef {import('./formats').ViewFormat} ViewFormat * @template TIn, TOut */ /** * @typedef {import('./formats').UTF8Format} UTF8Format * @template TIn, TOut */ /***/ }), /***/ 8002: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const { Buffer } = __webpack_require__(8764) || { Buffer: { isBuffer: () => false } } const { textEncoder, textDecoder } = __webpack_require__(5850)() const { BufferFormat, ViewFormat, UTF8Format } = __webpack_require__(2376) /** @type {(v: T) => v} */ const identity = (v) => v /** * @type {typeof import('./encodings').utf8} */ exports.utf8 = new UTF8Format({ encode: function (data) { // On node 16.9.1 buffer.toString() is 5x faster than TextDecoder return Buffer.isBuffer(data) ? data.toString('utf8') : ArrayBuffer.isView(data) ? textDecoder.decode(data) : String(data) }, decode: identity, name: 'utf8', createViewTranscoder () { return new ViewFormat({ encode: function (data) { return ArrayBuffer.isView(data) ? data : textEncoder.encode(data) }, decode: function (data) { return textDecoder.decode(data) }, name: `${this.name}+view` }) }, createBufferTranscoder () { return new BufferFormat({ encode: function (data) { return Buffer.isBuffer(data) ? data : ArrayBuffer.isView(data) ? Buffer.from(data.buffer, data.byteOffset, data.byteLength) : Buffer.from(String(data), 'utf8') }, decode: function (data) { return data.toString('utf8') }, name: `${this.name}+buffer` }) } }) /** * @type {typeof import('./encodings').json} */ exports.json = new UTF8Format({ encode: JSON.stringify, decode: JSON.parse, name: 'json' }) /** * @type {typeof import('./encodings').buffer} */ exports.buffer = new BufferFormat({ encode: function (data) { return Buffer.isBuffer(data) ? data : ArrayBuffer.isView(data) ? Buffer.from(data.buffer, data.byteOffset, data.byteLength) : Buffer.from(String(data), 'utf8') }, decode: identity, name: 'buffer', createViewTranscoder () { return new ViewFormat({ encode: function (data) { return ArrayBuffer.isView(data) ? data : Buffer.from(String(data), 'utf8') }, decode: function (data) { return Buffer.from(data.buffer, data.byteOffset, data.byteLength) }, name: `${this.name}+view` }) } }) /** * @type {typeof import('./encodings').view} */ exports.view = new ViewFormat({ encode: function (data) { return ArrayBuffer.isView(data) ? data : textEncoder.encode(data) }, decode: identity, name: 'view', createBufferTranscoder () { return new BufferFormat({ encode: function (data) { return Buffer.isBuffer(data) ? data : ArrayBuffer.isView(data) ? Buffer.from(data.buffer, data.byteOffset, data.byteLength) : Buffer.from(String(data), 'utf8') }, decode: identity, name: `${this.name}+buffer` }) } }) /** * @type {typeof import('./encodings').hex} */ exports.hex = new BufferFormat({ encode: function (data) { return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'hex') }, decode: function (buffer) { return buffer.toString('hex') }, name: 'hex' }) /** * @type {typeof import('./encodings').base64} */ exports.base64 = new BufferFormat({ encode: function (data) { return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'base64') }, decode: function (buffer) { return buffer.toString('base64') }, name: 'base64' }) /***/ }), /***/ 2376: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; const { Buffer } = __webpack_require__(8764) || {} const { Encoding } = __webpack_require__(8266) const textEndec = __webpack_require__(5850) /** * @template TIn, TOut * @extends {Encoding} */ class BufferFormat extends Encoding { /** * @param {Omit, 'format'>} options */ constructor (options) { super({ ...options, format: 'buffer' }) } /** @override */ createViewTranscoder () { return new ViewFormat({ encode: this.encode, // Buffer is a view (UInt8Array) decode: (data) => this.decode( Buffer.from(data.buffer, data.byteOffset, data.byteLength) ), name: `${this.name}+view` }) } /** @override */ createBufferTranscoder () { return this } } /** * @extends {Encoding} * @template TIn, TOut */ class ViewFormat extends Encoding { /** * @param {Omit, 'format'>} options */ constructor (options) { super({ ...options, format: 'view' }) } /** @override */ createBufferTranscoder () { return new BufferFormat({ encode: (data) => { const view = this.encode(data) return Buffer.from(view.buffer, view.byteOffset, view.byteLength) }, decode: this.decode, // Buffer is a view (UInt8Array) name: `${this.name}+buffer` }) } /** @override */ createViewTranscoder () { return this } } /** * @extends {Encoding} * @template TIn, TOut */ class UTF8Format extends Encoding { /** * @param {Omit, 'format'>} options */ constructor (options) { super({ ...options, format: 'utf8' }) } /** @override */ createBufferTranscoder () { return new BufferFormat({ encode: (data) => Buffer.from(this.encode(data), 'utf8'), decode: (data) => this.decode(data.toString('utf8')), name: `${this.name}+buffer` }) } /** @override */ createViewTranscoder () { const { textEncoder, textDecoder } = textEndec() return new ViewFormat({ encode: (data) => textEncoder.encode(this.encode(data)), decode: (data) => this.decode(textDecoder.decode(data)), name: `${this.name}+view` }) } /** @override */ createUTF8Transcoder () { return this } } exports.BufferFormat = BufferFormat exports.ViewFormat = ViewFormat exports.UTF8Format = UTF8Format /** * @typedef {import('./encoding').IEncoding} IEncoding * @template TIn, TFormat, TOut */ /***/ }), /***/ 5850: /***/ (function(module) { "use strict"; /** @type {{ textEncoder: TextEncoder, textDecoder: TextDecoder }|null} */ let lazy = null /** * Get semi-global instances of TextEncoder and TextDecoder. * @returns {{ textEncoder: TextEncoder, textDecoder: TextDecoder }} */ module.exports = function () { if (lazy === null) { lazy = { textEncoder: new TextEncoder(), textDecoder: new TextDecoder() } } return lazy } /***/ }), /***/ 3145: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { exports.Level = __webpack_require__(1708).BrowserLevel /***/ }), /***/ 8552: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var getNative = __webpack_require__(852), root = __webpack_require__(5639); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); module.exports = DataView; /***/ }), /***/ 1989: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var hashClear = __webpack_require__(1789), hashDelete = __webpack_require__(401), hashGet = __webpack_require__(7667), hashHas = __webpack_require__(1327), hashSet = __webpack_require__(1866); /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; module.exports = Hash; /***/ }), /***/ 8407: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var listCacheClear = __webpack_require__(7040), listCacheDelete = __webpack_require__(4125), listCacheGet = __webpack_require__(2117), listCacheHas = __webpack_require__(7518), listCacheSet = __webpack_require__(4705); /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; module.exports = ListCache; /***/ }), /***/ 7071: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var getNative = __webpack_require__(852), root = __webpack_require__(5639); /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'); module.exports = Map; /***/ }), /***/ 3369: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var mapCacheClear = __webpack_require__(4785), mapCacheDelete = __webpack_require__(1285), mapCacheGet = __webpack_require__(6000), mapCacheHas = __webpack_require__(9916), mapCacheSet = __webpack_require__(5265); /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; module.exports = MapCache; /***/ }), /***/ 3818: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var getNative = __webpack_require__(852), root = __webpack_require__(5639); /* Built-in method references that are verified to be native. */ var Promise = getNative(root, 'Promise'); module.exports = Promise; /***/ }), /***/ 8525: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var getNative = __webpack_require__(852), root = __webpack_require__(5639); /* Built-in method references that are verified to be native. */ var Set = getNative(root, 'Set'); module.exports = Set; /***/ }), /***/ 6384: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var ListCache = __webpack_require__(8407), stackClear = __webpack_require__(7465), stackDelete = __webpack_require__(3779), stackGet = __webpack_require__(7599), stackHas = __webpack_require__(4758), stackSet = __webpack_require__(4309); /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; module.exports = Stack; /***/ }), /***/ 2705: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var root = __webpack_require__(5639); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }), /***/ 1149: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var root = __webpack_require__(5639); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; /***/ }), /***/ 577: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var getNative = __webpack_require__(852), root = __webpack_require__(5639); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; /***/ }), /***/ 7412: /***/ (function(module) { /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; /***/ }), /***/ 4963: /***/ (function(module) { /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } module.exports = arrayFilter; /***/ }), /***/ 4636: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseTimes = __webpack_require__(2545), isArguments = __webpack_require__(5694), isArray = __webpack_require__(1469), isBuffer = __webpack_require__(4144), isIndex = __webpack_require__(213), isTypedArray = __webpack_require__(6719); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } module.exports = arrayLikeKeys; /***/ }), /***/ 2488: /***/ (function(module) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }), /***/ 4865: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseAssignValue = __webpack_require__(9465), eq = __webpack_require__(7813); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignValue; /***/ }), /***/ 8470: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var eq = __webpack_require__(7813); /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } module.exports = assocIndexOf; /***/ }), /***/ 4037: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var copyObject = __webpack_require__(8363), keys = __webpack_require__(3674); /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } module.exports = baseAssign; /***/ }), /***/ 3886: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var copyObject = __webpack_require__(8363), keysIn = __webpack_require__(1704); /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } module.exports = baseAssignIn; /***/ }), /***/ 9465: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var defineProperty = __webpack_require__(8777); /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } module.exports = baseAssignValue; /***/ }), /***/ 5990: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var Stack = __webpack_require__(6384), arrayEach = __webpack_require__(7412), assignValue = __webpack_require__(4865), baseAssign = __webpack_require__(4037), baseAssignIn = __webpack_require__(3886), cloneBuffer = __webpack_require__(4626), copyArray = __webpack_require__(278), copySymbols = __webpack_require__(8805), copySymbolsIn = __webpack_require__(1911), getAllKeys = __webpack_require__(8234), getAllKeysIn = __webpack_require__(6904), getTag = __webpack_require__(4160), initCloneArray = __webpack_require__(3824), initCloneByTag = __webpack_require__(9148), initCloneObject = __webpack_require__(8517), isArray = __webpack_require__(1469), isBuffer = __webpack_require__(4144), isMap = __webpack_require__(6688), isObject = __webpack_require__(3218), isSet = __webpack_require__(2928), keys = __webpack_require__(3674), keysIn = __webpack_require__(1704); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); } else if (isMap(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); } var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } module.exports = baseClone; /***/ }), /***/ 3118: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var isObject = __webpack_require__(3218); /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); module.exports = baseCreate; /***/ }), /***/ 8866: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var arrayPush = __webpack_require__(2488), isArray = __webpack_require__(1469); /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } module.exports = baseGetAllKeys; /***/ }), /***/ 4239: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var Symbol = __webpack_require__(2705), getRawTag = __webpack_require__(9607), objectToString = __webpack_require__(2333); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; /***/ }), /***/ 9454: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseGetTag = __webpack_require__(4239), isObjectLike = __webpack_require__(7005); /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } module.exports = baseIsArguments; /***/ }), /***/ 5588: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var getTag = __webpack_require__(4160), isObjectLike = __webpack_require__(7005); /** `Object#toString` result references. */ var mapTag = '[object Map]'; /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } module.exports = baseIsMap; /***/ }), /***/ 8458: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var isFunction = __webpack_require__(3560), isMasked = __webpack_require__(5346), isObject = __webpack_require__(3218), toSource = __webpack_require__(346); /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } module.exports = baseIsNative; /***/ }), /***/ 9221: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var getTag = __webpack_require__(4160), isObjectLike = __webpack_require__(7005); /** `Object#toString` result references. */ var setTag = '[object Set]'; /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } module.exports = baseIsSet; /***/ }), /***/ 8749: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseGetTag = __webpack_require__(4239), isLength = __webpack_require__(1780), isObjectLike = __webpack_require__(7005); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } module.exports = baseIsTypedArray; /***/ }), /***/ 280: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var isPrototype = __webpack_require__(5726), nativeKeys = __webpack_require__(6916); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } module.exports = baseKeys; /***/ }), /***/ 313: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var isObject = __webpack_require__(3218), isPrototype = __webpack_require__(5726), nativeKeysIn = __webpack_require__(3498); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = baseKeysIn; /***/ }), /***/ 2545: /***/ (function(module) { /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } module.exports = baseTimes; /***/ }), /***/ 1717: /***/ (function(module) { /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } module.exports = baseUnary; /***/ }), /***/ 4318: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var Uint8Array = __webpack_require__(1149); /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } module.exports = cloneArrayBuffer; /***/ }), /***/ 4626: /***/ (function(module, exports, __webpack_require__) { /* module decorator */ module = __webpack_require__.nmd(module); var root = __webpack_require__(5639); /** Detect free variable `exports`. */ var freeExports = true && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; /***/ }), /***/ 7157: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(4318); /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } module.exports = cloneDataView; /***/ }), /***/ 3147: /***/ (function(module) { /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } module.exports = cloneRegExp; /***/ }), /***/ 419: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var Symbol = __webpack_require__(2705); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } module.exports = cloneSymbol; /***/ }), /***/ 7133: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(4318); /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } module.exports = cloneTypedArray; /***/ }), /***/ 278: /***/ (function(module) { /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = copyArray; /***/ }), /***/ 8363: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var assignValue = __webpack_require__(4865), baseAssignValue = __webpack_require__(9465); /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } module.exports = copyObject; /***/ }), /***/ 8805: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var copyObject = __webpack_require__(8363), getSymbols = __webpack_require__(9551); /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } module.exports = copySymbols; /***/ }), /***/ 1911: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var copyObject = __webpack_require__(8363), getSymbolsIn = __webpack_require__(1442); /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } module.exports = copySymbolsIn; /***/ }), /***/ 4429: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var root = __webpack_require__(5639); /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; module.exports = coreJsData; /***/ }), /***/ 8777: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var getNative = __webpack_require__(852); var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); module.exports = defineProperty; /***/ }), /***/ 1957: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; module.exports = freeGlobal; /***/ }), /***/ 8234: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(8866), getSymbols = __webpack_require__(9551), keys = __webpack_require__(3674); /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } module.exports = getAllKeys; /***/ }), /***/ 6904: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(8866), getSymbolsIn = __webpack_require__(1442), keysIn = __webpack_require__(1704); /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } module.exports = getAllKeysIn; /***/ }), /***/ 5050: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var isKeyable = __webpack_require__(7019); /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } module.exports = getMapData; /***/ }), /***/ 852: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseIsNative = __webpack_require__(8458), getValue = __webpack_require__(7801); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } module.exports = getNative; /***/ }), /***/ 5924: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var overArg = __webpack_require__(5569); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }), /***/ 9607: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var Symbol = __webpack_require__(2705); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; /***/ }), /***/ 9551: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var arrayFilter = __webpack_require__(4963), stubArray = __webpack_require__(479); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; module.exports = getSymbols; /***/ }), /***/ 1442: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var arrayPush = __webpack_require__(2488), getPrototype = __webpack_require__(5924), getSymbols = __webpack_require__(9551), stubArray = __webpack_require__(479); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; module.exports = getSymbolsIn; /***/ }), /***/ 4160: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var DataView = __webpack_require__(8552), Map = __webpack_require__(7071), Promise = __webpack_require__(3818), Set = __webpack_require__(8525), WeakMap = __webpack_require__(577), baseGetTag = __webpack_require__(4239), toSource = __webpack_require__(346); /** `Object#toString` result references. */ var mapTag = '[object Map]', objectTag = '[object Object]', promiseTag = '[object Promise]', setTag = '[object Set]', weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } module.exports = getTag; /***/ }), /***/ 7801: /***/ (function(module) { /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } module.exports = getValue; /***/ }), /***/ 1789: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var nativeCreate = __webpack_require__(4536); /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } module.exports = hashClear; /***/ }), /***/ 401: /***/ (function(module) { /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } module.exports = hashDelete; /***/ }), /***/ 7667: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var nativeCreate = __webpack_require__(4536); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } module.exports = hashGet; /***/ }), /***/ 1327: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var nativeCreate = __webpack_require__(4536); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } module.exports = hashHas; /***/ }), /***/ 1866: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var nativeCreate = __webpack_require__(4536); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } module.exports = hashSet; /***/ }), /***/ 3824: /***/ (function(module) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } module.exports = initCloneArray; /***/ }), /***/ 9148: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(4318), cloneDataView = __webpack_require__(7157), cloneRegExp = __webpack_require__(3147), cloneSymbol = __webpack_require__(419), cloneTypedArray = __webpack_require__(7133); /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return new Ctor; case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return new Ctor; case symbolTag: return cloneSymbol(object); } } module.exports = initCloneByTag; /***/ }), /***/ 8517: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseCreate = __webpack_require__(3118), getPrototype = __webpack_require__(5924), isPrototype = __webpack_require__(5726); /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } module.exports = initCloneObject; /***/ }), /***/ 213: /***/ (function(module) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } module.exports = isIndex; /***/ }), /***/ 7019: /***/ (function(module) { /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } module.exports = isKeyable; /***/ }), /***/ 5346: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var coreJsData = __webpack_require__(4429); /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } module.exports = isMasked; /***/ }), /***/ 5726: /***/ (function(module) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } module.exports = isPrototype; /***/ }), /***/ 7040: /***/ (function(module) { /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } module.exports = listCacheClear; /***/ }), /***/ 4125: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var assocIndexOf = __webpack_require__(8470); /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } module.exports = listCacheDelete; /***/ }), /***/ 2117: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var assocIndexOf = __webpack_require__(8470); /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } module.exports = listCacheGet; /***/ }), /***/ 7518: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var assocIndexOf = __webpack_require__(8470); /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } module.exports = listCacheHas; /***/ }), /***/ 4705: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var assocIndexOf = __webpack_require__(8470); /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } module.exports = listCacheSet; /***/ }), /***/ 4785: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var Hash = __webpack_require__(1989), ListCache = __webpack_require__(8407), Map = __webpack_require__(7071); /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } module.exports = mapCacheClear; /***/ }), /***/ 1285: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var getMapData = __webpack_require__(5050); /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } module.exports = mapCacheDelete; /***/ }), /***/ 6000: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var getMapData = __webpack_require__(5050); /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } module.exports = mapCacheGet; /***/ }), /***/ 9916: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var getMapData = __webpack_require__(5050); /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } module.exports = mapCacheHas; /***/ }), /***/ 5265: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var getMapData = __webpack_require__(5050); /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } module.exports = mapCacheSet; /***/ }), /***/ 4536: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var getNative = __webpack_require__(852); /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; /***/ }), /***/ 6916: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var overArg = __webpack_require__(5569); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; /***/ }), /***/ 3498: /***/ (function(module) { /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } module.exports = nativeKeysIn; /***/ }), /***/ 1167: /***/ (function(module, exports, __webpack_require__) { /* module decorator */ module = __webpack_require__.nmd(module); var freeGlobal = __webpack_require__(1957); /** Detect free variable `exports`. */ var freeExports = true && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; /***/ }), /***/ 2333: /***/ (function(module) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; /***/ }), /***/ 5569: /***/ (function(module) { /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }), /***/ 5639: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var freeGlobal = __webpack_require__(1957); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; /***/ }), /***/ 7465: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var ListCache = __webpack_require__(8407); /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } module.exports = stackClear; /***/ }), /***/ 3779: /***/ (function(module) { /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } module.exports = stackDelete; /***/ }), /***/ 7599: /***/ (function(module) { /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } module.exports = stackGet; /***/ }), /***/ 4758: /***/ (function(module) { /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } module.exports = stackHas; /***/ }), /***/ 4309: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var ListCache = __webpack_require__(8407), Map = __webpack_require__(7071), MapCache = __webpack_require__(3369); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } module.exports = stackSet; /***/ }), /***/ 346: /***/ (function(module) { /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } module.exports = toSource; /***/ }), /***/ 361: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseClone = __webpack_require__(5990); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_SYMBOLS_FLAG = 4; /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } module.exports = cloneDeep; /***/ }), /***/ 7813: /***/ (function(module) { /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } module.exports = eq; /***/ }), /***/ 5694: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseIsArguments = __webpack_require__(9454), isObjectLike = __webpack_require__(7005); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; module.exports = isArguments; /***/ }), /***/ 1469: /***/ (function(module) { /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; module.exports = isArray; /***/ }), /***/ 1240: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var isFunction = __webpack_require__(3560), isLength = __webpack_require__(1780); /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } module.exports = isArrayLike; /***/ }), /***/ 4144: /***/ (function(module, exports, __webpack_require__) { /* module decorator */ module = __webpack_require__.nmd(module); var root = __webpack_require__(5639), stubFalse = __webpack_require__(5062); /** Detect free variable `exports`. */ var freeExports = true && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; module.exports = isBuffer; /***/ }), /***/ 3560: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseGetTag = __webpack_require__(4239), isObject = __webpack_require__(3218); /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } module.exports = isFunction; /***/ }), /***/ 1780: /***/ (function(module) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; /***/ }), /***/ 6688: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseIsMap = __webpack_require__(5588), baseUnary = __webpack_require__(1717), nodeUtil = __webpack_require__(1167); /* Node.js helper references. */ var nodeIsMap = nodeUtil && nodeUtil.isMap; /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; module.exports = isMap; /***/ }), /***/ 3218: /***/ (function(module) { /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }), /***/ 7005: /***/ (function(module) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } module.exports = isObjectLike; /***/ }), /***/ 2928: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseIsSet = __webpack_require__(9221), baseUnary = __webpack_require__(1717), nodeUtil = __webpack_require__(1167); /* Node.js helper references. */ var nodeIsSet = nodeUtil && nodeUtil.isSet; /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; module.exports = isSet; /***/ }), /***/ 6719: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var baseIsTypedArray = __webpack_require__(8749), baseUnary = __webpack_require__(1717), nodeUtil = __webpack_require__(1167); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; module.exports = isTypedArray; /***/ }), /***/ 3674: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(4636), baseKeys = __webpack_require__(280), isArrayLike = __webpack_require__(1240); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } module.exports = keys; /***/ }), /***/ 1704: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(4636), baseKeysIn = __webpack_require__(313), isArrayLike = __webpack_require__(1240); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } module.exports = keysIn; /***/ }), /***/ 479: /***/ (function(module) { /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } module.exports = stubArray; /***/ }), /***/ 5062: /***/ (function(module) { /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = stubFalse; /***/ }), /***/ 1271: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var process = __webpack_require__(3454); const { AbstractLevel, AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = __webpack_require__(875) const ModuleError = __webpack_require__(4473) const createRBT = __webpack_require__(4977) const rangeOptions = new Set(['gt', 'gte', 'lt', 'lte']) const kNone = Symbol('none') const kTree = Symbol('tree') const kIterator = Symbol('iterator') const kLowerBound = Symbol('lowerBound') const kUpperBound = Symbol('upperBound') const kOutOfRange = Symbol('outOfRange') const kReverse = Symbol('reverse') const kOptions = Symbol('options') const kTest = Symbol('test') const kAdvance = Symbol('advance') const kInit = Symbol('init') function compare (a, b) { // Only relevant when storeEncoding is 'utf8', // which guarantees that b is also a string. if (typeof a === 'string') { return a < b ? -1 : a > b ? 1 : 0 } const length = Math.min(a.byteLength, b.byteLength) for (let i = 0; i < length; i++) { const cmp = a[i] - b[i] if (cmp !== 0) return cmp } return a.byteLength - b.byteLength } function gt (value) { return compare(value, this[kUpperBound]) > 0 } function gte (value) { return compare(value, this[kUpperBound]) >= 0 } function lt (value) { return compare(value, this[kUpperBound]) < 0 } function lte (value) { return compare(value, this[kUpperBound]) <= 0 } class MemoryIterator extends AbstractIterator { constructor (db, options) { super(db, options) this[kInit](db[kTree], options) } _next (callback) { if (!this[kIterator].valid) return this.nextTick(callback) const key = this[kIterator].key const value = this[kIterator].value if (!this[kTest](key)) return this.nextTick(callback) this[kIterator][this[kAdvance]]() this.nextTick(callback, null, key, value) } _nextv (size, options, callback) { const it = this[kIterator] const entries = [] while (it.valid && entries.length < size && this[kTest](it.key)) { entries.push([it.key, it.value]) it[this[kAdvance]]() } this.nextTick(callback, null, entries) } _all (options, callback) { const size = this.limit - this.count const it = this[kIterator] const entries = [] while (it.valid && entries.length < size && this[kTest](it.key)) { entries.push([it.key, it.value]) it[this[kAdvance]]() } this.nextTick(callback, null, entries) } } class MemoryKeyIterator extends AbstractKeyIterator { constructor (db, options) { super(db, options) this[kInit](db[kTree], options) } _next (callback) { if (!this[kIterator].valid) return this.nextTick(callback) const key = this[kIterator].key if (!this[kTest](key)) return this.nextTick(callback) this[kIterator][this[kAdvance]]() this.nextTick(callback, null, key) } _nextv (size, options, callback) { const it = this[kIterator] const keys = [] while (it.valid && keys.length < size && this[kTest](it.key)) { keys.push(it.key) it[this[kAdvance]]() } this.nextTick(callback, null, keys) } _all (options, callback) { const size = this.limit - this.count const it = this[kIterator] const keys = [] while (it.valid && keys.length < size && this[kTest](it.key)) { keys.push(it.key) it[this[kAdvance]]() } this.nextTick(callback, null, keys) } } class MemoryValueIterator extends AbstractValueIterator { constructor (db, options) { super(db, options) this[kInit](db[kTree], options) } _next (callback) { if (!this[kIterator].valid) return this.nextTick(callback) const key = this[kIterator].key const value = this[kIterator].value if (!this[kTest](key)) return this.nextTick(callback) this[kIterator][this[kAdvance]]() this.nextTick(callback, null, value) } _nextv (size, options, callback) { const it = this[kIterator] const values = [] while (it.valid && values.length < size && this[kTest](it.key)) { values.push(it.value) it[this[kAdvance]]() } this.nextTick(callback, null, values) } _all (options, callback) { const size = this.limit - this.count const it = this[kIterator] const values = [] while (it.valid && values.length < size && this[kTest](it.key)) { values.push(it.value) it[this[kAdvance]]() } this.nextTick(callback, null, values) } } for (const Ctor of [MemoryIterator, MemoryKeyIterator, MemoryValueIterator]) { Ctor.prototype[kInit] = function (tree, options) { this[kReverse] = options.reverse this[kOptions] = options if (!this[kReverse]) { this[kAdvance] = 'next' this[kLowerBound] = 'gte' in options ? options.gte : 'gt' in options ? options.gt : kNone this[kUpperBound] = 'lte' in options ? options.lte : 'lt' in options ? options.lt : kNone if (this[kLowerBound] === kNone) { this[kIterator] = tree.begin } else if ('gte' in options) { this[kIterator] = tree.ge(this[kLowerBound]) } else { this[kIterator] = tree.gt(this[kLowerBound]) } if (this[kUpperBound] !== kNone) { this[kTest] = 'lte' in options ? lte : lt } } else { this[kAdvance] = 'prev' this[kLowerBound] = 'lte' in options ? options.lte : 'lt' in options ? options.lt : kNone this[kUpperBound] = 'gte' in options ? options.gte : 'gt' in options ? options.gt : kNone if (this[kLowerBound] === kNone) { this[kIterator] = tree.end } else if ('lte' in options) { this[kIterator] = tree.le(this[kLowerBound]) } else { this[kIterator] = tree.lt(this[kLowerBound]) } if (this[kUpperBound] !== kNone) { this[kTest] = 'gte' in options ? gte : gt } } } Ctor.prototype[kTest] = function () { return true } Ctor.prototype[kOutOfRange] = function (target) { if (!this[kTest](target)) { return true } else if (this[kLowerBound] === kNone) { return false } else if (!this[kReverse]) { if ('gte' in this[kOptions]) { return compare(target, this[kLowerBound]) < 0 } else { return compare(target, this[kLowerBound]) <= 0 } } else { if ('lte' in this[kOptions]) { return compare(target, this[kLowerBound]) > 0 } else { return compare(target, this[kLowerBound]) >= 0 } } } Ctor.prototype._seek = function (target, options) { if (this[kOutOfRange](target)) { this[kIterator] = this[kIterator].tree.end this[kIterator].next() } else if (this[kReverse]) { this[kIterator] = this[kIterator].tree.le(target) } else { this[kIterator] = this[kIterator].tree.ge(target) } } } class MemoryLevel extends AbstractLevel { constructor (location, options, _) { // Take a dummy location argument to align with other implementations if (typeof location === 'object' && location !== null) { options = location } // To help migrating from level-mem to abstract-level if (typeof location === 'function' || typeof options === 'function' || typeof _ === 'function') { throw new ModuleError('The levelup-style callback argument has been removed', { code: 'LEVEL_LEGACY' }) } let { storeEncoding, ...forward } = options || {} storeEncoding = storeEncoding || 'buffer' // Our compare() function supports Buffer, Uint8Array and strings if (!['buffer', 'view', 'utf8'].includes(storeEncoding)) { throw new ModuleError("The storeEncoding option must be 'buffer', 'view' or 'utf8'", { code: 'LEVEL_ENCODING_NOT_SUPPORTED' }) } super({ seek: true, permanence: false, createIfMissing: false, errorIfExists: false, encodings: { [storeEncoding]: true } }, forward) this[kTree] = createRBT(compare) } _put (key, value, options, callback) { const it = this[kTree].find(key) if (it.valid) { this[kTree] = it.update(value) } else { this[kTree] = this[kTree].insert(key, value) } this.nextTick(callback) } _get (key, options, callback) { const value = this[kTree].get(key) if (typeof value === 'undefined') { // TODO: use error code (not urgent, abstract-level normalizes this) return this.nextTick(callback, new Error('NotFound')) } this.nextTick(callback, null, value) } _getMany (keys, options, callback) { this.nextTick(callback, null, keys.map(key => this[kTree].get(key))) } _del (key, options, callback) { this[kTree] = this[kTree].remove(key) this.nextTick(callback) } _batch (operations, options, callback) { let tree = this[kTree] for (const op of operations) { const key = op.key const it = tree.find(key) if (op.type === 'put') { tree = it.valid ? it.update(op.value) : tree.insert(key, op.value) } else { tree = it.remove() } } this[kTree] = tree this.nextTick(callback) } _clear (options, callback) { if (options.limit === -1 && !Object.keys(options).some(isRangeOption)) { // Delete everything by creating a new empty tree. this[kTree] = createRBT(compare) return this.nextTick(callback) } const iterator = this._keys({ ...options }) const limit = iterator.limit let count = 0 const loop = () => { // TODO: add option to control "batch size" for (let i = 0; i < 500; i++) { if (++count > limit) return callback() if (!iterator[kIterator].valid) return callback() if (!iterator[kTest](iterator[kIterator].key)) return callback() // Must also include changes made in parallel to clear() this[kTree] = this[kTree].remove(iterator[kIterator].key) iterator[kIterator][iterator[kAdvance]]() } // Some time to breathe this.nextTick(loop) } this.nextTick(loop) } _iterator (options) { return new MemoryIterator(this, options) } _keys (options) { return new MemoryKeyIterator(this, options) } _values (options) { return new MemoryValueIterator(this, options) } } exports.MemoryLevel = MemoryLevel // Use setImmediate() in Node.js to allow IO in between our callbacks if (typeof process !== 'undefined' && !true && 0 && 0) {} function isRangeOption (k) { return rangeOptions.has(k) } /***/ }), /***/ 9746: /***/ (function(module) { module.exports = assert; function assert(val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } assert.equal = function assertEqual(l, r, msg) { if (l != r) throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); }; /***/ }), /***/ 4504: /***/ (function(__unused_webpack_module, exports) { "use strict"; var utils = exports; function toArray(msg, enc) { if (Array.isArray(msg)) return msg.slice(); if (!msg) return []; var res = []; if (typeof msg !== 'string') { for (var i = 0; i < msg.length; i++) res[i] = msg[i] | 0; return res; } if (enc === 'hex') { msg = msg.replace(/[^a-z0-9]+/ig, ''); if (msg.length % 2 !== 0) msg = '0' + msg; for (var i = 0; i < msg.length; i += 2) res.push(parseInt(msg[i] + msg[i + 1], 16)); } else { for (var i = 0; i < msg.length; i++) { var c = msg.charCodeAt(i); var hi = c >> 8; var lo = c & 0xff; if (hi) res.push(hi, lo); else res.push(lo); } } return res; } utils.toArray = toArray; function zero2(word) { if (word.length === 1) return '0' + word; else return word; } utils.zero2 = zero2; function toHex(msg) { var res = ''; for (var i = 0; i < msg.length; i++) res += zero2(msg[i].toString(16)); return res; } utils.toHex = toHex; utils.encode = function encode(arr, enc) { if (enc === 'hex') return toHex(arr); else return arr; }; /***/ }), /***/ 4473: /***/ (function(module) { "use strict"; module.exports = class ModuleError extends Error { /** * @param {string} message Error message * @param {{ code?: string, cause?: Error, expected?: boolean, transient?: boolean }} [options] */ constructor (message, options) { super(message || '') if (typeof options === 'object' && options !== null) { if (options.code) this.code = String(options.code) if (options.expected) this.expected = true if (options.transient) this.transient = true if (options.cause) this.cause = options.cause } if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor) } } } /***/ }), /***/ 3454: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var ref, ref1; module.exports = ((ref = __webpack_require__.g.process) == null ? void 0 : ref.env) && typeof ((ref1 = __webpack_require__.g.process) == null ? void 0 : ref1.env) === "object" ? __webpack_require__.g.process : __webpack_require__(7663); //# sourceMappingURL=process.js.map /***/ }), /***/ 7663: /***/ (function(module) { var __dirname = "/"; (function(){var e={308:function(e){var t=e.exports={};var r;var n;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){r=setTimeout}else{r=defaultSetTimout}}catch(e){r=defaultSetTimout}try{if(typeof clearTimeout==="function"){n=clearTimeout}else{n=defaultClearTimeout}}catch(e){n=defaultClearTimeout}})();function runTimeout(e){if(r===setTimeout){return setTimeout(e,0)}if((r===defaultSetTimout||!r)&&setTimeout){r=setTimeout;return setTimeout(e,0)}try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}function runClearTimeout(e){if(n===clearTimeout){return clearTimeout(e)}if((n===defaultClearTimeout||!n)&&clearTimeout){n=clearTimeout;return clearTimeout(e)}try{return n(e)}catch(t){try{return n.call(null,e)}catch(t){return n.call(this,e)}}}var i=[];var o=false;var u;var a=-1;function cleanUpNextTick(){if(!o||!u){return}o=false;if(u.length){i=u.concat(i)}else{a=-1}if(i.length){drainQueue()}}function drainQueue(){if(o){return}var e=runTimeout(cleanUpNextTick);o=true;var t=i.length;while(t){u=i;i=[];while(++a1){for(var r=1;rString(e)));if(r>2){return`one of ${t} ${e.slice(0,r-1).join(", ")}, or `+e[r-1]}else if(r===2){return`one of ${t} ${e[0]} or ${e[1]}`}else{return`of ${t} ${e[0]}`}}else{return`of ${t} ${String(e)}`}}function startsWith(e,t,r){return e.substr(!r||r<0?0:+r,t.length)===t}function endsWith(e,t,r){if(r===undefined||r>e.length){r=e.length}return e.substring(r-t.length,r)===t}function includes(e,t,r){if(typeof r!=="number"){r=0}if(r+t.length>e.length){return false}else{return e.indexOf(t,r)!==-1}}createErrorType("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError);createErrorType("ERR_INVALID_ARG_TYPE",(function(e,t,r){let n;if(typeof t==="string"&&startsWith(t,"not ")){n="must not be";t=t.replace(/^not /,"")}else{n="must be"}let i;if(endsWith(e," argument")){i=`The ${e} ${n} ${oneOf(t,"type")}`}else{const r=includes(e,".")?"property":"argument";i=`The "${e}" ${r} ${n} ${oneOf(t,"type")}`}i+=`. Received type ${typeof r}`;return i}),TypeError);createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");createErrorType("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"}));createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close");createErrorType("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"}));createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times");createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end");createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);createErrorType("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError);createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");e.exports.q=t},716:function(e,t,r){"use strict";var n=Object.keys||function(e){var t=[];for(var r in e){t.push(r)}return t};e.exports=Duplex;var i=r(787);var a=r(513);r(140)(Duplex,i);{var o=n(a.prototype);for(var s=0;s0){if(typeof t!=="string"&&!a.objectMode&&Object.getPrototypeOf(t)!==s.prototype){t=_uint8ArrayToBuffer(t)}if(n){if(a.endEmitted)R(e,new v);else addChunk(e,a,t,true)}else if(a.ended){R(e,new y)}else if(a.destroyed){return false}else{a.reading=false;if(a.decoder&&!r){t=a.decoder.write(t);if(a.objectMode||t.length!==0)addChunk(e,a,t,false);else maybeReadMore(e,a)}else{addChunk(e,a,t,false)}}}else if(!n){a.reading=false;maybeReadMore(e,a)}}return!a.ended&&(a.length=T){e=T}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function howMuchToRead(e,t){if(e<=0||t.length===0&&t.ended)return 0;if(t.objectMode)return 1;if(e!==e){if(t.flowing&&t.length)return t.buffer.head.data.length;else return t.length}if(e>t.highWaterMark)t.highWaterMark=computeNewHighWaterMark(e);if(e<=t.length)return e;if(!t.ended){t.needReadable=true;return 0}return t.length}Readable.prototype.read=function(e){u("read",e);e=parseInt(e,10);var t=this._readableState;var r=e;if(e!==0)t.emittedReadable=false;if(e===0&&t.needReadable&&((t.highWaterMark!==0?t.length>=t.highWaterMark:t.length>0)||t.ended)){u("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)endReadable(this);else emitReadable(this);return null}e=howMuchToRead(e,t);if(e===0&&t.ended){if(t.length===0)endReadable(this);return null}var n=t.needReadable;u("need readable",n);if(t.length===0||t.length-e0)i=fromList(e,t);else i=null;if(i===null){t.needReadable=t.length<=t.highWaterMark;e=0}else{t.length-=e;t.awaitDrain=0}if(t.length===0){if(!t.ended)t.needReadable=true;if(r!==e&&t.ended)endReadable(this)}if(i!==null)this.emit("data",i);return i};function onEofChunk(e,t){u("onEofChunk");if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;if(t.sync){emitReadable(e)}else{t.needReadable=false;if(!t.emittedReadable){t.emittedReadable=true;emitReadable_(e)}}}function emitReadable(e){var t=e._readableState;u("emitReadable",t.needReadable,t.emittedReadable);t.needReadable=false;if(!t.emittedReadable){u("emitReadable",t.flowing);t.emittedReadable=true;process.nextTick(emitReadable_,e)}}function emitReadable_(e){var t=e._readableState;u("emitReadable_",t.destroyed,t.length,t.ended);if(!t.destroyed&&(t.length||t.ended)){e.emit("readable");t.emittedReadable=false}t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark;flow(e)}function maybeReadMore(e,t){if(!t.readingMore){t.readingMore=true;process.nextTick(maybeReadMore_,e,t)}}function maybeReadMore_(e,t){while(!t.reading&&!t.ended&&(t.length1&&indexOf(n.pipes,e)!==-1)&&!f){u("false write response, pause",n.awaitDrain);n.awaitDrain++}r.pause()}}function onerror(t){u("onerror",t);unpipe();e.removeListener("error",onerror);if(a(e,"error")===0)R(e,t)}prependListener(e,"error",onerror);function onclose(){e.removeListener("finish",onfinish);unpipe()}e.once("close",onclose);function onfinish(){u("onfinish");e.removeListener("close",onclose);unpipe()}e.once("finish",onfinish);function unpipe(){u("unpipe");r.unpipe(e)}e.emit("pipe",r);if(!n.flowing){u("pipe resume");r.resume()}return e};function pipeOnDrain(e){return function pipeOnDrainFunctionResult(){var t=e._readableState;u("pipeOnDrain",t.awaitDrain);if(t.awaitDrain)t.awaitDrain--;if(t.awaitDrain===0&&a(e,"data")){t.flowing=true;flow(e)}}}Readable.prototype.unpipe=function(e){var t=this._readableState;var r={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1){if(e&&e!==t.pipes)return this;if(!e)e=t.pipes;t.pipes=null;t.pipesCount=0;t.flowing=false;if(e)e.emit("unpipe",this,r);return this}if(!e){var n=t.pipes;var i=t.pipesCount;t.pipes=null;t.pipesCount=0;t.flowing=false;for(var a=0;a0;if(n.flowing!==false)this.resume()}else if(e==="readable"){if(!n.endEmitted&&!n.readableListening){n.readableListening=n.needReadable=true;n.flowing=false;n.emittedReadable=false;u("on readable",n.length,n.reading);if(n.length){emitReadable(this)}else if(!n.reading){process.nextTick(nReadingNextTick,this)}}}return r};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.removeListener=function(e,t){var r=o.prototype.removeListener.call(this,e,t);if(e==="readable"){process.nextTick(updateReadableListening,this)}return r};Readable.prototype.removeAllListeners=function(e){var t=o.prototype.removeAllListeners.apply(this,arguments);if(e==="readable"||e===undefined){process.nextTick(updateReadableListening,this)}return t};function updateReadableListening(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0;if(t.resumeScheduled&&!t.paused){t.flowing=true}else if(e.listenerCount("data")>0){e.resume()}}function nReadingNextTick(e){u("readable nexttick read 0");e.read(0)}Readable.prototype.resume=function(){var e=this._readableState;if(!e.flowing){u("resume");e.flowing=!e.readableListening;resume(this,e)}e.paused=false;return this};function resume(e,t){if(!t.resumeScheduled){t.resumeScheduled=true;process.nextTick(resume_,e,t)}}function resume_(e,t){u("resume",t.reading);if(!t.reading){e.read(0)}t.resumeScheduled=false;e.emit("resume");flow(e);if(t.flowing&&!t.reading)e.read(0)}Readable.prototype.pause=function(){u("call pause flowing=%j",this._readableState.flowing);if(this._readableState.flowing!==false){u("pause");this._readableState.flowing=false;this.emit("pause")}this._readableState.paused=true;return this};function flow(e){var t=e._readableState;u("flow",t.flowing);while(t.flowing&&e.read()!==null){}}Readable.prototype.wrap=function(e){var t=this;var r=this._readableState;var n=false;e.on("end",(function(){u("wrapped end");if(r.decoder&&!r.ended){var e=r.decoder.end();if(e&&e.length)t.push(e)}t.push(null)}));e.on("data",(function(i){u("wrapped data");if(r.decoder)i=r.decoder.write(i);if(r.objectMode&&(i===null||i===undefined))return;else if(!r.objectMode&&(!i||!i.length))return;var a=t.push(i);if(!a){n=true;e.pause()}}));for(var i in e){if(this[i]===undefined&&typeof e[i]==="function"){this[i]=function methodWrap(t){return function methodWrapReturnFunction(){return e[t].apply(e,arguments)}}(i)}}for(var a=0;a=t.length){if(t.decoder)r=t.buffer.join("");else if(t.buffer.length===1)r=t.buffer.first();else r=t.buffer.concat(t.length);t.buffer.clear()}else{r=t.buffer.consume(e,t.decoder)}return r}function endReadable(e){var t=e._readableState;u("endReadable",t.endEmitted);if(!t.endEmitted){t.ended=true;process.nextTick(endReadableNT,t,e)}}function endReadableNT(e,t){u("endReadableNT",e.endEmitted,e.length);if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end");if(e.autoDestroy){var r=t._writableState;if(!r||r.autoDestroy&&r.finished){t.destroy()}}}}if(typeof Symbol==="function"){Readable.from=function(e,t){if(S===undefined){S=r(720)}return S(Readable,e,t)}}function indexOf(e,t){for(var r=0,n=e.length;r-1))throw new v(e);this._writableState.defaultEncoding=e;return this};Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:false,get:function get(){return this._writableState&&this._writableState.getBuffer()}});function decodeChunk(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=o.from(t,r)}return t}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function get(){return this._writableState.highWaterMark}});function writeOrBuffer(e,t,r,n,i,a){if(!r){var o=decodeChunk(t,n,i);if(n!==o){r=true;i="buffer";n=o}}var s=t.objectMode?1:n.length;t.length+=s;var f=t.length0)this.tail.next=t;else this.head=t;this.tail=t;++this.length}},{key:"unshift",value:function unshift(e){var t={data:e,next:this.head};if(this.length===0)this.tail=t;this.head=t;++this.length}},{key:"shift",value:function shift(){if(this.length===0)return;var e=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return e}},{key:"clear",value:function clear(){this.head=this.tail=null;this.length=0}},{key:"join",value:function join(e){if(this.length===0)return"";var t=this.head;var r=""+t.data;while(t=t.next){r+=e+t.data}return r}},{key:"concat",value:function concat(e){if(this.length===0)return i.alloc(0);var t=i.allocUnsafe(e>>>0);var r=this.head;var n=0;while(r){copyBuffer(r.data,t,n);n+=r.data.length;r=r.next}return t}},{key:"consume",value:function consume(e,t){var r;if(ei.length?i.length:e;if(a===i.length)n+=i;else n+=i.slice(0,e);e-=a;if(e===0){if(a===i.length){++r;if(t.next)this.head=t.next;else this.head=this.tail=null}else{this.head=t;t.data=i.slice(a)}break}++r}this.length-=r;return n}},{key:"_getBuffer",value:function _getBuffer(e){var t=i.allocUnsafe(e);var r=this.head;var n=1;r.data.copy(t);e-=r.data.length;while(r=r.next){var a=r.data;var o=e>a.length?a.length:e;a.copy(t,t.length-e,0,o);e-=o;if(e===0){if(o===a.length){++n;if(r.next)this.head=r.next;else this.head=this.tail=null}else{this.head=r;r.data=a.slice(o)}break}++n}this.length-=n;return t}},{key:s,value:function value(e,t){return o(this,_objectSpread({},t,{depth:0,customInspect:false}))}}]);return BufferList}()},289:function(e){"use strict";function destroy(e,t){var r=this;var n=this._readableState&&this._readableState.destroyed;var i=this._writableState&&this._writableState.destroyed;if(n||i){if(t){t(e)}else if(e){if(!this._writableState){process.nextTick(emitErrorNT,this,e)}else if(!this._writableState.errorEmitted){this._writableState.errorEmitted=true;process.nextTick(emitErrorNT,this,e)}}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(e||null,(function(e){if(!t&&e){if(!r._writableState){process.nextTick(emitErrorAndCloseNT,r,e)}else if(!r._writableState.errorEmitted){r._writableState.errorEmitted=true;process.nextTick(emitErrorAndCloseNT,r,e)}else{process.nextTick(emitCloseNT,r)}}else if(t){process.nextTick(emitCloseNT,r);t(e)}else{process.nextTick(emitCloseNT,r)}}));return this}function emitErrorAndCloseNT(e,t){emitErrorNT(e,t);emitCloseNT(e)}function emitCloseNT(e){if(e._writableState&&!e._writableState.emitClose)return;if(e._readableState&&!e._readableState.emitClose)return;e.emit("close")}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finalCalled=false;this._writableState.prefinished=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(e,t){e.emit("error",t)}function errorOrDestroy(e,t){var r=e._readableState;var n=e._writableState;if(r&&r.autoDestroy||n&&n.autoDestroy)e.destroy(t);else e.emit("error",t)}e.exports={destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}},7:function(e,t,r){"use strict";var n=r(349).q.ERR_STREAM_PREMATURE_CLOSE;function once(e){var t=false;return function(){if(t)return;t=true;for(var r=arguments.length,n=new Array(r),i=0;i0;return destroyer(e,a,s,(function(e){if(!i)i=e;if(e)o.forEach(call);if(a)return;o.forEach(call);n(i)}))}));return t.reduce(pipe)}e.exports=pipeline},483:function(e,t,r){"use strict";var n=r(349).q.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}function getHighWaterMark(e,t,r,i){var a=highWaterMarkFrom(t,i,r);if(a!=null){if(!(isFinite(a)&&Math.floor(a)===a)||a<0){var o=i?r:"highWaterMark";throw new n(o,a)}return Math.floor(a)}return e.objectMode?16:16*1024}e.exports={getHighWaterMark:getHighWaterMark}},455:function(e,t,r){e.exports=r(781)},207:function(e,t,r){var n=r(300);var i=n.Buffer;function copyProps(e,t){for(var r in e){t[r]=e[r]}}if(i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow){e.exports=n}else{copyProps(n,t);t.Buffer=SafeBuffer}function SafeBuffer(e,t,r){return i(e,t,r)}SafeBuffer.prototype=Object.create(i.prototype);copyProps(i,SafeBuffer);SafeBuffer.from=function(e,t,r){if(typeof e==="number"){throw new TypeError("Argument must not be a number")}return i(e,t,r)};SafeBuffer.alloc=function(e,t,r){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}var n=i(e);if(t!==undefined){if(typeof r==="string"){n.fill(t,r)}else{n.fill(t)}}else{n.fill(0)}return n};SafeBuffer.allocUnsafe=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return i(e)};SafeBuffer.allocUnsafeSlow=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return n.SlowBuffer(e)}},552:function(e,t,r){e.exports=Stream;var n=r(361).EventEmitter;var i=r(140);i(Stream,n);Stream.Readable=r(787);Stream.Writable=r(513);Stream.Duplex=r(716);Stream.Transform=r(551);Stream.PassThrough=r(788);Stream.finished=r(7);Stream.pipeline=r(522);Stream.Stream=Stream;function Stream(){n.call(this)}Stream.prototype.pipe=function(e,t){var r=this;function ondata(t){if(e.writable){if(false===e.write(t)&&r.pause){r.pause()}}}r.on("data",ondata);function ondrain(){if(r.readable&&r.resume){r.resume()}}e.on("drain",ondrain);if(!e._isStdio&&(!t||t.end!==false)){r.on("end",onend);r.on("close",onclose)}var i=false;function onend(){if(i)return;i=true;e.end()}function onclose(){if(i)return;i=true;if(typeof e.destroy==="function")e.destroy()}function onerror(e){cleanup();if(n.listenerCount(this,"error")===0){throw e}}r.on("error",onerror);e.on("error",onerror);function cleanup(){r.removeListener("data",ondata);e.removeListener("drain",ondrain);r.removeListener("end",onend);r.removeListener("close",onclose);r.removeListener("error",onerror);e.removeListener("error",onerror);r.removeListener("end",cleanup);r.removeListener("close",cleanup);e.removeListener("close",cleanup)}r.on("end",cleanup);r.on("close",cleanup);e.on("close",cleanup);e.emit("pipe",r);return e}},862:function(e,t,r){"use strict";var n=r(207).Buffer;var i=n.isEncoding||function(e){e=""+e;switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function _normalizeEncoding(e){if(!e)return"utf8";var t;while(true){switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase();t=true}}}function normalizeEncoding(e){var t=_normalizeEncoding(e);if(typeof t!=="string"&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}t.s=StringDecoder;function StringDecoder(e){this.encoding=normalizeEncoding(e);var t;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;t=4;break;case"utf8":this.fillLast=utf8FillLast;t=4;break;case"base64":this.text=base64Text;this.end=base64End;t=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=n.allocUnsafe(t)}StringDecoder.prototype.write=function(e){if(e.length===0)return"";var t;var r;if(this.lastNeed){t=this.fillLast(e);if(t===undefined)return"";r=this.lastNeed;this.lastNeed=0}else{r=0}if(r>5===6)return 2;else if(e>>4===14)return 3;else if(e>>3===30)return 4;return e>>6===2?-1:-2}function utf8CheckIncomplete(e,t,r){var n=t.length-1;if(n=0){if(i>0)e.lastNeed=i-1;return i}if(--n=0){if(i>0)e.lastNeed=i-2;return i}if(--n=0){if(i>0){if(i===2)i=0;else e.lastNeed=i-3}return i}return 0}function utf8CheckExtraBytes(e,t,r){if((t[0]&192)!==128){e.lastNeed=0;return"�"}if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128){e.lastNeed=1;return"�"}if(e.lastNeed>2&&t.length>2){if((t[2]&192)!==128){e.lastNeed=2;return"�"}}}}function utf8FillLast(e){var t=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,e,t);if(r!==undefined)return r;if(this.lastNeed<=e.length){e.copy(this.lastChar,t,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}e.copy(this.lastChar,t,0,e.length);this.lastNeed-=e.length}function utf8Text(e,t){var r=utf8CheckIncomplete(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);e.copy(this.lastChar,0,n);return e.toString("utf8",t,n)}function utf8End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+"�";return t}function utf16Text(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=e[e.length-1];return e.toString("utf16le",t,e.length-1)}function utf16End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function base64Text(e,t){var r=(e.length-t)%3;if(r===0)return e.toString("base64",t);this.lastNeed=3-r;this.lastTotal=3;if(r===1){this.lastChar[0]=e[e.length-1]}else{this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1]}return e.toString("base64",t,e.length-r)}function base64End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+this.lastChar.toString("base64",0,3-this.lastNeed);return t}function simpleWrite(e){return e.toString(this.encoding)}function simpleEnd(e){return e&&e.length?this.write(e):""}},777:function(e){e.exports=deprecate;function deprecate(e,t){if(config("noDeprecation")){return e}var r=false;function deprecated(){if(!r){if(config("throwDeprecation")){throw new Error(t)}else if(config("traceDeprecation")){console.trace(t)}else{console.warn(t)}r=true}return e.apply(this,arguments)}return deprecated}function config(e){try{if(!__webpack_require__.g.localStorage)return false}catch(e){return false}var t=__webpack_require__.g.localStorage[e];if(null==t)return false;return String(t).toLowerCase()==="true"}},300:function(e){"use strict";e.exports=__webpack_require__(8764)},361:function(e){"use strict";e.exports=__webpack_require__(7187)},781:function(e){"use strict";e.exports=(__webpack_require__(7187).EventEmitter)},837:function(e){"use strict";e.exports=__webpack_require__(9539)}};var t={};function __nccwpck_require__(r){var n=t[r];if(n!==undefined){return n.exports}var i=t[r]={exports:{}};var a=true;try{e[r](i,i.exports,__nccwpck_require__);a=false}finally{if(a)delete t[r]}return i.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var r=__nccwpck_require__(552);module.exports=r})(); /***/ }), /***/ 1951: /***/ (function(module) { var __dirname = "/"; (function(){var __webpack_modules__={965:function(__unused_webpack_module,exports){var indexOf=function(e,t){if(e.indexOf)return e.indexOf(t);else for(var r=0;r */ let promise module.exports = typeof queueMicrotask === 'function' ? queueMicrotask.bind(typeof window !== 'undefined' ? window : __webpack_require__.g) // reuse resolved promise, and allocate it lazily : cb => (promise || (promise = Promise.resolve())) .then(cb) .catch(err => setTimeout(() => { throw err }, 0)) /***/ }), /***/ 9180: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { window.global = window; __webpack_require__.g.fetch = window.fetch; module.exports.Buffer = __webpack_require__(8764).Buffer; /***/ }), /***/ 497: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { /** * Converts a wasm binary into a json representation * @param {Buffer} * @return {Array} */ exports.wasm2json = __webpack_require__(3195) /** * Converts a json representation to a wasm binary * @param {Array} * @return {Buffer} */ exports.json2wasm = __webpack_require__(4747) /** * Converts text to json. The only accepts text that is a simple list of opcode name and immediates * @param {String} * @return {Object} * @example * const codeStr = ` * i64.const 1 * i64.const 2 * i64.add * ` * const json = text2json(codeStr) */ exports.text2json = __webpack_require__(9837) exports.Iterator = __webpack_require__(3804) /***/ }), /***/ 3804: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { const Buffer = (__webpack_require__(1415).Buffer); const leb128 = (__webpack_require__(5548).unsigned); const wasm2json = __webpack_require__(3195); const Pipe = __webpack_require__(825); const SECTIONS = [ 'custom', 'type', 'import', 'function', 'table', 'memory', 'global', 'export', 'start', 'element', 'code', 'data', ]; /** * The Module Iterator allows for iteration over a webassembly module's sections. * A section is wrapped in a section class. A section class instance allows you * append entries to a given section */ module.exports = class ModuleIterator { /** * param {Buffer} wasm - a webassembly binary */ constructor(wasm) { this._wasm = wasm; this._sections = []; this._modified = false; } /** * if the orignal wasm module was modified then this will return the modified * wasm module */ get wasm() { if (this._modified) { this._wasm = Buffer.concat(this._sections.concat(this._pipe.buffer)); this._modified = false; } return this._wasm; } /** * Iterates through the module's sections * return {Iterator.
} */ *[Symbol.iterator]() { this._pipe = new Pipe(this._wasm); this._sections = [this._pipe.read(8)]; while (!this._pipe.end) { const start = this._pipe.bytesRead; const sectionType = this._pipe.read(1)[0]; const size = Number(leb128.read(this._pipe)); const body = this._pipe.read(size); const end = this._pipe.bytesRead; const section = this._wasm.slice(start, end); const index = this._sections.push(section) - 1; yield new Section(sectionType, body, this, index); } } _update(index, data) { this._modified = true; this._sections[index] = data; } }; /** * The section class is always internal created by the Module class. And return * through the Module's iternator */ class Section { constructor(sectionType, section, it, index) { this._it = it; this._index = index; this.type = SECTIONS[sectionType]; this._type = sectionType; this._section = section; const pipe = new Pipe(section); if (this.type !== 'custom') { this.count = Number(leb128.read(pipe)); } this._body = pipe.buffer; } /** * Parses the section and return the JSON repesentation of it * returns {Object} */ toJSON() { return wasm2json.sectionParsers[this.type](new Pipe(this._section)); } /** * Appends an array of entries to this section. NOTE: this will modify the * parent wasm module. * @param {Arrayy.} entries */ appendEntries(entries) { this.count += entries.length; this._body = Buffer.concat([this._body].concat(entries)); const bodyAndCount = Buffer.concat([leb128.encode(this.count), this._body]); // encode length has save modifed section this._it._update( this._index, Buffer.concat([ Buffer.from([this._type]), leb128.encode(bodyAndCount.length), bodyAndCount, ]) ); } } /***/ }), /***/ 4747: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { const Buffer = (__webpack_require__(1415).Buffer); const leb = __webpack_require__(5548); const Stream = __webpack_require__(825); const OP_IMMEDIATES = __webpack_require__(8575); const _exports = (module.exports = (json) => { return _exports.generate(json).buffer; }); // https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#language-types // All types are distinguished by a negative varint7 values that is the first // byte of their encoding (representing a type constructor) const LANGUAGE_TYPES = (_exports.LANGUAGE_TYPES = { i32: 0x7f, i64: 0x7e, f32: 0x7d, f64: 0x7c, anyFunc: 0x70, func: 0x60, block_type: 0x40, }); // https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#external_kind // A single-byte unsigned integer indicating the kind of definition being imported or defined: const EXTERNAL_KIND = (_exports.EXTERNAL_KIND = { function: 0, table: 1, memory: 2, global: 3, }); const SECTION_IDS = (_exports.SECTION_IDS = { custom: 0, type: 1, import: 2, function: 3, table: 4, memory: 5, global: 6, export: 7, start: 8, element: 9, code: 10, data: 11, }); const OPCODES = (_exports.OPCODES = { unreachable: 0x0, nop: 0x1, block: 0x2, loop: 0x3, if: 0x4, else: 0x5, end: 0xb, br: 0xc, br_if: 0xd, br_table: 0xe, return: 0xf, call: 0x10, call_indirect: 0x11, drop: 0x1a, select: 0x1b, get_local: 0x20, set_local: 0x21, tee_local: 0x22, get_global: 0x23, set_global: 0x24, 'i32.load': 0x28, 'i64.load': 0x29, 'f32.load': 0x2a, 'f64.load': 0x2b, 'i32.load8_s': 0x2c, 'i32.load8_u': 0x2d, 'i32.load16_s': 0x2e, 'i32.load16_u': 0x2f, 'i64.load8_s': 0x30, 'i64.load8_u': 0x31, 'i64.load16_s': 0x32, 'i64.load16_u': 0x33, 'i64.load32_s': 0x34, 'i64.load32_u': 0x35, 'i32.store': 0x36, 'i64.store': 0x37, 'f32.store': 0x38, 'f64.store': 0x39, 'i32.store8': 0x3a, 'i32.store16': 0x3b, 'i64.store8': 0x3c, 'i64.store16': 0x3d, 'i64.store32': 0x3e, current_memory: 0x3f, grow_memory: 0x40, 'i32.const': 0x41, 'i64.const': 0x42, 'f32.const': 0x43, 'f64.const': 0x44, 'i32.eqz': 0x45, 'i32.eq': 0x46, 'i32.ne': 0x47, 'i32.lt_s': 0x48, 'i32.lt_u': 0x49, 'i32.gt_s': 0x4a, 'i32.gt_u': 0x4b, 'i32.le_s': 0x4c, 'i32.le_u': 0x4d, 'i32.ge_s': 0x4e, 'i32.ge_u': 0x4f, 'i64.eqz': 0x50, 'i64.eq': 0x51, 'i64.ne': 0x52, 'i64.lt_s': 0x53, 'i64.lt_u': 0x54, 'i64.gt_s': 0x55, 'i64.gt_u': 0x56, 'i64.le_s': 0x57, 'i64.le_u': 0x58, 'i64.ge_s': 0x59, 'i64.ge_u': 0x5a, 'f32.eq': 0x5b, 'f32.ne': 0x5c, 'f32.lt': 0x5d, 'f32.gt': 0x5e, 'f32.le': 0x5f, 'f32.ge': 0x60, 'f64.eq': 0x61, 'f64.ne': 0x62, 'f64.lt': 0x63, 'f64.gt': 0x64, 'f64.le': 0x65, 'f64.ge': 0x66, 'i32.clz': 0x67, 'i32.ctz': 0x68, 'i32.popcnt': 0x69, 'i32.add': 0x6a, 'i32.sub': 0x6b, 'i32.mul': 0x6c, 'i32.div_s': 0x6d, 'i32.div_u': 0x6e, 'i32.rem_s': 0x6f, 'i32.rem_u': 0x70, 'i32.and': 0x71, 'i32.or': 0x72, 'i32.xor': 0x73, 'i32.shl': 0x74, 'i32.shr_s': 0x75, 'i32.shr_u': 0x76, 'i32.rotl': 0x77, 'i32.rotr': 0x78, 'i64.clz': 0x79, 'i64.ctz': 0x7a, 'i64.popcnt': 0x7b, 'i64.add': 0x7c, 'i64.sub': 0x7d, 'i64.mul': 0x7e, 'i64.div_s': 0x7f, 'i64.div_u': 0x80, 'i64.rem_s': 0x81, 'i64.rem_u': 0x82, 'i64.and': 0x83, 'i64.or': 0x84, 'i64.xor': 0x85, 'i64.shl': 0x86, 'i64.shr_s': 0x87, 'i64.shr_u': 0x88, 'i64.rotl': 0x89, 'i64.rotr': 0x8a, 'f32.abs': 0x8b, 'f32.neg': 0x8c, 'f32.ceil': 0x8d, 'f32.floor': 0x8e, 'f32.trunc': 0x8f, 'f32.nearest': 0x90, 'f32.sqrt': 0x91, 'f32.add': 0x92, 'f32.sub': 0x93, 'f32.mul': 0x94, 'f32.div': 0x95, 'f32.min': 0x96, 'f32.max': 0x97, 'f32.copysign': 0x98, 'f64.abs': 0x99, 'f64.neg': 0x9a, 'f64.ceil': 0x9b, 'f64.floor': 0x9c, 'f64.trunc': 0x9d, 'f64.nearest': 0x9e, 'f64.sqrt': 0x9f, 'f64.add': 0xa0, 'f64.sub': 0xa1, 'f64.mul': 0xa2, 'f64.div': 0xa3, 'f64.min': 0xa4, 'f64.max': 0xa5, 'f64.copysign': 0xa6, 'i32.wrap/i64': 0xa7, 'i32.trunc_s/f32': 0xa8, 'i32.trunc_u/f32': 0xa9, 'i32.trunc_s/f64': 0xaa, 'i32.trunc_u/f64': 0xab, 'i64.extend_s/i32': 0xac, 'i64.extend_u/i32': 0xad, 'i64.trunc_s/f32': 0xae, 'i64.trunc_u/f32': 0xaf, 'i64.trunc_s/f64': 0xb0, 'i64.trunc_u/f64': 0xb1, 'f32.convert_s/i32': 0xb2, 'f32.convert_u/i32': 0xb3, 'f32.convert_s/i64': 0xb4, 'f32.convert_u/i64': 0xb5, 'f32.demote/f64': 0xb6, 'f64.convert_s/i32': 0xb7, 'f64.convert_u/i32': 0xb8, 'f64.convert_s/i64': 0xb9, 'f64.convert_u/i64': 0xba, 'f64.promote/f32': 0xbb, 'i32.reinterpret/f32': 0xbc, 'i64.reinterpret/f64': 0xbd, 'f32.reinterpret/i32': 0xbe, 'f64.reinterpret/i64': 0xbf, }); _exports.typeGenerators = { function: (json, stream) => { leb.unsigned.write(json, stream); }, table: (json, stream) => { stream.write([LANGUAGE_TYPES[json.elementType]]); _exports.typeGenerators.memory(json.limits, stream); }, /** * generates a [`global_type`](https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#global_type) */ global: (json, stream) => { stream.write([LANGUAGE_TYPES[json.contentType]]); stream.write([json.mutability]); }, /** * Generates a [resizable_limits](https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#resizable_limits) * @param {Object} json * @param {Stream} stream */ memory: (json, stream) => { leb.unsigned.write(Number(json.maximum !== undefined), stream); // the flags leb.unsigned.write(json.intial, stream); if (json.maximum !== undefined) { leb.unsigned.write(json.maximum, stream); } }, /** * Generates a [init_expr](https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#resizable_limits) * The encoding of an initializer expression is the normal encoding of the * expression followed by the end opcode as a delimiter. */ initExpr: (json, stream) => { _exports.generateOp(json, stream); _exports.generateOp({ name: 'end', type: 'void' }, stream); }, }; _exports.immediataryGenerators = { varuint1: (json, stream) => { stream.write([json]); return stream; }, varuint32: (json, stream) => { leb.unsigned.write(json, stream); return stream; }, varint32: (json, stream) => { leb.signed.write(json, stream); return stream; }, varint64: (json, stream) => { leb.signed.write(json, stream); return stream; }, uint32: (json, stream) => { stream.write(json); return stream; }, uint64: (json, stream) => { stream.write(json); return stream; }, block_type: (json, stream) => { stream.write([LANGUAGE_TYPES[json]]); return stream; }, br_table: (json, stream) => { leb.unsigned.write(json.targets.length, stream); for (let target of json.targets) { leb.unsigned.write(target, stream); } leb.unsigned.write(json.defaultTarget, stream); return stream; }, call_indirect: (json, stream) => { leb.unsigned.write(json.index, stream); stream.write([json.reserved]); return stream; }, memory_immediate: (json, stream) => { leb.unsigned.write(json.flags, stream); leb.unsigned.write(json.offset, stream); return stream; }, }; const entryGenerators = { type: (entry, stream = new Stream()) => { // a single type entry binary encoded stream.write([LANGUAGE_TYPES[entry.form]]); // the form const len = entry.params.length; // number of parameters leb.unsigned.write(len, stream); if (len !== 0) { stream.write(entry.params.map((type) => LANGUAGE_TYPES[type])); // the paramter types } stream.write([entry.return_type ? 1 : 0]); // number of return types if (entry.return_type) { stream.write([LANGUAGE_TYPES[entry.return_type]]); } return stream.buffer; }, import: (entry, stream = new Stream()) => { // write the module string leb.unsigned.write(entry.moduleStr.length, stream); stream.write(entry.moduleStr); // write the field string leb.unsigned.write(entry.fieldStr.length, stream); stream.write(entry.fieldStr); stream.write([EXTERNAL_KIND[entry.kind]]); _exports.typeGenerators[entry.kind](entry.type, stream); }, function: (entry, stream = new Stream()) => { leb.unsigned.write(entry, stream); return stream.buffer; }, table: _exports.typeGenerators.table, global: (entry, stream = new Stream()) => { _exports.typeGenerators.global(entry.type, stream); _exports.typeGenerators.initExpr(entry.init, stream); return stream; }, memory: _exports.typeGenerators.memory, export: (entry, stream = new Stream()) => { const fieldStr = Buffer.from(entry.field_str); const strLen = fieldStr.length; leb.unsigned.write(strLen, stream); stream.write(fieldStr); stream.write([EXTERNAL_KIND[entry.kind]]); leb.unsigned.write(entry.index, stream); return stream; }, element: (entry, stream = new Stream()) => { leb.unsigned.write(entry.index, stream); _exports.typeGenerators.initExpr(entry.offset, stream); leb.unsigned.write(entry.elements.length, stream); for (let elem of entry.elements) { leb.unsigned.write(elem, stream); } return stream; }, code: (entry, stream = new Stream()) => { let codeStream = new Stream(); // write the locals leb.unsigned.write(entry.locals.length, codeStream); for (let local of entry.locals) { leb.unsigned.write(local.count, codeStream); codeStream.write([LANGUAGE_TYPES[local.type]]); } // write opcode for (let op of entry.code) { _exports.generateOp(op, codeStream); } leb.unsigned.write(codeStream.bytesWrote, stream); stream.write(codeStream.buffer); return stream; }, data: (entry, stream = new Stream()) => { leb.unsigned.write(entry.index, stream); _exports.typeGenerators.initExpr(entry.offset, stream); leb.unsigned.write(entry.data.length, stream); stream.write(entry.data); return stream; }, }; _exports.entryGenerators = entryGenerators; _exports.generateSection = function (json, stream = new Stream()) { const name = json.name; const payload = new Stream(); stream.write([SECTION_IDS[name]]); if (name === 'custom') { leb.unsigned.write(json.sectionName.length, payload); payload.write(json.sectionName); payload.write(json.payload); } else if (name === 'start') { leb.unsigned.write(json.index, payload); } else { leb.unsigned.write(json.entries.length, payload); for (let entry of json.entries) { entryGenerators[name](entry, payload); } } // write the size of the payload leb.unsigned.write(payload.bytesWrote, stream); stream.write(payload.buffer); return stream; }; _exports.generate = (json, stream = new Stream()) => { const [preamble, ...rest] = json; _exports.generatePreramble(preamble, stream); for (let item of rest) { _exports.generateSection(item, stream); } return stream; }; _exports.generatePreramble = (json, stream = new Stream()) => { stream.write(json.magic); stream.write(json.version); return stream; }; _exports.generateOp = (json, stream = new Stream()) => { let name = json.name; if (json.return_type !== undefined) { name = json.return_type + '.' + name; } stream.write([OPCODES[name]]); const immediates = OP_IMMEDIATES[json.name === 'const' ? json.return_type : json.name]; if (immediates) { _exports.immediataryGenerators[immediates](json.immediates, stream); } return stream; }; /***/ }), /***/ 825: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { const Buffer = (__webpack_require__(9509).Buffer) module.exports = class BufferPipe { /** * Creates a new instance of a pipe * @param {Buffer} buf - an optional buffer to start with */ constructor (buf = Buffer.from([])) { this.buffer = buf this._bytesRead = 0 this._bytesWrote = 0 } /** * read `num` number of bytes from the pipe * @param {Number} num * @return {Buffer} */ read (num) { this._bytesRead += num const data = this.buffer.slice(0, num) this.buffer = this.buffer.slice(num) return data } /** * Wites a buffer to the pipe * @param {Buffer} buf */ write (buf) { buf = Buffer.from(buf) this._bytesWrote += buf.length this.buffer = Buffer.concat([this.buffer, buf]) } /** * Whether or not there is more data to read from the buffer * returns {Boolean} */ get end () { return !this.buffer.length } /** * returns the number of bytes read from the stream * @return {Integer} */ get bytesRead () { return this._bytesRead } /** * returns the number of bytes wrote to the stream * @return {Integer} */ get bytesWrote () { return this._bytesWrote } } /***/ }), /***/ 1415: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { __webpack_require__.g.fetch = window.fetch; /* unused reexport */ __webpack_require__(8764).Buffer; /***/ }), /***/ 9837: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { const immediates = __webpack_require__(8575) module.exports = (text) => { const json = [] const textArray = text.split(/\s|\n/) while (textArray.length) { const textOp = textArray.shift() const jsonOp = {} let [type, name] = textOp.split('.') if (name === undefined) { name = type } else { jsonOp.return_type = type } jsonOp.name = name const immediate = immediates[jsonOp.name === 'const' ? jsonOp.return_type : jsonOp.name] if (immediate) { jsonOp.immediates = immediataryParser(immediate, textArray) } json.push(jsonOp) } return json } function immediataryParser (type, txt) { const json = {} switch (type) { case 'br_table': const dests = [] while (1) { let dest = txt[0] if (isNaN(dest)) break txt.shift() dests.push(dest) } return dests case 'call_indirect': json.index = txt.shift() json.reserved = 0 return json case 'memory_immediate': json.flags = txt.shift() json.offset = txt.shift() return json default: return txt.shift() } } /***/ }), /***/ 3195: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /* provided dependency */ var Buffer = __webpack_require__(8764)["Buffer"]; const leb = __webpack_require__(5548) const Stream = __webpack_require__(825) const OP_IMMEDIATES = __webpack_require__(8575) const _exports = module.exports = (buf, filter) => { const stream = new Stream(buf) return _exports.parse(stream, filter) } // https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#language-types // All types are distinguished by a negative varint7 values that is the first // byte of their encoding (representing a type constructor) const LANGUAGE_TYPES = _exports.LANGUAGE_TYPES = { 0x7f: 'i32', 0x7e: 'i64', 0x7d: 'f32', 0x7c: 'f64', 0x70: 'anyFunc', 0x60: 'func', 0x40: 'block_type' } // https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#external_kind // A single-byte unsigned integer indicating the kind of definition being imported or defined: const EXTERNAL_KIND = _exports.EXTERNAL_KIND = { 0: 'function', 1: 'table', 2: 'memory', 3: 'global' } _exports.parsePreramble = (stream) => { const obj = {} obj.name = 'preramble' obj.magic = [...stream.read(4)] obj.version = [...stream.read(4)] return obj } _exports.parseSectionHeader = (stream) => { const id = stream.read(1)[0] const size = leb.unsigned.readBn(stream).toNumber() return { id, name: SECTION_IDS[id], size } } const OPCODES = _exports.OPCODES = { // flow control 0x0: 'unreachable', 0x1: 'nop', 0x2: 'block', 0x3: 'loop', 0x4: 'if', 0x5: 'else', 0xb: 'end', 0xc: 'br', 0xd: 'br_if', 0xe: 'br_table', 0xf: 'return', // calls 0x10: 'call', 0x11: 'call_indirect', // Parametric operators 0x1a: 'drop', 0x1b: 'select', // Varibale access 0x20: 'get_local', 0x21: 'set_local', 0x22: 'tee_local', 0x23: 'get_global', 0x24: 'set_global', // Memory-related operators 0x28: 'i32.load', 0x29: 'i64.load', 0x2a: 'f32.load', 0x2b: 'f64.load', 0x2c: 'i32.load8_s', 0x2d: 'i32.load8_u', 0x2e: 'i32.load16_s', 0x2f: 'i32.load16_u', 0x30: 'i64.load8_s', 0x31: 'i64.load8_u', 0x32: 'i64.load16_s', 0x33: 'i64.load16_u', 0x34: 'i64.load32_s', 0x35: 'i64.load32_u', 0x36: 'i32.store', 0x37: 'i64.store', 0x38: 'f32.store', 0x39: 'f64.store', 0x3a: 'i32.store8', 0x3b: 'i32.store16', 0x3c: 'i64.store8', 0x3d: 'i64.store16', 0x3e: 'i64.store32', 0x3f: 'current_memory', 0x40: 'grow_memory', // Constants 0x41: 'i32.const', 0x42: 'i64.const', 0x43: 'f32.const', 0x44: 'f64.const', // Comparison operators 0x45: 'i32.eqz', 0x46: 'i32.eq', 0x47: 'i32.ne', 0x48: 'i32.lt_s', 0x49: 'i32.lt_u', 0x4a: 'i32.gt_s', 0x4b: 'i32.gt_u', 0x4c: 'i32.le_s', 0x4d: 'i32.le_u', 0x4e: 'i32.ge_s', 0x4f: 'i32.ge_u', 0x50: 'i64.eqz', 0x51: 'i64.eq', 0x52: 'i64.ne', 0x53: 'i64.lt_s', 0x54: 'i64.lt_u', 0x55: 'i64.gt_s', 0x56: 'i64.gt_u', 0x57: 'i64.le_s', 0x58: 'i64.le_u', 0x59: 'i64.ge_s', 0x5a: 'i64.ge_u', 0x5b: 'f32.eq', 0x5c: 'f32.ne', 0x5d: 'f32.lt', 0x5e: 'f32.gt', 0x5f: 'f32.le', 0x60: 'f32.ge', 0x61: 'f64.eq', 0x62: 'f64.ne', 0x63: 'f64.lt', 0x64: 'f64.gt', 0x65: 'f64.le', 0x66: 'f64.ge', // Numeric operators 0x67: 'i32.clz', 0x68: 'i32.ctz', 0x69: 'i32.popcnt', 0x6a: 'i32.add', 0x6b: 'i32.sub', 0x6c: 'i32.mul', 0x6d: 'i32.div_s', 0x6e: 'i32.div_u', 0x6f: 'i32.rem_s', 0x70: 'i32.rem_u', 0x71: 'i32.and', 0x72: 'i32.or', 0x73: 'i32.xor', 0x74: 'i32.shl', 0x75: 'i32.shr_s', 0x76: 'i32.shr_u', 0x77: 'i32.rotl', 0x78: 'i32.rotr', 0x79: 'i64.clz', 0x7a: 'i64.ctz', 0x7b: 'i64.popcnt', 0x7c: 'i64.add', 0x7d: 'i64.sub', 0x7e: 'i64.mul', 0x7f: 'i64.div_s', 0x80: 'i64.div_u', 0x81: 'i64.rem_s', 0x82: 'i64.rem_u', 0x83: 'i64.and', 0x84: 'i64.or', 0x85: 'i64.xor', 0x86: 'i64.shl', 0x87: 'i64.shr_s', 0x88: 'i64.shr_u', 0x89: 'i64.rotl', 0x8a: 'i64.rotr', 0x8b: 'f32.abs', 0x8c: 'f32.neg', 0x8d: 'f32.ceil', 0x8e: 'f32.floor', 0x8f: 'f32.trunc', 0x90: 'f32.nearest', 0x91: 'f32.sqrt', 0x92: 'f32.add', 0x93: 'f32.sub', 0x94: 'f32.mul', 0x95: 'f32.div', 0x96: 'f32.min', 0x97: 'f32.max', 0x98: 'f32.copysign', 0x99: 'f64.abs', 0x9a: 'f64.neg', 0x9b: 'f64.ceil', 0x9c: 'f64.floor', 0x9d: 'f64.trunc', 0x9e: 'f64.nearest', 0x9f: 'f64.sqrt', 0xa0: 'f64.add', 0xa1: 'f64.sub', 0xa2: 'f64.mul', 0xa3: 'f64.div', 0xa4: 'f64.min', 0xa5: 'f64.max', 0xa6: 'f64.copysign', // Conversions 0xa7: 'i32.wrap/i64', 0xa8: 'i32.trunc_s/f32', 0xa9: 'i32.trunc_u/f32', 0xaa: 'i32.trunc_s/f64', 0xab: 'i32.trunc_u/f64', 0xac: 'i64.extend_s/i32', 0xad: 'i64.extend_u/i32', 0xae: 'i64.trunc_s/f32', 0xaf: 'i64.trunc_u/f32', 0xb0: 'i64.trunc_s/f64', 0xb1: 'i64.trunc_u/f64', 0xb2: 'f32.convert_s/i32', 0xb3: 'f32.convert_u/i32', 0xb4: 'f32.convert_s/i64', 0xb5: 'f32.convert_u/i64', 0xb6: 'f32.demote/f64', 0xb7: 'f64.convert_s/i32', 0xb8: 'f64.convert_u/i32', 0xb9: 'f64.convert_s/i64', 0xba: 'f64.convert_u/i64', 0xbb: 'f64.promote/f32', // Reinterpretations 0xbc: 'i32.reinterpret/f32', 0xbd: 'i64.reinterpret/f64', 0xbe: 'f32.reinterpret/i32', 0xbf: 'f64.reinterpret/i64' } const SECTION_IDS = _exports.SECTION_IDS = { 0: 'custom', 1: 'type', 2: 'import', 3: 'function', 4: 'table', 5: 'memory', 6: 'global', 7: 'export', 8: 'start', 9: 'element', 10: 'code', 11: 'data' } _exports.immediataryParsers = { 'varuint1': (stream) => { const int1 = stream.read(1)[0] return int1 }, 'varuint32': (stream) => { const int32 = leb.unsigned.read(stream) return int32 }, 'varint32': (stream) => { const int32 = leb.signed.read(stream) return int32 }, 'varint64': (stream) => { const int64 = leb.signed.read(stream) return int64 }, 'uint32': (stream) => { return [...stream.read(4)] }, 'uint64': (stream) => { return [...stream.read(8)] }, 'block_type': (stream) => { const type = stream.read(1)[0] return LANGUAGE_TYPES[type] }, 'br_table': (stream) => { const json = { targets: [] } const num = leb.unsigned.readBn(stream).toNumber() for (let i = 0; i < num; i++) { const target = leb.unsigned.readBn(stream).toNumber() json.targets.push(target) } json.defaultTarget = leb.unsigned.readBn(stream).toNumber() return json }, 'call_indirect': (stream) => { const json = {} json.index = leb.unsigned.readBn(stream).toNumber() json.reserved = stream.read(1)[0] return json }, 'memory_immediate': (stream) => { const json = {} json.flags = leb.unsigned.readBn(stream).toNumber() json.offset = leb.unsigned.readBn(stream).toNumber() return json } } _exports.typeParsers = { 'function': (stream) => { return leb.unsigned.readBn(stream).toNumber() }, table: (stream) => { const entry = {} const type = stream.read(1)[0] // read single byte entry.elementType = LANGUAGE_TYPES[type] entry.limits = _exports.typeParsers.memory(stream) return entry }, /** * parses a [`global_type`](https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#global_type) * @param {Stream} stream * @return {Object} */ global: (stream) => { const global = {} let type = stream.read(1)[0] global.contentType = LANGUAGE_TYPES[type] global.mutability = stream.read(1)[0] return global }, /** * Parses a [resizable_limits](https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#resizable_limits) * @param {Stream} stream * return {Object} */ memory: (stream) => { const limits = {} limits.flags = leb.unsigned.readBn(stream).toNumber() limits.intial = leb.unsigned.readBn(stream).toNumber() if (limits.flags === 1) { limits.maximum = leb.unsigned.readBn(stream).toNumber() } return limits }, /** * Parses a [init_expr](https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#resizable_limits) * The encoding of an initializer expression is the normal encoding of the * expression followed by the end opcode as a delimiter. */ initExpr: (stream) => { const op = _exports.parseOp(stream) stream.read(1) // skip the `end` return op } } const sectionParsers = _exports.sectionParsers = { 'custom': (stream, header) => { const json = { name: 'custom' } const section = new Stream(stream.read(header.size)) const nameLen = leb.unsigned.readBn(section).toNumber() const name = section.read(nameLen) json.sectionName = Buffer.from(name).toString() json.payload = [...section.buffer] return json }, 'type': (stream) => { const numberOfEntries = leb.unsigned.readBn(stream).toNumber() const json = { name: 'type', entries: [] } for (let i = 0; i < numberOfEntries; i++) { let type = stream.read(1)[0] const entry = { form: LANGUAGE_TYPES[type], params: [] } const paramCount = leb.unsigned.readBn(stream).toNumber() // parse the entries for (let q = 0; q < paramCount; q++) { const type = stream.read(1)[0] entry.params.push(LANGUAGE_TYPES[type]) } const numOfReturns = leb.unsigned.readBn(stream).toNumber() if (numOfReturns) { type = stream.read(1)[0] entry.return_type = LANGUAGE_TYPES[type] } json.entries.push(entry) } return json }, 'import': (stream) => { const numberOfEntries = leb.unsigned.readBn(stream).toNumber() const json = { name: 'import', entries: [] } for (let i = 0; i < numberOfEntries; i++) { const entry = {} const moduleLen = leb.unsigned.readBn(stream).toNumber() entry.moduleStr = Buffer.from(stream.read(moduleLen)).toString() const fieldLen = leb.unsigned.readBn(stream).toNumber() entry.fieldStr = Buffer.from(stream.read(fieldLen)).toString() const kind = stream.read(1)[0] // read single byte entry.kind = EXTERNAL_KIND[kind] entry.type = _exports.typeParsers[entry.kind](stream) json.entries.push(entry) } return json }, 'function': (stream) => { const numberOfEntries = leb.unsigned.readBn(stream).toNumber() const json = { name: 'function', entries: [] } for (let i = 0; i < numberOfEntries; i++) { const entry = leb.unsigned.readBn(stream).toNumber() json.entries.push(entry) } return json }, 'table': (stream) => { const numberOfEntries = leb.unsigned.readBn(stream).toNumber() const json = { name: 'table', entries: [] } // parse table_type for (let i = 0; i < numberOfEntries; i++) { const entry = _exports.typeParsers.table(stream) json.entries.push(entry) } return json }, 'memory': (stream) => { const numberOfEntries = leb.unsigned.readBn(stream).toNumber() const json = { name: 'memory', entries: [] } for (let i = 0; i < numberOfEntries; i++) { const entry = _exports.typeParsers.memory(stream) json.entries.push(entry) } return json }, 'global': (stream) => { const numberOfEntries = leb.unsigned.readBn(stream).toNumber() const json = { name: 'global', entries: [] } for (let i = 0; i < numberOfEntries; i++) { const entry = {} entry.type = _exports.typeParsers.global(stream) entry.init = _exports.typeParsers.initExpr(stream) json.entries.push(entry) } return json }, 'export': (stream) => { const numberOfEntries = leb.unsigned.readBn(stream).toNumber() const json = { name: 'export', entries: [] } for (let i = 0; i < numberOfEntries; i++) { const strLength = leb.unsigned.readBn(stream).toNumber() const entry = {} entry.field_str = Buffer.from(stream.read(strLength)).toString() const kind = stream.read(1)[0] entry.kind = EXTERNAL_KIND[kind] entry.index = leb.unsigned.readBn(stream).toNumber() json.entries.push(entry) } return json }, 'start': (stream) => { const json = { name: 'start' } json.index = leb.unsigned.readBn(stream).toNumber() return json }, 'element': (stream) => { const numberOfEntries = leb.unsigned.readBn(stream).toNumber() const json = { name: 'element', entries: [] } for (let i = 0; i < numberOfEntries; i++) { const entry = { elements: [] } entry.index = leb.unsigned.readBn(stream).toNumber() entry.offset = _exports.typeParsers.initExpr(stream) const numElem = leb.unsigned.readBn(stream).toNumber() for (let i = 0; i < numElem; i++) { const elem = leb.unsigned.readBn(stream).toNumber() entry.elements.push(elem) } json.entries.push(entry) } return json }, 'code': (stream) => { const numberOfEntries = leb.unsigned.readBn(stream).toNumber() const json = { name: 'code', entries: [] } for (let i = 0; i < numberOfEntries; i++) { const codeBody = { locals: [], code: [] } let bodySize = leb.unsigned.readBn(stream).toNumber() const endBytes = stream.bytesRead + bodySize // parse locals const localCount = leb.unsigned.readBn(stream).toNumber() for (let q = 0; q < localCount; q++) { const local = {} local.count = leb.unsigned.readBn(stream).toNumber() const type = stream.read(1)[0] local.type = LANGUAGE_TYPES[type] codeBody.locals.push(local) } // parse code while (stream.bytesRead < endBytes) { const op = _exports.parseOp(stream) codeBody.code.push(op) } json.entries.push(codeBody) } return json }, 'data': (stream) => { const numberOfEntries = leb.unsigned.readBn(stream).toNumber() const json = { name: 'data', entries: [] } for (let i = 0; i < numberOfEntries; i++) { const entry = {} entry.index = leb.unsigned.readBn(stream).toNumber() entry.offset = _exports.typeParsers.initExpr(stream) const segmentSize = leb.unsigned.readBn(stream).toNumber() entry.data = [...stream.read(segmentSize)] json.entries.push(entry) } return json } } _exports.parseOp = (stream) => { const json = {} const op = stream.read(1)[0] const fullName = OPCODES[op] let [type, name] = fullName.split('.') if (name === undefined) { name = type } else { json.return_type = type } json.name = name const immediates = OP_IMMEDIATES[name === 'const' ? type : name] if (immediates) { json.immediates = _exports.immediataryParsers[immediates](stream) } return json } _exports.parse = (stream, filter) => { const preramble = _exports.parsePreramble(stream) const json = [preramble] while (!stream.end) { const header = _exports.parseSectionHeader(stream) json.push(sectionParsers[header.name](stream, header)) } return json } /***/ }), /***/ 8060: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { const toolkit = __webpack_require__(497); const text2json = toolkit.text2json; const SECTION_IDS = (__webpack_require__(4747).SECTION_IDS); const defaultCostTable = __webpack_require__(5936); // gets the cost of an operation for entry in a section from the cost table function getCost(json, costTable = {}, defaultCost = 0) { let cost = 0; // finds the default cost defaultCost = costTable['DEFAULT'] !== undefined ? costTable['DEFAULT'] : 0; if (Array.isArray(json)) { json.forEach((el) => { cost += getCost(el, costTable); }); } else if (typeof json === 'object') { for (const propName in json) { const propCost = costTable[propName]; if (propCost) { cost += getCost(json[propName], propCost, defaultCost); } } } else if (costTable[json] === undefined) { cost = defaultCost; } else { cost = costTable[json]; } return cost; } // meters a single code entrie function meterCodeEntry(entry, costTable, meterFuncIndex, meterType, cost) { function meteringStatement(cost, meteringImportIndex) { return text2json(`${meterType}.const ${cost} call ${meteringImportIndex}`); } function remapOp(op, funcIndex) { if (op.name === 'call' && op.immediates >= funcIndex) { op.immediates = (++op.immediates).toString(); } } function meterTheMeteringStatement() { const code = meteringStatement(0, 0); // sum the operations cost return code.reduce((sum, op) => sum + getCost(op.name, costTable.code), 0); } // operations that can possible cause a branch const branchingOps = new Set([ 'grow_memory', 'end', 'br', 'br_table', 'br_if', 'if', 'else', 'return', 'loop', ]); const meteringOverHead = meterTheMeteringStatement(); let code = entry.code.slice(); let meteredCode = []; cost += getCost(entry.locals, costTable.local); while (code.length) { let i = 0; // meters a segment of wasm code while (true) { const op = code[i++]; remapOp(op, meterFuncIndex); cost += getCost(op.name, costTable.code); if (branchingOps.has(op.name)) { break; } } // add the metering statement if (cost !== 0) { // add the cost of metering cost += meteringOverHead; meteredCode = meteredCode.concat(meteringStatement(cost, meterFuncIndex)); } // start a new segment meteredCode = meteredCode.concat(code.slice(0, i)); code = code.slice(i); cost = 0; } entry.code = meteredCode; return entry; } /** * Injects metering into a JSON output of [wasm2json](https://github.com/ewasm/wasm-json-toolkit#wasm2json) * @param {Object} json the json tobe metered * @param {Object} opts * @param {Object} [opts.costTable=defaultTable] the cost table to meter with. See these notes about the default. * @param {String} [opts.moduleStr='metering'] the import string for the metering function * @param {String} [opts.fieldStr='usegas'] the field string for the metering function * @param {String} [opts.meterType='i64'] the register type that is used to meter. Can be `i64`, `i32`, `f64`, `f32` * @return {Object} the metered json */ exports.meterJSON = (json, opts) => { function findSection(module, sectionName) { return module.find((section) => section.name === sectionName); } function createSection(module, name) { const newSectionId = SECTION_IDS[name]; for (let index in module) { const section = module[index]; const sectionId = SECTION_IDS[section.name]; if (sectionId) { if (newSectionId < sectionId) { // inject a new section module.splice(index, 0, { name, entries: [], }); return; } } } } let funcIndex = 0; let functionModule, typeModule; let { costTable, moduleStr, fieldStr, meterType } = opts; // set defaults if (!costTable) costTable = defaultCostTable; if (!moduleStr) moduleStr = 'metering'; if (!fieldStr) fieldStr = 'usegas'; if (!meterType) meterType = 'i32'; // add nessicarry sections iff they don't exist if (!findSection(json, 'type')) createSection(json, 'type'); if (!findSection(json, 'import')) createSection(json, 'import'); const importJson = { moduleStr: moduleStr, fieldStr: fieldStr, kind: 'function', }; const importType = { form: 'func', params: [meterType], }; json = json.slice(0); for (let section of json) { section = Object.assign(section); switch (section.name) { case 'type': // mark the import index importJson.type = section.entries.push(importType) - 1; // save for use for the code section typeModule = section; break; case 'function': // save for use for the code section functionModule = section; break; case 'import': for (const entry of section.entries) { if (entry.moduleStr === moduleStr && entry.fieldStr === fieldStr) { throw new Error('importing metering function is not allowed'); } if (entry.kind === 'function') { funcIndex++; } } // append the metering import section.entries.push(importJson); break; case 'export': for (const entry of section.entries) { if (entry.kind === 'function' && entry.index >= funcIndex) { entry.index++; } } break; case 'element': for (const entry of section.entries) { // remap elements indices entry.elements = entry.elements.map((el) => el >= funcIndex ? ++el : el ); } break; case 'start': // remap start index if (section.index >= funcIndex) section.index++; break; case 'code': for (const i in section.entries) { const entry = section.entries[i]; const typeIndex = functionModule.entries[i]; const type = typeModule.entries[typeIndex]; const cost = getCost(type, costTable.type); meterCodeEntry(entry, costTable.code, funcIndex, meterType, cost); } break; } } return json; }; /** * Injects metering into a webassembly binary * @param {Object} json the json tobe metered * @param {Object} opts * @param {Object} [opts.costTable=defaultTable] the cost table to meter with. See these notes about the default. * @param {String} [opts.moduleStr='metering'] the import string for the metering function * @param {String} [opts.fieldStr='usegas'] the field string for the metering function * @param {String} [opts.meterType='i64'] the register type that is used to meter. Can be `i64`, `i32`, `f64`, `f32` * @return {Buffer} */ exports.meterWASM = (wasm, opts = {}) => { let json = toolkit.wasm2json(wasm); json = exports.meterJSON(json, opts); return toolkit.json2wasm(json); }; /***/ }), /***/ 9967: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /*! run-parallel-limit. MIT License. Feross Aboukhadijeh */ module.exports = runParallelLimit const queueMicrotask = __webpack_require__(4375) function runParallelLimit (tasks, limit, cb) { if (typeof limit !== 'number') throw new Error('second argument must be a Number') let results, len, pending, keys, isErrored let isSync = true let next if (Array.isArray(tasks)) { results = [] pending = len = tasks.length } else { keys = Object.keys(tasks) results = {} pending = len = keys.length } function done (err) { function end () { if (cb) cb(err, results) cb = null } if (isSync) queueMicrotask(end) else end() } function each (i, err, result) { results[i] = result if (err) isErrored = true if (--pending === 0 || err) { done(err) } else if (!isErrored && next < len) { let key if (keys) { key = keys[next] next += 1 tasks[key](function (err, result) { each(key, err, result) }) } else { key = next next += 1 tasks[key](function (err, result) { each(key, err, result) }) } } } next = limit if (!pending) { // empty done(null) } else if (keys) { // object keys.some(function (key, i) { tasks[key](function (err, result) { each(key, err, result) }) if (i === limit - 1) return true // early return return false }) } else { // array tasks.some(function (task, i) { task(function (err, result) { each(i, err, result) }) if (i === limit - 1) return true // early return return false }) } isSync = false } /***/ }), /***/ 9509: /***/ (function(module, exports, __webpack_require__) { /*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = __webpack_require__(8764) var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } SafeBuffer.prototype = Object.create(Buffer.prototype) // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } /***/ }), /***/ 7668: /***/ (function(module, exports) { "use strict"; const stringify = configure() // @ts-expect-error stringify.configure = configure // @ts-expect-error stringify.stringify = stringify // @ts-expect-error stringify.default = stringify // @ts-expect-error used for named export exports.stringify = stringify // @ts-expect-error used for named export exports.configure = configure module.exports = stringify // eslint-disable-next-line const strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/ // eslint-disable-next-line const strEscapeSequencesReplacer = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/g // Escaped special characters. Use empty strings to fill up unused entries. const meta = [ '\\u0000', '\\u0001', '\\u0002', '\\u0003', '\\u0004', '\\u0005', '\\u0006', '\\u0007', '\\b', '\\t', '\\n', '\\u000b', '\\f', '\\r', '\\u000e', '\\u000f', '\\u0010', '\\u0011', '\\u0012', '\\u0013', '\\u0014', '\\u0015', '\\u0016', '\\u0017', '\\u0018', '\\u0019', '\\u001a', '\\u001b', '\\u001c', '\\u001d', '\\u001e', '\\u001f', '', '', '\\"', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '\\\\' ] function escapeFn (str) { if (str.length === 2) { const charCode = str.charCodeAt(1) return `${str[0]}\\u${charCode.toString(16)}` } const charCode = str.charCodeAt(0) return meta.length > charCode ? meta[charCode] : `\\u${charCode.toString(16)}` } // Escape C0 control characters, double quotes, the backslash and every code // unit with a numeric value in the inclusive range 0xD800 to 0xDFFF. function strEscape (str) { // Some magic numbers that worked out fine while benchmarking with v8 8.0 if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) { return str } if (str.length > 100) { return str.replace(strEscapeSequencesReplacer, escapeFn) } let result = '' let last = 0 for (let i = 0; i < str.length; i++) { const point = str.charCodeAt(i) if (point === 34 || point === 92 || point < 32) { result += `${str.slice(last, i)}${meta[point]}` last = i + 1 } else if (point >= 0xd800 && point <= 0xdfff) { if (point <= 0xdbff && i + 1 < str.length) { const point = str.charCodeAt(i + 1) if (point >= 0xdc00 && point <= 0xdfff) { i++ continue } } result += `${str.slice(last, i)}${`\\u${point.toString(16)}`}` last = i + 1 } } result += str.slice(last) return result } function insertSort (array) { // Insertion sort is very efficient for small input sizes but it has a bad // worst case complexity. Thus, use native array sort for bigger values. if (array.length > 2e2) { return array.sort() } for (let i = 1; i < array.length; i++) { const currentValue = array[i] let position = i while (position !== 0 && array[position - 1] > currentValue) { array[position] = array[position - 1] position-- } array[position] = currentValue } return array } const typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor( Object.getPrototypeOf( Object.getPrototypeOf( new Uint8Array() ) ), Symbol.toStringTag ).get function isTypedArrayWithEntries (value) { return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0 } function stringifyTypedArray (array, separator, maximumBreadth) { if (array.length < maximumBreadth) { maximumBreadth = array.length } const whitespace = separator === ',' ? '' : ' ' let res = `"0":${whitespace}${array[0]}` for (let i = 1; i < maximumBreadth; i++) { res += `${separator}"${i}":${whitespace}${array[i]}` } return res } function getCircularValueOption (options) { if (options && Object.prototype.hasOwnProperty.call(options, 'circularValue')) { var circularValue = options.circularValue if (typeof circularValue === 'string') { return `"${circularValue}"` } if (circularValue == null) { return circularValue } if (circularValue === Error || circularValue === TypeError) { return { toString () { throw new TypeError('Converting circular structure to JSON') } } } throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined') } return '"[Circular]"' } function getBooleanOption (options, key) { if (options && Object.prototype.hasOwnProperty.call(options, key)) { var value = options[key] if (typeof value !== 'boolean') { throw new TypeError(`The "${key}" argument must be of type boolean`) } } return value === undefined ? true : value } function getPositiveIntegerOption (options, key) { if (options && Object.prototype.hasOwnProperty.call(options, key)) { var value = options[key] if (typeof value !== 'number') { throw new TypeError(`The "${key}" argument must be of type number`) } if (!Number.isInteger(value)) { throw new TypeError(`The "${key}" argument must be an integer`) } if (value < 1) { throw new RangeError(`The "${key}" argument must be >= 1`) } } return value === undefined ? Infinity : value } function getItemCount (number) { if (number === 1) { return '1 item' } return `${number} items` } function getUniqueReplacerSet (replacerArray) { const replacerSet = new Set() for (const value of replacerArray) { if (typeof value === 'string') { replacerSet.add(value) } else if (typeof value === 'number') { replacerSet.add(String(value)) } } return replacerSet } function configure (options) { const circularValue = getCircularValueOption(options) const bigint = getBooleanOption(options, 'bigint') const deterministic = getBooleanOption(options, 'deterministic') const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth') const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth') function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) { let value = parent[key] if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') { value = value.toJSON(key) } value = replacer.call(parent, key, value) switch (typeof value) { case 'string': return `"${strEscape(value)}"` case 'object': { if (value === null) { return 'null' } if (stack.indexOf(value) !== -1) { return circularValue } let res = '' let join = ',' const originalIndentation = indentation if (Array.isArray(value)) { if (value.length === 0) { return '[]' } if (maximumDepth < stack.length + 1) { return '"[Array]"' } stack.push(value) if (spacer !== '') { indentation += spacer res += `\n${indentation}` join = `,\n${indentation}` } const maximumValuesToStringify = Math.min(value.length, maximumBreadth) let i = 0 for (; i < maximumValuesToStringify - 1; i++) { const tmp = stringifyFnReplacer(i, value, stack, replacer, spacer, indentation) res += tmp !== undefined ? tmp : 'null' res += join } const tmp = stringifyFnReplacer(i, value, stack, replacer, spacer, indentation) res += tmp !== undefined ? tmp : 'null' if (value.length - 1 > maximumBreadth) { const removedKeys = value.length - maximumBreadth - 1 res += `${join}"... ${getItemCount(removedKeys)} not stringified"` } if (spacer !== '') { res += `\n${originalIndentation}` } stack.pop() return `[${res}]` } let keys = Object.keys(value) const keyLength = keys.length if (keyLength === 0) { return '{}' } if (maximumDepth < stack.length + 1) { return '"[Object]"' } let whitespace = '' let separator = '' if (spacer !== '') { indentation += spacer join = `,\n${indentation}` whitespace = ' ' } let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth) if (isTypedArrayWithEntries(value)) { res += stringifyTypedArray(value, join, maximumBreadth) keys = keys.slice(value.length) maximumPropertiesToStringify -= value.length separator = join } if (deterministic) { keys = insertSort(keys) } stack.push(value) for (let i = 0; i < maximumPropertiesToStringify; i++) { const key = keys[i] const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation) if (tmp !== undefined) { res += `${separator}"${strEscape(key)}":${whitespace}${tmp}` separator = join } } if (keyLength > maximumBreadth) { const removedKeys = keyLength - maximumBreadth res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"` separator = join } if (spacer !== '' && separator.length > 1) { res = `\n${indentation}${res}\n${originalIndentation}` } stack.pop() return `{${res}}` } case 'number': return isFinite(value) ? String(value) : 'null' case 'boolean': return value === true ? 'true' : 'false' case 'bigint': return bigint ? String(value) : undefined } } function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) { if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') { value = value.toJSON(key) } switch (typeof value) { case 'string': return `"${strEscape(value)}"` case 'object': { if (value === null) { return 'null' } if (stack.indexOf(value) !== -1) { return circularValue } const originalIndentation = indentation let res = '' let join = ',' if (Array.isArray(value)) { if (value.length === 0) { return '[]' } if (maximumDepth < stack.length + 1) { return '"[Array]"' } stack.push(value) if (spacer !== '') { indentation += spacer res += `\n${indentation}` join = `,\n${indentation}` } const maximumValuesToStringify = Math.min(value.length, maximumBreadth) let i = 0 for (; i < maximumValuesToStringify - 1; i++) { const tmp = stringifyArrayReplacer(i, value[i], stack, replacer, spacer, indentation) res += tmp !== undefined ? tmp : 'null' res += join } const tmp = stringifyArrayReplacer(i, value[i], stack, replacer, spacer, indentation) res += tmp !== undefined ? tmp : 'null' if (value.length - 1 > maximumBreadth) { const removedKeys = value.length - maximumBreadth - 1 res += `${join}"... ${getItemCount(removedKeys)} not stringified"` } if (spacer !== '') { res += `\n${originalIndentation}` } stack.pop() return `[${res}]` } if (replacer.size === 0) { return '{}' } stack.push(value) let whitespace = '' if (spacer !== '') { indentation += spacer join = `,\n${indentation}` whitespace = ' ' } let separator = '' for (const key of replacer) { const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation) if (tmp !== undefined) { res += `${separator}"${strEscape(key)}":${whitespace}${tmp}` separator = join } } if (spacer !== '' && separator.length > 1) { res = `\n${indentation}${res}\n${originalIndentation}` } stack.pop() return `{${res}}` } case 'number': return isFinite(value) ? String(value) : 'null' case 'boolean': return value === true ? 'true' : 'false' case 'bigint': return bigint ? String(value) : undefined } } function stringifyIndent (key, value, stack, spacer, indentation) { switch (typeof value) { case 'string': return `"${strEscape(value)}"` case 'object': { if (value === null) { return 'null' } if (typeof value.toJSON === 'function') { value = value.toJSON(key) // Prevent calling `toJSON` again. if (typeof value !== 'object') { return stringifyIndent(key, value, stack, spacer, indentation) } if (value === null) { return 'null' } } if (stack.indexOf(value) !== -1) { return circularValue } const originalIndentation = indentation if (Array.isArray(value)) { if (value.length === 0) { return '[]' } if (maximumDepth < stack.length + 1) { return '"[Array]"' } stack.push(value) indentation += spacer let res = `\n${indentation}` const join = `,\n${indentation}` const maximumValuesToStringify = Math.min(value.length, maximumBreadth) let i = 0 for (; i < maximumValuesToStringify - 1; i++) { const tmp = stringifyIndent(i, value[i], stack, spacer, indentation) res += tmp !== undefined ? tmp : 'null' res += join } const tmp = stringifyIndent(i, value[i], stack, spacer, indentation) res += tmp !== undefined ? tmp : 'null' if (value.length - 1 > maximumBreadth) { const removedKeys = value.length - maximumBreadth - 1 res += `${join}"... ${getItemCount(removedKeys)} not stringified"` } res += `\n${originalIndentation}` stack.pop() return `[${res}]` } let keys = Object.keys(value) const keyLength = keys.length if (keyLength === 0) { return '{}' } if (maximumDepth < stack.length + 1) { return '"[Object]"' } indentation += spacer const join = `,\n${indentation}` let res = '' let separator = '' let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth) if (isTypedArrayWithEntries(value)) { res += stringifyTypedArray(value, join, maximumBreadth) keys = keys.slice(value.length) maximumPropertiesToStringify -= value.length separator = join } if (deterministic) { keys = insertSort(keys) } stack.push(value) for (let i = 0; i < maximumPropertiesToStringify; i++) { const key = keys[i] const tmp = stringifyIndent(key, value[key], stack, spacer, indentation) if (tmp !== undefined) { res += `${separator}"${strEscape(key)}": ${tmp}` separator = join } } if (keyLength > maximumBreadth) { const removedKeys = keyLength - maximumBreadth res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"` separator = join } if (separator !== '') { res = `\n${indentation}${res}\n${originalIndentation}` } stack.pop() return `{${res}}` } case 'number': return isFinite(value) ? String(value) : 'null' case 'boolean': return value === true ? 'true' : 'false' case 'bigint': return bigint ? String(value) : undefined } } function stringifySimple (key, value, stack) { switch (typeof value) { case 'string': return `"${strEscape(value)}"` case 'object': { if (value === null) { return 'null' } if (typeof value.toJSON === 'function') { value = value.toJSON(key) // Prevent calling `toJSON` again if (typeof value !== 'object') { return stringifySimple(key, value, stack) } if (value === null) { return 'null' } } if (stack.indexOf(value) !== -1) { return circularValue } let res = '' if (Array.isArray(value)) { if (value.length === 0) { return '[]' } if (maximumDepth < stack.length + 1) { return '"[Array]"' } stack.push(value) const maximumValuesToStringify = Math.min(value.length, maximumBreadth) let i = 0 for (; i < maximumValuesToStringify - 1; i++) { const tmp = stringifySimple(i, value[i], stack) res += tmp !== undefined ? tmp : 'null' res += ',' } const tmp = stringifySimple(i, value[i], stack) res += tmp !== undefined ? tmp : 'null' if (value.length - 1 > maximumBreadth) { const removedKeys = value.length - maximumBreadth - 1 res += `,"... ${getItemCount(removedKeys)} not stringified"` } stack.pop() return `[${res}]` } let keys = Object.keys(value) const keyLength = keys.length if (keyLength === 0) { return '{}' } if (maximumDepth < stack.length + 1) { return '"[Object]"' } let separator = '' let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth) if (isTypedArrayWithEntries(value)) { res += stringifyTypedArray(value, ',', maximumBreadth) keys = keys.slice(value.length) maximumPropertiesToStringify -= value.length separator = ',' } if (deterministic) { keys = insertSort(keys) } stack.push(value) for (let i = 0; i < maximumPropertiesToStringify; i++) { const key = keys[i] const tmp = stringifySimple(key, value[key], stack) if (tmp !== undefined) { res += `${separator}"${strEscape(key)}":${tmp}` separator = ',' } } if (keyLength > maximumBreadth) { const removedKeys = keyLength - maximumBreadth res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"` } stack.pop() return `{${res}}` } case 'number': return isFinite(value) ? String(value) : 'null' case 'boolean': return value === true ? 'true' : 'false' case 'bigint': return bigint ? String(value) : undefined } } function stringify (value, replacer, space) { if (arguments.length > 1) { let spacer = '' if (typeof space === 'number') { spacer = ' '.repeat(Math.min(space, 10)) } else if (typeof space === 'string') { spacer = space.slice(0, 10) } if (replacer != null) { if (typeof replacer === 'function') { return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '') } if (Array.isArray(replacer)) { return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '') } } if (spacer.length !== 0) { return stringifyIndent('', value, [], spacer, '') } } return stringifySimple('', value, []) } return stringify } /***/ }), /***/ 2399: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* provided dependency */ var process = __webpack_require__(3454); /* eslint-disable node/no-deprecated-api */ var buffer = __webpack_require__(8764) var Buffer = buffer.Buffer var safer = {} var key for (key in buffer) { if (!buffer.hasOwnProperty(key)) continue if (key === 'SlowBuffer' || key === 'Buffer') continue safer[key] = buffer[key] } var Safer = safer.Buffer = {} for (key in Buffer) { if (!Buffer.hasOwnProperty(key)) continue if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue Safer[key] = Buffer[key] } safer.Buffer.prototype = Buffer.prototype if (!Safer.from || Safer.from === Uint8Array.from) { Safer.from = function (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) } if (value && typeof value.length === 'undefined') { throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) } return Buffer(value, encodingOrOffset, length) } } if (!Safer.alloc) { Safer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) } if (size < 0 || size >= 2 * (1 << 30)) { throw new RangeError('The value "' + size + '" is invalid for option "size"') } var buf = Buffer(size) if (!fill || fill.length === 0) { buf.fill(0) } else if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } return buf } } if (!safer.kStringMaxLength) { try { safer.kStringMaxLength = process.binding('buffer').kStringMaxLength } catch (e) { // we can't determine kStringMaxLength in environments where process.binding // is unsupported, so let's not set it } } if (!safer.constants) { safer.constants = { MAX_LENGTH: safer.kMaxLength } if (safer.kStringMaxLength) { safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength } } module.exports = safer /***/ }), /***/ 2553: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /**/ var Buffer = (__webpack_require__(9509).Buffer); /**/ var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.StringDecoder = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. If an invalid byte is detected, -2 is returned. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return byte >> 6 === 0x02 ? -1 : -2; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'; } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'; } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'; } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character is added when ending on a partial // character. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'; return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } /***/ }), /***/ 3931: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "HTTPRangeReader": function() { return /* binding */ HTTPRangeReader; }, /* harmony export */ "cleanup": function() { return /* binding */ cleanup$1; }, /* harmony export */ "setOptions": function() { return /* binding */ setOptions$1; }, /* harmony export */ "unzip": function() { return /* binding */ unzip; }, /* harmony export */ "unzipRaw": function() { return /* binding */ unzipRaw; } /* harmony export */ }); /* module decorator */ module = __webpack_require__.hmd(module); /* provided dependency */ var process = __webpack_require__(3454); /* unzipit@1.4.0, license MIT */ /* global SharedArrayBuffer, process */ function readBlobAsArrayBuffer(blob) { if (blob.arrayBuffer) { return blob.arrayBuffer(); } return new Promise((resolve, reject) => { const reader = new FileReader(); reader.addEventListener('loadend', () => { resolve(reader.result); }); reader.addEventListener('error', reject); reader.readAsArrayBuffer(blob); }); } async function readBlobAsUint8Array(blob) { const arrayBuffer = await readBlobAsArrayBuffer(blob); return new Uint8Array(arrayBuffer); } function isBlob(v) { return typeof Blob !== 'undefined' && v instanceof Blob; } function isSharedArrayBuffer(b) { return typeof SharedArrayBuffer !== 'undefined' && b instanceof SharedArrayBuffer; } const isNode = (typeof process !== 'undefined') && process.versions && (typeof process.versions.node !== 'undefined') && (typeof process.versions.electron === 'undefined'); function isTypedArraySameAsArrayBuffer(typedArray) { return typedArray.byteOffset === 0 && typedArray.byteLength === typedArray.buffer.byteLength; } class ArrayBufferReader { constructor(arrayBufferOrView) { this.typedArray = (arrayBufferOrView instanceof ArrayBuffer || isSharedArrayBuffer(arrayBufferOrView)) ? new Uint8Array(arrayBufferOrView) : new Uint8Array(arrayBufferOrView.buffer, arrayBufferOrView.byteOffset, arrayBufferOrView.byteLength); } async getLength() { return this.typedArray.byteLength; } async read(offset, length) { return new Uint8Array(this.typedArray.buffer, this.typedArray.byteOffset + offset, length); } } class BlobReader { constructor(blob) { this.blob = blob; } async getLength() { return this.blob.size; } async read(offset, length) { const blob = this.blob.slice(offset, offset + length); const arrayBuffer = await readBlobAsArrayBuffer(blob); return new Uint8Array(arrayBuffer); } async sliceAsBlob(offset, length, type = '') { return this.blob.slice(offset, offset + length, type); } } class HTTPRangeReader { constructor(url) { this.url = url; } async getLength() { if (this.length === undefined) { const req = await fetch(this.url, { method: 'HEAD' }); if (!req.ok) { throw new Error(`failed http request ${this.url}, status: ${req.status}: ${req.statusText}`); } this.length = parseInt(req.headers.get('content-length')); if (Number.isNaN(this.length)) { throw Error('could not get length'); } } return this.length; } async read(offset, size) { if (size === 0) { return new Uint8Array(0); } const req = await fetch(this.url, { headers: { Range: `bytes=${offset}-${offset + size - 1}`, }, }); if (!req.ok) { throw new Error(`failed http request ${this.url}, status: ${req.status} offset: ${offset} size: ${size}: ${req.statusText}`); } const buffer = await req.arrayBuffer(); return new Uint8Array(buffer); } } function inflate(data, buf) { var u8=Uint8Array; if(data[0]==3 && data[1]==0) return (buf ? buf : new u8(0)); var bitsF = _bitsF, bitsE = _bitsE, decodeTiny = _decodeTiny, get17 = _get17; var noBuf = (buf==null); if(noBuf) buf = new u8((data.length>>>2)<<3); var BFINAL=0, BTYPE=0, HLIT=0, HDIST=0, HCLEN=0, ML=0, MD=0; var off = 0, pos = 0; var lmap, dmap; while(BFINAL==0) { BFINAL = bitsF(data, pos , 1); BTYPE = bitsF(data, pos+1, 2); pos+=3; //console.log(BFINAL, BTYPE); if(BTYPE==0) { if((pos&7)!=0) pos+=8-(pos&7); var p8 = (pos>>>3)+4, len = data[p8-4]|(data[p8-3]<<8); //console.log(len);//bitsF(data, pos, 16), if(noBuf) buf=_check(buf, off+len); buf.set(new u8(data.buffer, data.byteOffset+p8, len), off); //for(var i=0; itl)tl=l; } pos+=3*HCLEN; //console.log(itree); makeCodes(U.itree, tl); codes2map(U.itree, tl, U.imap); lmap = U.lmap; dmap = U.dmap; pos = decodeTiny(U.imap, (1<>>24))-1; pos+=(ml&0xffffff); makeCodes(U.ltree, mx0); codes2map(U.ltree, mx0, lmap); //var md = decodeTiny(U.imap, (1<>>24))-1; pos+=(md&0xffffff); makeCodes(U.dtree, mx1); codes2map(U.dtree, mx1, dmap); } //var ooff=off, opos=pos; while(true) { var code = lmap[get17(data, pos) & ML]; pos += code&15; var lit = code>>>4; //U.lhst[lit]++; if((lit>>>8)==0) { buf[off++] = lit; } else if(lit==256) { break; } else { var end = off+lit-254; if(lit>264) { var ebs = U.ldef[lit-257]; end = off + (ebs>>>3) + bitsE(data, pos, ebs&7); pos += ebs&7; } //dst[end-off]++; var dcode = dmap[get17(data, pos) & MD]; pos += dcode&15; var dlit = dcode>>>4; var dbs = U.ddef[dlit], dst = (dbs>>>4) + bitsF(data, pos, dbs&15); pos += dbs&15; //var o0 = off-dst, stp = Math.min(end-off, dst); //if(stp>20) while(off>>3); } //console.log(dst); //console.log(tlen, dlen, off-tlen+tcnt); return buf.length==off ? buf : buf.slice(0,off); } function _check(buf, len) { var bl=buf.length; if(len<=bl) return buf; var nbuf = new Uint8Array(Math.max(bl<<1,len)); nbuf.set(buf,0); //for(var i=0; i>>4; if(lit<=15) { tree[i]=lit; i++; } else { var ll = 0, n = 0; if(lit==16) { n = (3 + bitsE(data, pos, 2)); pos += 2; ll = tree[i-1]; } else if(lit==17) { n = (3 + bitsE(data, pos, 3)); pos += 3; } else if(lit==18) { n = (11 + bitsE(data, pos, 7)); pos += 7; } var ni = i+n; while(i>>1; while(imx)mx=v; i++; } while(i>1; var cl = tree[i+1], val = (lit<<4)|cl; // : (0x8000 | (U.of0[lit-257]<<7) | (U.exb[lit-257]<<4) | cl); var rest = (MAX_BITS-cl), i0 = tree[i]<>>(15-MAX_BITS); while(i0!=i1) { var p0 = r15[i0]>>>(15-MAX_BITS); map[p0]=val; i0++; } } } function revCodes(tree, MAX_BITS) { var r15 = U.rev15, imb = 15-MAX_BITS; for(var i=0; i>>imb; } } function _bitsE(dt, pos, length) { return ((dt[pos>>>3] | (dt[(pos>>>3)+1]<<8) )>>>(pos&7))&((1<>>3] | (dt[(pos>>>3)+1]<<8) | (dt[(pos>>>3)+2]<<16))>>>(pos&7))&((1<>>3] | (dt[(pos>>>3)+1]<<8))>>>(pos&7))&511; } */ function _get17(dt, pos) { // return at least 17 meaningful bytes return (dt[pos>>>3] | (dt[(pos>>>3)+1]<<8) | (dt[(pos>>>3)+2]<<16) )>>>(pos&7); } const U = function(){ var u16=Uint16Array, u32=Uint32Array; return { next_code : new u16(16), bl_count : new u16(16), ordr : [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ], of0 : [3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999], exb : [0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0], ldef : new u16(32), df0 : [1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 65535, 65535], dxb : [0,0,0,0,1,1,2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0], ddef : new u32(32), flmap: new u16( 512), fltree: [], fdmap: new u16( 32), fdtree: [], lmap : new u16(32768), ltree : [], ttree:[], dmap : new u16(32768), dtree : [], imap : new u16( 512), itree : [], //rev9 : new u16( 512) rev15: new u16(1<<15), lhst : new u32(286), dhst : new u32( 30), ihst : new u32(19), lits : new u32(15000), strt : new u16(1<<16), prev : new u16(1<<15) }; } (); (function(){ var len = 1<<15; for(var i=0; i>> 1) | ((x & 0x55555555) << 1)); x = (((x & 0xcccccccc) >>> 2) | ((x & 0x33333333) << 2)); x = (((x & 0xf0f0f0f0) >>> 4) | ((x & 0x0f0f0f0f) << 4)); x = (((x & 0xff00ff00) >>> 8) | ((x & 0x00ff00ff) << 8)); U.rev15[i] = (((x >>> 16) | (x << 16)))>>>17; } function pushV(tgt, n, sv) { while(n--!=0) tgt.push(0,sv); } for(var i=0; i<32; i++) { U.ldef[i]=(U.of0[i]<<3)|U.exb[i]; U.ddef[i]=(U.df0[i]<<4)|U.dxb[i]; } pushV(U.fltree, 144, 8); pushV(U.fltree, 255-143, 9); pushV(U.fltree, 279-255, 7); pushV(U.fltree,287-279,8); /* var i = 0; for(; i<=143; i++) U.fltree.push(0,8); for(; i<=255; i++) U.fltree.push(0,9); for(; i<=279; i++) U.fltree.push(0,7); for(; i<=287; i++) U.fltree.push(0,8); */ makeCodes(U.fltree, 9); codes2map(U.fltree, 9, U.flmap); revCodes (U.fltree, 9); pushV(U.fdtree,32,5); //for(i=0;i<32; i++) U.fdtree.push(0,5); makeCodes(U.fdtree, 5); codes2map(U.fdtree, 5, U.fdmap); revCodes (U.fdtree, 5); pushV(U.itree,19,0); pushV(U.ltree,286,0); pushV(U.dtree,30,0); pushV(U.ttree,320,0); /* for(var i=0; i< 19; i++) U.itree.push(0,0); for(var i=0; i<286; i++) U.ltree.push(0,0); for(var i=0; i< 30; i++) U.dtree.push(0,0); for(var i=0; i<320; i++) U.ttree.push(0,0); */ })(); const crc = { table : ( function() { var tab = new Uint32Array(256); for (var n=0; n<256; n++) { var c = n; for (var k=0; k<8; k++) { if (c & 1) c = 0xedb88320 ^ (c >>> 1); else c = c >>> 1; } tab[n] = c; } return tab; })(), update : function(c, buf, off, len) { for (var i=0; i>> 8); return c; }, crc : function(b,o,l) { return crc.update(0xffffffff,b,o,l) ^ 0xffffffff; } }; function inflateRaw(file, buf) { return inflate(file, buf); } /* global module */ const config = { numWorkers: 1, workerURL: '', useWorkers: false, }; let nextId = 0; // Requests are put on a queue. // We don't send the request to the worker until the worker // is finished. This probably adds a small amount of latency // but the issue is imagine you have 2 workers. You give worker // A x seconds of work to do and worker B y seconds of work to // do. You don't know which will finish first. If you give // the worker with more work to do the request then you'll // waste time. // note: we can't check `workers.length` for deciding if // we've reached `config.numWorkers` because creation the worker // is async which means other requests to make workers might // come in before a worker gets added to `workers` let numWorkers = 0; let canUseWorkers = true; // gets set to false if we can't start a worker const workers = []; const availableWorkers = []; const waitingForWorkerQueue = []; const currentlyProcessingIdToRequestMap = new Map(); function handleResult(e) { makeWorkerAvailable(e.target); const {id, error, data} = e.data; const request = currentlyProcessingIdToRequestMap.get(id); currentlyProcessingIdToRequestMap.delete(id); if (error) { request.reject(error); } else { request.resolve(data); } } // Because Firefox uses non-standard onerror to signal an error. function startWorker(url) { return new Promise((resolve, reject) => { const worker = new Worker(url); worker.onmessage = (e) => { if (e.data === 'start') { worker.onerror = undefined; worker.onmessage = undefined; resolve(worker); } else { reject(new Error(`unexpected message: ${e.data}`)); } }; worker.onerror = reject; }); } function dynamicRequire(mod, request) { return mod.require(request); } const workerHelper = (function() { if (isNode) { // We need to use `dynamicRequire` because `require` on it's own will be optimized by webpack. const {Worker} = dynamicRequire(module, 'worker_threads'); return { async createWorker(url) { return new Worker(url); }, addEventListener(worker, fn) { worker.on('message', (data) => { fn({target: worker, data}); }); }, async terminate(worker) { await worker.terminate(); }, }; } else { return { async createWorker(url) { // I don't understand this security issue // Apparently there is some iframe setting or http header // that prevents cross domain workers. But, I can manually // download the text and do it. I reported this to Chrome // and they said it was fine so ¯\_(ツ)_/¯ try { const worker = await startWorker(url); return worker; } catch (e) { console.warn('could not load worker:', url); } let text; try { const req = await fetch(url, {mode: 'cors'}); if (!req.ok) { throw new Error(`could not load: ${url}`); } text = await req.text(); url = URL.createObjectURL(new Blob([text], {type: 'application/javascript'})); const worker = await startWorker(url); config.workerURL = url; // this is a hack. What's a better way to structure this code? return worker; } catch (e) { console.warn('could not load worker via fetch:', url); } if (text !== undefined) { try { url = `data:application/javascript;base64,${btoa(text)}`; const worker = await startWorker(url); config.workerURL = url; return worker; } catch (e) { console.warn('could not load worker via dataURI'); } } console.warn('workers will not be used'); throw new Error('can not start workers'); }, addEventListener(worker, fn) { worker.addEventListener('message', fn); }, async terminate(worker) { worker.terminate(); }, }; } }()); function makeWorkerAvailable(worker) { availableWorkers.push(worker); processWaitingForWorkerQueue(); } async function getAvailableWorker() { if (availableWorkers.length === 0 && numWorkers < config.numWorkers) { ++numWorkers; // see comment at numWorkers declaration try { const worker = await workerHelper.createWorker(config.workerURL); workers.push(worker); availableWorkers.push(worker); workerHelper.addEventListener(worker, handleResult); } catch (e) { // set this global out-of-band (needs refactor) canUseWorkers = false; } } return availableWorkers.pop(); } // @param {Uint8Array} src // @param {number} uncompressedSize // @param {string} [type] mime-type // @returns {ArrayBuffer|Blob} ArrayBuffer if type is falsy or Blob otherwise. function inflateRawLocal(src, uncompressedSize, type, resolve) { const dst = new Uint8Array(uncompressedSize); inflateRaw(src, dst); resolve(type ? new Blob([dst], {type}) : dst.buffer); } async function processWaitingForWorkerQueue() { if (waitingForWorkerQueue.length === 0) { return; } if (config.useWorkers && canUseWorkers) { const worker = await getAvailableWorker(); // canUseWorkers might have been set out-of-band (need refactor) if (canUseWorkers) { if (worker) { if (waitingForWorkerQueue.length === 0) { // the queue might be empty while we awaited for a worker. makeWorkerAvailable(worker); return; } const {id, src, uncompressedSize, type, resolve, reject} = waitingForWorkerQueue.shift(); currentlyProcessingIdToRequestMap.set(id, {id, resolve, reject}); const transferables = []; // NOTE: Originally I thought you could transfer an ArrayBuffer. // The code on this side is often using views into the entire file // which means if we transferred we'd lose the entire file. That sucks // because it means there's an expensive copy to send the uncompressed // data to the worker. // // Also originally I thought we could send a Blob but we'd need to refactor // the code in unzipit/readEntryData as currently it reads the uncompressed // bytes. // //if (!isBlob(src) && !isSharedArrayBuffer(src)) { // transferables.push(src); //} worker.postMessage({ type: 'inflate', data: { id, type, src, uncompressedSize, }, }, transferables); } return; } } // inflate locally // We loop here because what happens if many requests happen at once // the first N requests will try to async make a worker. Other requests // will then be on the queue. But if we fail to make workers then there // are pending requests. while (waitingForWorkerQueue.length) { const {src, uncompressedSize, type, resolve} = waitingForWorkerQueue.shift(); let data = src; if (isBlob(src)) { data = await readBlobAsUint8Array(src); } inflateRawLocal(data, uncompressedSize, type, resolve); } } function setOptions(options) { config.workerURL = options.workerURL || config.workerURL; // there's no reason to set the workerURL if you're not going to use workers if (options.workerURL) { config.useWorkers = true; } config.useWorkers = options.useWorkers !== undefined ? options.useWorkers : config.useWorkers; config.numWorkers = options.numWorkers || config.numWorkers; } // It has to take non-zero time to put a large typed array in a Blob since the very // next instruction you could change the contents of the array. So, if you're reading // the zip file for images/video/audio then all you want is a Blob on which to get a URL. // so that operation of putting the data in a Blob should happen in the worker. // // Conversely if you want the data itself then you want an ArrayBuffer immediately // since the worker can transfer its ArrayBuffer zero copy. // // @param {Uint8Array|Blob} src // @param {number} uncompressedSize // @param {string} [type] falsy or mimeType string (eg: 'image/png') // @returns {ArrayBuffer|Blob} ArrayBuffer if type is falsy or Blob otherwise. function inflateRawAsync(src, uncompressedSize, type) { return new Promise((resolve, reject) => { // note: there is potential an expensive copy here. In order for the data // to make it into the worker we need to copy the data to the worker unless // it's a Blob or a SharedArrayBuffer. // // Solutions: // // 1. A minor enhancement, if `uncompressedSize` is small don't call the worker. // // might be a win period as their is overhead calling the worker // // 2. Move the entire library to the worker // // Good, Maybe faster if you pass a URL, Blob, or SharedArrayBuffer? Not sure about that // as those are also easy to transfer. Still slow if you pass an ArrayBuffer // as the ArrayBuffer has to be copied to the worker. // // I guess benchmarking is really the only thing to try. waitingForWorkerQueue.push({src, uncompressedSize, type, resolve, reject, id: nextId++}); processWaitingForWorkerQueue(); }); } function clearArray(arr) { arr.splice(0, arr.length); } async function cleanup() { for (const worker of workers) { await workerHelper.terminate(worker); } clearArray(workers); clearArray(availableWorkers); clearArray(waitingForWorkerQueue); currentlyProcessingIdToRequestMap.clear(); numWorkers = 0; canUseWorkers = true; } /* class Zip { constructor(reader) { comment, // the comment for this entry commentBytes, // the raw comment for this entry } } */ function dosDateTimeToDate(date, time) { const day = date & 0x1f; // 1-31 const month = (date >> 5 & 0xf) - 1; // 1-12, 0-11 const year = (date >> 9 & 0x7f) + 1980; // 0-128, 1980-2108 const millisecond = 0; const second = (time & 0x1f) * 2; // 0-29, 0-58 (even numbers) const minute = time >> 5 & 0x3f; // 0-59 const hour = time >> 11 & 0x1f; // 0-23 return new Date(year, month, day, hour, minute, second, millisecond); } class ZipEntry { constructor(reader, rawEntry) { this._reader = reader; this._rawEntry = rawEntry; this.name = rawEntry.name; this.nameBytes = rawEntry.nameBytes; this.size = rawEntry.uncompressedSize; this.compressedSize = rawEntry.compressedSize; this.comment = rawEntry.comment; this.commentBytes = rawEntry.commentBytes; this.compressionMethod = rawEntry.compressionMethod; this.lastModDate = dosDateTimeToDate(rawEntry.lastModFileDate, rawEntry.lastModFileTime); this.isDirectory = rawEntry.uncompressedSize === 0 && rawEntry.name.endsWith('/'); this.encrypted = !!(rawEntry.generalPurposeBitFlag & 0x1); this.externalFileAttributes = rawEntry.externalFileAttributes; this.versionMadeBy = rawEntry.versionMadeBy; } // returns a promise that returns a Blob for this entry async blob(type = 'application/octet-stream') { return await readEntryDataAsBlob(this._reader, this._rawEntry, type); } // returns a promise that returns an ArrayBuffer for this entry async arrayBuffer() { return await readEntryDataAsArrayBuffer(this._reader, this._rawEntry); } // returns text, assumes the text is valid utf8. If you want more options decode arrayBuffer yourself async text() { const buffer = await this.arrayBuffer(); return decodeBuffer(new Uint8Array(buffer)); } // returns text with JSON.parse called on it. If you want more options decode arrayBuffer yourself async json() { const text = await this.text(); return JSON.parse(text); } } const EOCDR_WITHOUT_COMMENT_SIZE = 22; const MAX_COMMENT_SIZE = 0xffff; // 2-byte size const EOCDR_SIGNATURE = 0x06054b50; const ZIP64_EOCDR_SIGNATURE = 0x06064b50; async function readAs(reader, offset, length) { return await reader.read(offset, length); } // The point of this function is we want to be able to pass the data // to a worker as fast as possible so when decompressing if the data // is already a blob and we can get a blob then get a blob. // // I'm not sure what a better way to refactor this is. We've got examples // of multiple readers. Ideally, for every type of reader we could ask // it, "give me a type that is zero copy both locally and when sent to a worker". // // The problem is the worker would also have to know the how to handle this // opaque type. I suppose the correct solution is to register different // reader handlers in the worker so BlobReader would register some // `handleZeroCopyType`. At the moment I don't feel like // refactoring. As it is you just pass in an instance of the reader // but instead you'd have to register the reader and some how get the // source for the `handleZeroCopyType` handler function into the worker. // That sounds like a huge PITA, requiring you to put the implementation // in a separate file so the worker can load it or some other workaround // hack. // // For now this hack works even if it's not generic. async function readAsBlobOrTypedArray(reader, offset, length, type) { if (reader.sliceAsBlob) { return await reader.sliceAsBlob(offset, length, type); } return await reader.read(offset, length); } const crc$1 = { unsigned() { return 0; }, }; function getUint16LE(uint8View, offset) { return uint8View[offset ] + uint8View[offset + 1] * 0x100; } function getUint32LE(uint8View, offset) { return uint8View[offset ] + uint8View[offset + 1] * 0x100 + uint8View[offset + 2] * 0x10000 + uint8View[offset + 3] * 0x1000000; } function getUint64LE(uint8View, offset) { return getUint32LE(uint8View, offset) + getUint32LE(uint8View, offset + 4) * 0x100000000; } /* eslint-disable no-irregular-whitespace */ // const decodeCP437 = (function() { // const cp437 = '\u0000☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ '; // // return function(uint8view) { // return Array.from(uint8view).map(v => cp437[v]).join(''); // }; // }()); /* eslint-enable no-irregular-whitespace */ const utf8Decoder = new TextDecoder(); function decodeBuffer(uint8View, isUTF8) { /* eslint-disable-line no-unused-vars */ /* lgtm [js/superfluous-trailing-arguments] */ if (isSharedArrayBuffer(uint8View.buffer)) { uint8View = new Uint8Array(uint8View); } return utf8Decoder.decode(uint8View); /* AFAICT the UTF8 flat is not set so it's 100% up to the user to self decode if their file is not utf8 filenames return isUTF8 ? utf8Decoder.decode(uint8View) : decodeCP437(uint8View); */ } async function findEndOfCentralDirector(reader, totalLength) { const size = Math.min(EOCDR_WITHOUT_COMMENT_SIZE + MAX_COMMENT_SIZE, totalLength); const readStart = totalLength - size; const data = await readAs(reader, readStart, size); for (let i = size - EOCDR_WITHOUT_COMMENT_SIZE; i >= 0; --i) { if (getUint32LE(data, i) !== EOCDR_SIGNATURE) { continue; } // 0 - End of central directory signature const eocdr = new Uint8Array(data.buffer, data.byteOffset + i, data.byteLength - i); // 4 - Number of this disk const diskNumber = getUint16LE(eocdr, 4); if (diskNumber !== 0) { throw new Error(`multi-volume zip files are not supported. This is volume: ${diskNumber}`); } // 6 - Disk where central directory starts // 8 - Number of central directory records on this disk // 10 - Total number of central directory records const entryCount = getUint16LE(eocdr, 10); // 12 - Size of central directory (bytes) const centralDirectorySize = getUint32LE(eocdr, 12); // 16 - Offset of start of central directory, relative to start of archive const centralDirectoryOffset = getUint32LE(eocdr, 16); // 20 - Comment length const commentLength = getUint16LE(eocdr, 20); const expectedCommentLength = eocdr.length - EOCDR_WITHOUT_COMMENT_SIZE; if (commentLength !== expectedCommentLength) { throw new Error(`invalid comment length. expected: ${expectedCommentLength}, actual: ${commentLength}`); } // 22 - Comment // the encoding is always cp437. const commentBytes = new Uint8Array(eocdr.buffer, eocdr.byteOffset + 22, commentLength); const comment = decodeBuffer(commentBytes); if (entryCount === 0xffff || centralDirectoryOffset === 0xffffffff) { return await readZip64CentralDirectory(reader, readStart + i, comment, commentBytes); } else { return await readEntries(reader, centralDirectoryOffset, centralDirectorySize, entryCount, comment, commentBytes); } } throw new Error('could not find end of central directory. maybe not zip file'); } const END_OF_CENTRAL_DIRECTORY_LOCATOR_SIGNATURE = 0x07064b50; async function readZip64CentralDirectory(reader, offset, comment, commentBytes) { // ZIP64 Zip64 end of central directory locator const zip64EocdlOffset = offset - 20; const eocdl = await readAs(reader, zip64EocdlOffset, 20); // 0 - zip64 end of central dir locator signature if (getUint32LE(eocdl, 0) !== END_OF_CENTRAL_DIRECTORY_LOCATOR_SIGNATURE) { throw new Error('invalid zip64 end of central directory locator signature'); } // 4 - number of the disk with the start of the zip64 end of central directory // 8 - relative offset of the zip64 end of central directory record const zip64EocdrOffset = getUint64LE(eocdl, 8); // 16 - total number of disks // ZIP64 end of central directory record const zip64Eocdr = await readAs(reader, zip64EocdrOffset, 56); // 0 - zip64 end of central dir signature 4 bytes (0x06064b50) if (getUint32LE(zip64Eocdr, 0) !== ZIP64_EOCDR_SIGNATURE) { throw new Error('invalid zip64 end of central directory record signature'); } // 4 - size of zip64 end of central directory record 8 bytes // 12 - version made by 2 bytes // 14 - version needed to extract 2 bytes // 16 - number of this disk 4 bytes // 20 - number of the disk with the start of the central directory 4 bytes // 24 - total number of entries in the central directory on this disk 8 bytes // 32 - total number of entries in the central directory 8 bytes const entryCount = getUint64LE(zip64Eocdr, 32); // 40 - size of the central directory 8 bytes const centralDirectorySize = getUint64LE(zip64Eocdr, 40); // 48 - offset of start of central directory with respect to the starting disk number 8 bytes const centralDirectoryOffset = getUint64LE(zip64Eocdr, 48); // 56 - zip64 extensible data sector (variable size) return readEntries(reader, centralDirectoryOffset, centralDirectorySize, entryCount, comment, commentBytes); } const CENTRAL_DIRECTORY_FILE_HEADER_SIGNATURE = 0x02014b50; async function readEntries(reader, centralDirectoryOffset, centralDirectorySize, rawEntryCount, comment, commentBytes) { let readEntryCursor = 0; const allEntriesBuffer = await readAs(reader, centralDirectoryOffset, centralDirectorySize); const rawEntries = []; for (let e = 0; e < rawEntryCount; ++e) { const buffer = allEntriesBuffer.subarray(readEntryCursor, readEntryCursor + 46); // 0 - Central directory file header signature const signature = getUint32LE(buffer, 0); if (signature !== CENTRAL_DIRECTORY_FILE_HEADER_SIGNATURE) { throw new Error(`invalid central directory file header signature: 0x${signature.toString(16)}`); } const rawEntry = { // 4 - Version made by versionMadeBy: getUint16LE(buffer, 4), // 6 - Version needed to extract (minimum) versionNeededToExtract: getUint16LE(buffer, 6), // 8 - General purpose bit flag generalPurposeBitFlag: getUint16LE(buffer, 8), // 10 - Compression method compressionMethod: getUint16LE(buffer, 10), // 12 - File last modification time lastModFileTime: getUint16LE(buffer, 12), // 14 - File last modification date lastModFileDate: getUint16LE(buffer, 14), // 16 - CRC-32 crc32: getUint32LE(buffer, 16), // 20 - Compressed size compressedSize: getUint32LE(buffer, 20), // 24 - Uncompressed size uncompressedSize: getUint32LE(buffer, 24), // 28 - File name length (n) fileNameLength: getUint16LE(buffer, 28), // 30 - Extra field length (m) extraFieldLength: getUint16LE(buffer, 30), // 32 - File comment length (k) fileCommentLength: getUint16LE(buffer, 32), // 34 - Disk number where file starts // 36 - Internal file attributes internalFileAttributes: getUint16LE(buffer, 36), // 38 - External file attributes externalFileAttributes: getUint32LE(buffer, 38), // 42 - Relative offset of local file header relativeOffsetOfLocalHeader: getUint32LE(buffer, 42), }; if (rawEntry.generalPurposeBitFlag & 0x40) { throw new Error('strong encryption is not supported'); } readEntryCursor += 46; const data = allEntriesBuffer.subarray(readEntryCursor, readEntryCursor + rawEntry.fileNameLength + rawEntry.extraFieldLength + rawEntry.fileCommentLength); rawEntry.nameBytes = data.slice(0, rawEntry.fileNameLength); rawEntry.name = decodeBuffer(rawEntry.nameBytes); // 46+n - Extra field const fileCommentStart = rawEntry.fileNameLength + rawEntry.extraFieldLength; const extraFieldBuffer = data.slice(rawEntry.fileNameLength, fileCommentStart); rawEntry.extraFields = []; let i = 0; while (i < extraFieldBuffer.length - 3) { const headerId = getUint16LE(extraFieldBuffer, i + 0); const dataSize = getUint16LE(extraFieldBuffer, i + 2); const dataStart = i + 4; const dataEnd = dataStart + dataSize; if (dataEnd > extraFieldBuffer.length) { throw new Error('extra field length exceeds extra field buffer size'); } rawEntry.extraFields.push({ id: headerId, data: extraFieldBuffer.slice(dataStart, dataEnd), }); i = dataEnd; } // 46+n+m - File comment rawEntry.commentBytes = data.slice(fileCommentStart, fileCommentStart + rawEntry.fileCommentLength); rawEntry.comment = decodeBuffer(rawEntry.commentBytes); readEntryCursor += data.length; if (rawEntry.uncompressedSize === 0xffffffff || rawEntry.compressedSize === 0xffffffff || rawEntry.relativeOffsetOfLocalHeader === 0xffffffff) { // ZIP64 format // find the Zip64 Extended Information Extra Field const zip64ExtraField = rawEntry.extraFields.find(e => e.id === 0x0001); if (!zip64ExtraField) { throw new Error('expected zip64 extended information extra field'); } const zip64EiefBuffer = zip64ExtraField.data; let index = 0; // 0 - Original Size 8 bytes if (rawEntry.uncompressedSize === 0xffffffff) { if (index + 8 > zip64EiefBuffer.length) { throw new Error('zip64 extended information extra field does not include uncompressed size'); } rawEntry.uncompressedSize = getUint64LE(zip64EiefBuffer, index); index += 8; } // 8 - Compressed Size 8 bytes if (rawEntry.compressedSize === 0xffffffff) { if (index + 8 > zip64EiefBuffer.length) { throw new Error('zip64 extended information extra field does not include compressed size'); } rawEntry.compressedSize = getUint64LE(zip64EiefBuffer, index); index += 8; } // 16 - Relative Header Offset 8 bytes if (rawEntry.relativeOffsetOfLocalHeader === 0xffffffff) { if (index + 8 > zip64EiefBuffer.length) { throw new Error('zip64 extended information extra field does not include relative header offset'); } rawEntry.relativeOffsetOfLocalHeader = getUint64LE(zip64EiefBuffer, index); index += 8; } // 24 - Disk Start Number 4 bytes } // check for Info-ZIP Unicode Path Extra Field (0x7075) // see https://github.com/thejoshwolfe/yauzl/issues/33 const nameField = rawEntry.extraFields.find(e => e.id === 0x7075 && e.data.length >= 6 && // too short to be meaningful e.data[0] === 1 && // Version 1 byte version of this extra field, currently 1 getUint32LE(e.data, 1), crc$1.unsigned(rawEntry.nameBytes)); // NameCRC32 4 bytes File Name Field CRC32 Checksum // > If the CRC check fails, this UTF-8 Path Extra Field should be // > ignored and the File Name field in the header should be used instead. if (nameField) { // UnicodeName Variable UTF-8 version of the entry File Name rawEntry.fileName = decodeBuffer(nameField.data.slice(5)); } // validate file size if (rawEntry.compressionMethod === 0) { let expectedCompressedSize = rawEntry.uncompressedSize; if ((rawEntry.generalPurposeBitFlag & 0x1) !== 0) { // traditional encryption prefixes the file data with a header expectedCompressedSize += 12; } if (rawEntry.compressedSize !== expectedCompressedSize) { throw new Error(`compressed size mismatch for stored file: ${rawEntry.compressedSize} != ${expectedCompressedSize}`); } } rawEntries.push(rawEntry); } const zip = { comment, commentBytes, }; return { zip, entries: rawEntries.map(e => new ZipEntry(reader, e)), }; } async function readEntryDataHeader(reader, rawEntry) { if (rawEntry.generalPurposeBitFlag & 0x1) { throw new Error('encrypted entries not supported'); } const buffer = await readAs(reader, rawEntry.relativeOffsetOfLocalHeader, 30); // note: maybe this should be passed in or cached on entry // as it's async so there will be at least one tick (not sure about that) const totalLength = await reader.getLength(); // 0 - Local file header signature = 0x04034b50 const signature = getUint32LE(buffer, 0); if (signature !== 0x04034b50) { throw new Error(`invalid local file header signature: 0x${signature.toString(16)}`); } // all this should be redundant // 4 - Version needed to extract (minimum) // 6 - General purpose bit flag // 8 - Compression method // 10 - File last modification time // 12 - File last modification date // 14 - CRC-32 // 18 - Compressed size // 22 - Uncompressed size // 26 - File name length (n) const fileNameLength = getUint16LE(buffer, 26); // 28 - Extra field length (m) const extraFieldLength = getUint16LE(buffer, 28); // 30 - File name // 30+n - Extra field const localFileHeaderEnd = rawEntry.relativeOffsetOfLocalHeader + buffer.length + fileNameLength + extraFieldLength; let decompress; if (rawEntry.compressionMethod === 0) { // 0 - The file is stored (no compression) decompress = false; } else if (rawEntry.compressionMethod === 8) { // 8 - The file is Deflated decompress = true; } else { throw new Error(`unsupported compression method: ${rawEntry.compressionMethod}`); } const fileDataStart = localFileHeaderEnd; const fileDataEnd = fileDataStart + rawEntry.compressedSize; if (rawEntry.compressedSize !== 0) { // bounds check now, because the read streams will probably not complain loud enough. // since we're dealing with an unsigned offset plus an unsigned size, // we only have 1 thing to check for. if (fileDataEnd > totalLength) { throw new Error(`file data overflows file bounds: ${fileDataStart} + ${rawEntry.compressedSize} > ${totalLength}`); } } return { decompress, fileDataStart, }; } async function readEntryDataAsArrayBuffer(reader, rawEntry) { const {decompress, fileDataStart} = await readEntryDataHeader(reader, rawEntry); if (!decompress) { const dataView = await readAs(reader, fileDataStart, rawEntry.compressedSize); // make copy? // // 1. The source is a Blob/file. In this case we'll get back TypedArray we can just hand to the user // 2. The source is a TypedArray. In this case we'll get back TypedArray that is a view into a larger buffer // but because ultimately this is used to return an ArrayBuffer to `someEntry.arrayBuffer()` // we need to return copy since we need the `ArrayBuffer`, not the TypedArray to exactly match the data. // Note: We could add another API function `bytes()` or something that returned a `Uint8Array` // instead of an `ArrayBuffer`. This would let us skip a copy here. But this case only happens for uncompressed // data. That seems like a rare enough case that adding a new API is not worth it? Or is it? A zip of jpegs or mp3s // might not be compressed. For now that's a TBD. return isTypedArraySameAsArrayBuffer(dataView) ? dataView.buffer : dataView.slice().buffer; } // see comment in readEntryDateAsBlob const typedArrayOrBlob = await readAsBlobOrTypedArray(reader, fileDataStart, rawEntry.compressedSize); const result = await inflateRawAsync(typedArrayOrBlob, rawEntry.uncompressedSize); return result; } async function readEntryDataAsBlob(reader, rawEntry, type) { const {decompress, fileDataStart} = await readEntryDataHeader(reader, rawEntry); if (!decompress) { const typedArrayOrBlob = await readAsBlobOrTypedArray(reader, fileDataStart, rawEntry.compressedSize, type); if (isBlob(typedArrayOrBlob)) { return typedArrayOrBlob; } return new Blob([isSharedArrayBuffer(typedArrayOrBlob.buffer) ? new Uint8Array(typedArrayOrBlob) : typedArrayOrBlob], {type}); } // Here's the issue with this mess (should refactor?) // if the source is a blob then we really want to pass a blob to inflateRawAsync to avoid a large // copy if we're going to a worker. const typedArrayOrBlob = await readAsBlobOrTypedArray(reader, fileDataStart, rawEntry.compressedSize); const result = await inflateRawAsync(typedArrayOrBlob, rawEntry.uncompressedSize, type); return result; } function setOptions$1(options) { setOptions(options); } async function unzipRaw(source) { let reader; if (typeof Blob !== 'undefined' && source instanceof Blob) { reader = new BlobReader(source); } else if (source instanceof ArrayBuffer || (source && source.buffer && source.buffer instanceof ArrayBuffer)) { reader = new ArrayBufferReader(source); } else if (isSharedArrayBuffer(source) || isSharedArrayBuffer(source.buffer)) { reader = new ArrayBufferReader(source); } else if (typeof source === 'string') { const req = await fetch(source); if (!req.ok) { throw new Error(`failed http request ${source}, status: ${req.status}: ${req.statusText}`); } const blob = await req.blob(); reader = new BlobReader(blob); } else if (typeof source.getLength === 'function' && typeof source.read === 'function') { reader = source; } else { throw new Error('unsupported source type'); } const totalLength = await reader.getLength(); if (totalLength > Number.MAX_SAFE_INTEGER) { throw new Error(`file too large. size: ${totalLength}. Only file sizes up 4503599627370496 bytes are supported`); } return await findEndOfCentralDirector(reader, totalLength); } // If the names are not utf8 you should use unzipitRaw async function unzip(source) { const {zip, entries} = await unzipRaw(source); return { zip, entries: Object.fromEntries(entries.map(v => [v.name, v])), }; } function cleanup$1() { cleanup(); } /***/ }), /***/ 384: /***/ (function(module) { module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } /***/ }), /***/ 5955: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; // Currently in sync with Node.js lib/internal/util/types.js // https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 var isArgumentsObject = __webpack_require__(2584); var isGeneratorFunction = __webpack_require__(8662); var whichTypedArray = __webpack_require__(6430); var isTypedArray = __webpack_require__(5692); function uncurryThis(f) { return f.call.bind(f); } var BigIntSupported = typeof BigInt !== 'undefined'; var SymbolSupported = typeof Symbol !== 'undefined'; var ObjectToString = uncurryThis(Object.prototype.toString); var numberValue = uncurryThis(Number.prototype.valueOf); var stringValue = uncurryThis(String.prototype.valueOf); var booleanValue = uncurryThis(Boolean.prototype.valueOf); if (BigIntSupported) { var bigIntValue = uncurryThis(BigInt.prototype.valueOf); } if (SymbolSupported) { var symbolValue = uncurryThis(Symbol.prototype.valueOf); } function checkBoxedPrimitive(value, prototypeValueOf) { if (typeof value !== 'object') { return false; } try { prototypeValueOf(value); return true; } catch(e) { return false; } } exports.isArgumentsObject = isArgumentsObject; exports.isGeneratorFunction = isGeneratorFunction; exports.isTypedArray = isTypedArray; // Taken from here and modified for better browser support // https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js function isPromise(input) { return ( ( typeof Promise !== 'undefined' && input instanceof Promise ) || ( input !== null && typeof input === 'object' && typeof input.then === 'function' && typeof input.catch === 'function' ) ); } exports.isPromise = isPromise; function isArrayBufferView(value) { if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { return ArrayBuffer.isView(value); } return ( isTypedArray(value) || isDataView(value) ); } exports.isArrayBufferView = isArrayBufferView; function isUint8Array(value) { return whichTypedArray(value) === 'Uint8Array'; } exports.isUint8Array = isUint8Array; function isUint8ClampedArray(value) { return whichTypedArray(value) === 'Uint8ClampedArray'; } exports.isUint8ClampedArray = isUint8ClampedArray; function isUint16Array(value) { return whichTypedArray(value) === 'Uint16Array'; } exports.isUint16Array = isUint16Array; function isUint32Array(value) { return whichTypedArray(value) === 'Uint32Array'; } exports.isUint32Array = isUint32Array; function isInt8Array(value) { return whichTypedArray(value) === 'Int8Array'; } exports.isInt8Array = isInt8Array; function isInt16Array(value) { return whichTypedArray(value) === 'Int16Array'; } exports.isInt16Array = isInt16Array; function isInt32Array(value) { return whichTypedArray(value) === 'Int32Array'; } exports.isInt32Array = isInt32Array; function isFloat32Array(value) { return whichTypedArray(value) === 'Float32Array'; } exports.isFloat32Array = isFloat32Array; function isFloat64Array(value) { return whichTypedArray(value) === 'Float64Array'; } exports.isFloat64Array = isFloat64Array; function isBigInt64Array(value) { return whichTypedArray(value) === 'BigInt64Array'; } exports.isBigInt64Array = isBigInt64Array; function isBigUint64Array(value) { return whichTypedArray(value) === 'BigUint64Array'; } exports.isBigUint64Array = isBigUint64Array; function isMapToString(value) { return ObjectToString(value) === '[object Map]'; } isMapToString.working = ( typeof Map !== 'undefined' && isMapToString(new Map()) ); function isMap(value) { if (typeof Map === 'undefined') { return false; } return isMapToString.working ? isMapToString(value) : value instanceof Map; } exports.isMap = isMap; function isSetToString(value) { return ObjectToString(value) === '[object Set]'; } isSetToString.working = ( typeof Set !== 'undefined' && isSetToString(new Set()) ); function isSet(value) { if (typeof Set === 'undefined') { return false; } return isSetToString.working ? isSetToString(value) : value instanceof Set; } exports.isSet = isSet; function isWeakMapToString(value) { return ObjectToString(value) === '[object WeakMap]'; } isWeakMapToString.working = ( typeof WeakMap !== 'undefined' && isWeakMapToString(new WeakMap()) ); function isWeakMap(value) { if (typeof WeakMap === 'undefined') { return false; } return isWeakMapToString.working ? isWeakMapToString(value) : value instanceof WeakMap; } exports.isWeakMap = isWeakMap; function isWeakSetToString(value) { return ObjectToString(value) === '[object WeakSet]'; } isWeakSetToString.working = ( typeof WeakSet !== 'undefined' && isWeakSetToString(new WeakSet()) ); function isWeakSet(value) { return isWeakSetToString(value); } exports.isWeakSet = isWeakSet; function isArrayBufferToString(value) { return ObjectToString(value) === '[object ArrayBuffer]'; } isArrayBufferToString.working = ( typeof ArrayBuffer !== 'undefined' && isArrayBufferToString(new ArrayBuffer()) ); function isArrayBuffer(value) { if (typeof ArrayBuffer === 'undefined') { return false; } return isArrayBufferToString.working ? isArrayBufferToString(value) : value instanceof ArrayBuffer; } exports.isArrayBuffer = isArrayBuffer; function isDataViewToString(value) { return ObjectToString(value) === '[object DataView]'; } isDataViewToString.working = ( typeof ArrayBuffer !== 'undefined' && typeof DataView !== 'undefined' && isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) ); function isDataView(value) { if (typeof DataView === 'undefined') { return false; } return isDataViewToString.working ? isDataViewToString(value) : value instanceof DataView; } exports.isDataView = isDataView; // Store a copy of SharedArrayBuffer in case it's deleted elsewhere var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; function isSharedArrayBufferToString(value) { return ObjectToString(value) === '[object SharedArrayBuffer]'; } function isSharedArrayBuffer(value) { if (typeof SharedArrayBufferCopy === 'undefined') { return false; } if (typeof isSharedArrayBufferToString.working === 'undefined') { isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); } return isSharedArrayBufferToString.working ? isSharedArrayBufferToString(value) : value instanceof SharedArrayBufferCopy; } exports.isSharedArrayBuffer = isSharedArrayBuffer; function isAsyncFunction(value) { return ObjectToString(value) === '[object AsyncFunction]'; } exports.isAsyncFunction = isAsyncFunction; function isMapIterator(value) { return ObjectToString(value) === '[object Map Iterator]'; } exports.isMapIterator = isMapIterator; function isSetIterator(value) { return ObjectToString(value) === '[object Set Iterator]'; } exports.isSetIterator = isSetIterator; function isGeneratorObject(value) { return ObjectToString(value) === '[object Generator]'; } exports.isGeneratorObject = isGeneratorObject; function isWebAssemblyCompiledModule(value) { return ObjectToString(value) === '[object WebAssembly.Module]'; } exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; function isNumberObject(value) { return checkBoxedPrimitive(value, numberValue); } exports.isNumberObject = isNumberObject; function isStringObject(value) { return checkBoxedPrimitive(value, stringValue); } exports.isStringObject = isStringObject; function isBooleanObject(value) { return checkBoxedPrimitive(value, booleanValue); } exports.isBooleanObject = isBooleanObject; function isBigIntObject(value) { return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); } exports.isBigIntObject = isBigIntObject; function isSymbolObject(value) { return SymbolSupported && checkBoxedPrimitive(value, symbolValue); } exports.isSymbolObject = isSymbolObject; function isBoxedPrimitive(value) { return ( isNumberObject(value) || isStringObject(value) || isBooleanObject(value) || isBigIntObject(value) || isSymbolObject(value) ); } exports.isBoxedPrimitive = isBoxedPrimitive; function isAnyArrayBuffer(value) { return typeof Uint8Array !== 'undefined' && ( isArrayBuffer(value) || isSharedArrayBuffer(value) ); } exports.isAnyArrayBuffer = isAnyArrayBuffer; ['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { Object.defineProperty(exports, method, { enumerable: false, value: function() { throw new Error(method + ' is not supported in userland'); } }); }); /***/ }), /***/ 9539: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { /* provided dependency */ var process = __webpack_require__(3454); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(obj) { var keys = Object.keys(obj); var descriptors = {}; for (var i = 0; i < keys.length; i++) { descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); } return descriptors; }; var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { if (typeof process !== 'undefined' && process.noDeprecation === true) { return fn; } // Allow for deprecating things in the process of starting up. if (typeof process === 'undefined') { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnvRegex = /^$/; if (process.env.NODE_DEBUG) { var debugEnv = process.env.NODE_DEBUG; debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') .replace(/\*/g, '.*') .replace(/,/g, '$|^') .toUpperCase(); debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); } exports.debuglog = function(set) { set = set.toUpperCase(); if (!debugs[set]) { if (debugEnvRegex.test(set)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. exports.types = __webpack_require__(5955); function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; exports.types.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; exports.types.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; exports.types.isNativeError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = __webpack_require__(384); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = __webpack_require__(5717); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; exports.promisify = function promisify(original) { if (typeof original !== 'function') throw new TypeError('The "original" argument must be of type Function'); if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { var fn = original[kCustomPromisifiedSymbol]; if (typeof fn !== 'function') { throw new TypeError('The "util.promisify.custom" argument must be of type Function'); } Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return fn; } function fn() { var promiseResolve, promiseReject; var promise = new Promise(function (resolve, reject) { promiseResolve = resolve; promiseReject = reject; }); var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } args.push(function (err, value) { if (err) { promiseReject(err); } else { promiseResolve(value); } }); try { original.apply(this, args); } catch (err) { promiseReject(err); } return promise; } Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return Object.defineProperties( fn, getOwnPropertyDescriptors(original) ); } exports.promisify.custom = kCustomPromisifiedSymbol function callbackifyOnRejected(reason, cb) { // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). // Because `null` is a special error value in callbacks which means "no error // occurred", we error-wrap so the callback consumer can distinguish between // "the promise rejected with null" or "the promise fulfilled with undefined". if (!reason) { var newReason = new Error('Promise was rejected with a falsy value'); newReason.reason = reason; reason = newReason; } return cb(reason); } function callbackify(original) { if (typeof original !== 'function') { throw new TypeError('The "original" argument must be of type Function'); } // We DO NOT return the promise as it gives the user a false sense that // the promise is actually somehow related to the callback's execution // and that the callback throwing will reject the promise. function callbackified() { var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } var maybeCb = args.pop(); if (typeof maybeCb !== 'function') { throw new TypeError('The last argument must be of type Function'); } var self = this; var cb = function() { return maybeCb.apply(self, arguments); }; // In true node style we process the callback on `nextTick` with all the // implications (stack, `uncaughtException`, `async_hooks`) original.apply(this, args) .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); } Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)); return callbackified; } exports.callbackify = callbackify; /***/ }), /***/ 345: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SortKeyCacheResult = exports.CacheKey = void 0; class CacheKey { constructor(contractTxId, sortKey) { this.contractTxId = contractTxId; this.sortKey = sortKey; } } exports.CacheKey = CacheKey; // tslint:disable-next-line:max-classes-per-file class SortKeyCacheResult { constructor(sortKey, cachedValue) { this.sortKey = sortKey; this.cachedValue = cachedValue; } } exports.SortKeyCacheResult = SortKeyCacheResult; //# sourceMappingURL=SortKeyCache.js.map /***/ }), /***/ 7563: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LevelDbCache = void 0; const level_1 = __webpack_require__(3145); const memory_level_1 = __webpack_require__(1271); const LoggerFactory_1 = __webpack_require__(5913); /** * The LevelDB is a lexicographically sorted key-value database - so it's ideal for this use case * - as it simplifies cache look-ups (e.g. lastly stored value or value "lower-or-equal" than given sortKey). * The cache for contracts are implemented as sub-levels - https://www.npmjs.com/package/level#sublevel--dbsublevelname-options. * * The default location for the node.js cache is ./cache/warp. * The default name for the browser IndexedDB cache is warp-cache * * In order to reduce the cache size, the oldest entries are automatically pruned. */ class LevelDbCache { constructor(cacheOptions) { this.logger = LoggerFactory_1.LoggerFactory.INST.create('LevelDbCache'); if (cacheOptions.inMemory) { this.db = new memory_level_1.MemoryLevel({ valueEncoding: 'json' }); } else { if (!cacheOptions.dbLocation) { throw new Error('LevelDb cache configuration error - no db location specified'); } const dbLocation = cacheOptions.dbLocation; this.logger.info(`Using location ${dbLocation}`); this.db = new level_1.Level(dbLocation, { valueEncoding: 'json' }); } } async get(contractTxId, sortKey, returnDeepCopy) { const contractCache = this.db.sublevel(contractTxId, { valueEncoding: 'json' }); try { const result = await contractCache.get(sortKey); return { sortKey: sortKey, cachedValue: result }; } catch (e) { if (e.code == 'LEVEL_NOT_FOUND') { return null; } else { throw e; } } } async getLast(contractTxId) { const contractCache = this.db.sublevel(contractTxId, { valueEncoding: 'json' }); const keys = await contractCache.keys({ reverse: true, limit: 1 }).all(); if (keys.length) { return { sortKey: keys[0], cachedValue: await contractCache.get(keys[0]) }; } else { return null; } } async getLessOrEqual(contractTxId, sortKey) { const contractCache = this.db.sublevel(contractTxId, { valueEncoding: 'json' }); const keys = await contractCache.keys({ reverse: true, lte: sortKey, limit: 1 }).all(); if (keys.length) { return { sortKey: keys[0], cachedValue: await contractCache.get(keys[0]) }; } else { return null; } } async put(stateCacheKey, value) { const contractCache = this.db.sublevel(stateCacheKey.contractTxId, { valueEncoding: 'json' }); // manually opening to fix https://github.com/Level/level/issues/221 await contractCache.open(); await contractCache.put(stateCacheKey.sortKey, value); } close() { return this.db.close(); } async dump() { const result = await this.db.iterator().all(); return result; } // TODO: this implementation is sub-optimal // the lastSortKey should be probably memoized during "put" async getLastSortKey() { let lastSortKey = ''; const keys = await this.db.keys().all(); for (const key of keys) { // default key format used by sub-levels: // !! const sortKey = key.substring(45); if (sortKey.localeCompare(lastSortKey) > 0) { lastSortKey = sortKey; } } return lastSortKey == '' ? null : lastSortKey; } async allContracts() { const keys = await this.db.keys().all(); const result = new Set(); keys.forEach((k) => result.add(k.substring(1, 44))); return Array.from(result); } } exports.LevelDbCache = LevelDbCache; //# sourceMappingURL=LevelDbCache.js.map /***/ }), /***/ 1200: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MemCache = void 0; /** * A simple, in-memory cache, with keys being transaction ids (e.g. contract transaction id). */ class MemCache { constructor() { this.storage = {}; } clearAll() { Object.keys(this.storage).forEach((key) => { delete this.storage[key]; }); } contains(key) { return Object.prototype.hasOwnProperty.call(this.storage, key); } get(key) { return this.storage[key]; } put(key, value) { this.storage[key] = value; } remove(key) { delete this.storage[key]; } } exports.MemCache = MemCache; //# sourceMappingURL=MemCache.js.map /***/ }), /***/ 8469: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=Contract.js.map /***/ }), /***/ 9692: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; 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.HandlerBasedContract = void 0; const safe_stable_stringify_1 = __importDefault(__webpack_require__(7668)); const crypto = __importStar(__webpack_require__(1087)); const ContractCallStack_1 = __webpack_require__(5614); const LexicographicalInteractionsSorter_1 = __webpack_require__(1967); const StateEvaluator_1 = __webpack_require__(7462); const SmartWeaveTags_1 = __webpack_require__(7312); const create_interaction_tx_1 = __webpack_require__(40); const Benchmark_1 = __webpack_require__(9106); const LoggerFactory_1 = __webpack_require__(5913); const Evolve_1 = __webpack_require__(2491); const ArweaveWrapper_1 = __webpack_require__(9360); const utils_1 = __webpack_require__(5082); const CreateContract_1 = __webpack_require__(3611); const SourceImpl_1 = __webpack_require__(4217); const InnerWritesEvaluator_1 = __webpack_require__(8102); /** * An implementation of {@link Contract} that is backwards compatible with current style * of writing SW contracts (ie. using the "handle" function). * * It requires {@link ExecutorFactory} that is using {@link HandlerApi} generic type. */ class HandlerBasedContract { constructor(_contractTxId, warp, _parentContract = null, _callingInteraction = null) { this._contractTxId = _contractTxId; this.warp = warp; this._parentContract = _parentContract; this._callingInteraction = _callingInteraction; this.logger = LoggerFactory_1.LoggerFactory.INST.create('HandlerBasedContract'); this._evaluationOptions = new StateEvaluator_1.DefaultEvaluationOptions(); this._innerWritesEvaluator = new InnerWritesEvaluator_1.InnerWritesEvaluator(); this._benchmarkStats = null; this.waitForConfirmation = this.waitForConfirmation.bind(this); this._arweaveWrapper = new ArweaveWrapper_1.ArweaveWrapper(warp.arweave); this._sorter = new LexicographicalInteractionsSorter_1.LexicographicalInteractionsSorter(warp.arweave); if (_parentContract != null) { this._evaluationOptions = _parentContract.evaluationOptions(); this._callDepth = _parentContract.callDepth() + 1; const interaction = _parentContract.getCallStack().getInteraction(_callingInteraction.id); if (this._callDepth > this._evaluationOptions.maxCallDepth) { throw Error(`Max call depth of ${this._evaluationOptions.maxCallDepth} has been exceeded for interaction ${JSON.stringify(interaction.interactionInput)}`); } this.logger.debug('Calling interaction', { id: _callingInteraction.id, sortKey: _callingInteraction.sortKey }); const callStack = new ContractCallStack_1.ContractCallStack(_contractTxId, this._callDepth); interaction.interactionInput.foreignContractCalls.set(_contractTxId, callStack); this._callStack = callStack; this._rootSortKey = _parentContract.rootSortKey; } else { this._callDepth = 0; this._callStack = new ContractCallStack_1.ContractCallStack(_contractTxId, 0); this._rootSortKey = null; } } async readState(sortKeyOrBlockHeight, currentTx, interactions) { var _a, _b, _c; this.logger.info('Read state for', { contractTxId: this._contractTxId, currentTx, sortKeyOrBlockHeight }); const initBenchmark = Benchmark_1.Benchmark.measure(); this.maybeResetRootContract(); if (this._parentContract != null && sortKeyOrBlockHeight == null) { throw new Error('SortKey MUST be always set for non-root contract calls'); } const { stateEvaluator } = this.warp; const sortKey = typeof sortKeyOrBlockHeight == 'number' ? this._sorter.generateLastSortKey(sortKeyOrBlockHeight) : sortKeyOrBlockHeight; const executionContext = await this.createExecutionContext(this._contractTxId, sortKey, false, interactions); this.logger.info('Execution Context', { srcTxId: (_a = executionContext.contractDefinition) === null || _a === void 0 ? void 0 : _a.srcTxId, missingInteractions: (_b = executionContext.sortedInteractions) === null || _b === void 0 ? void 0 : _b.length, cachedSortKey: (_c = executionContext.cachedState) === null || _c === void 0 ? void 0 : _c.sortKey }); initBenchmark.stop(); const stateBenchmark = Benchmark_1.Benchmark.measure(); const result = await stateEvaluator.eval(executionContext, currentTx || []); stateBenchmark.stop(); const total = initBenchmark.elapsed(true) + stateBenchmark.elapsed(true); this._benchmarkStats = { gatewayCommunication: initBenchmark.elapsed(true), stateEvaluation: stateBenchmark.elapsed(true), total }; this.logger.info('Benchmark', { 'Gateway communication ': initBenchmark.elapsed(), 'Contract evaluation ': stateBenchmark.elapsed(), 'Total: ': `${total.toFixed(0)}ms` }); return result; } async viewState(input, tags = [], transfer = CreateContract_1.emptyTransfer) { this.logger.info('View state for', this._contractTxId); return await this.callContract(input, undefined, undefined, tags, transfer); } async viewStateForTx(input, interactionTx) { this.logger.info(`View state for ${this._contractTxId}`, interactionTx); return await this.callContractForTx(input, interactionTx); } async dryWrite(input, caller, tags, transfer) { this.logger.info('Dry-write for', this._contractTxId); return await this.callContract(input, caller, undefined, tags, transfer); } async dryWriteFromTx(input, transaction, currentTx) { this.logger.info(`Dry-write from transaction ${transaction.id} for ${this._contractTxId}`); return await this.callContractForTx(input, transaction, currentTx || []); } async writeInteraction(input, options) { this.logger.info('Write interaction', { input, options }); if (!this.signer) { throw new Error("Wallet not connected. Use 'connect' method first."); } const { arweave, interactionsLoader } = this.warp; const effectiveTags = (options === null || options === void 0 ? void 0 : options.tags) || []; const effectiveTransfer = (options === null || options === void 0 ? void 0 : options.transfer) || CreateContract_1.emptyTransfer; const effectiveStrict = (options === null || options === void 0 ? void 0 : options.strict) === true; const effectiveVrf = (options === null || options === void 0 ? void 0 : options.vrf) === true; const effectiveDisableBundling = (options === null || options === void 0 ? void 0 : options.disableBundling) === true; const effectiveReward = options === null || options === void 0 ? void 0 : options.reward; const bundleInteraction = interactionsLoader.type() == 'warp' && !effectiveDisableBundling; if (bundleInteraction && effectiveTransfer.target != CreateContract_1.emptyTransfer.target && effectiveTransfer.winstonQty != CreateContract_1.emptyTransfer.winstonQty) { throw new Error('Ar Transfers are not allowed for bundled interactions'); } if (effectiveVrf && !bundleInteraction) { throw new Error('Vrf generation is only available for bundle interaction'); } if (bundleInteraction) { return await this.bundleInteraction(input, { tags: effectiveTags, strict: effectiveStrict, vrf: effectiveVrf }); } else { const interactionTx = await this.createInteraction(input, effectiveTags, effectiveTransfer, effectiveStrict, false, false, effectiveReward); const response = await arweave.transactions.post(interactionTx); if (response.status !== 200) { this.logger.error('Error while posting transaction', response); return null; } if (this._evaluationOptions.waitForConfirmation) { this.logger.info('Waiting for confirmation of', interactionTx.id); const benchmark = Benchmark_1.Benchmark.measure(); await this.waitForConfirmation(interactionTx.id); this.logger.info('Transaction confirmed after', benchmark.elapsed()); } if (this.warp.environment == 'local' && this._evaluationOptions.mineArLocalBlocks) { await this.warp.testing.mineBlock(); } return { originalTxId: interactionTx.id }; } } async bundleInteraction(input, options) { this.logger.info('Bundle interaction input', input); const interactionTx = await this.createInteraction(input, options.tags, CreateContract_1.emptyTransfer, options.strict, true, options.vrf); const response = await fetch(`${this._evaluationOptions.bundlerUrl}gateway/sequencer/register`, { method: 'POST', body: JSON.stringify(interactionTx), headers: { 'Accept-Encoding': 'gzip, deflate, br', 'Content-Type': 'application/json', Accept: 'application/json' } }) .then((res) => { this.logger.debug(res); return res.ok ? res.json() : Promise.reject(res); }) .catch((error) => { var _a; this.logger.error(error); if ((_a = error.body) === null || _a === void 0 ? void 0 : _a.message) { this.logger.error(error.body.message); } throw new Error(`Unable to bundle interaction: ${JSON.stringify(error)}`); }); return { bundlrResponse: response, originalTxId: interactionTx.id }; } async createInteraction(input, tags, transfer, strict, bundle = false, vrf = false, reward) { if (this._evaluationOptions.internalWrites) { // Call contract and verify if there are any internal writes: // 1. Evaluate current contract state // 2. Apply input as "dry-run" transaction // 3. Verify the callStack and search for any "internalWrites" transactions // 4. For each found "internalWrite" transaction - generate additional tag: // {name: 'InternalWrite', value: callingContractTxId} const handlerResult = await this.callContract(input, undefined, undefined, tags, transfer); if (strict && handlerResult.type !== 'ok') { throw Error(`Cannot create interaction: ${handlerResult.errorMessage}`); } const callStack = this.getCallStack(); const innerWrites = this._innerWritesEvaluator.eval(callStack); this.logger.debug('Input', input); this.logger.debug('Callstack', callStack.print()); innerWrites.forEach((contractTxId) => { tags.push({ name: SmartWeaveTags_1.SmartWeaveTags.INTERACT_WRITE, value: contractTxId }); }); this.logger.debug('Tags with inner calls', tags); } else { if (strict) { const handlerResult = await this.callContract(input, undefined, undefined, tags, transfer); if (handlerResult.type !== 'ok') { throw Error(`Cannot create interaction: ${handlerResult.errorMessage}`); } } } if (vrf) { tags.push({ name: SmartWeaveTags_1.SmartWeaveTags.REQUEST_VRF, value: 'true' }); } const interactionTx = await (0, create_interaction_tx_1.createInteractionTx)(this.warp.arweave, this.signer, this._contractTxId, input, tags, transfer.target, transfer.winstonQty, bundle, reward); return interactionTx; } txId() { return this._contractTxId; } getCallStack() { return this._callStack; } connect(signer) { if (typeof signer == 'function') { this.signer = signer; } else { this.signer = async (tx) => { await this.warp.arweave.transactions.sign(tx, signer); }; } return this; } setEvaluationOptions(options) { this._evaluationOptions = { ...this._evaluationOptions, ...options }; return this; } async waitForConfirmation(transactionId) { const { arweave } = this.warp; const status = await arweave.transactions.getStatus(transactionId); if (status.confirmed === null) { this.logger.info(`Transaction ${transactionId} not yet confirmed. Waiting another 20 seconds before next check.`); await (0, utils_1.sleep)(20000); await this.waitForConfirmation(transactionId); } else { this.logger.info(`Transaction ${transactionId} confirmed`, status); return status; } } async createExecutionContext(contractTxId, upToSortKey, forceDefinitionLoad = false, interactions) { var _a; const { definitionLoader, interactionsLoader, executorFactory, stateEvaluator } = this.warp; const benchmark = Benchmark_1.Benchmark.measure(); const cachedState = await stateEvaluator.latestAvailableState(contractTxId, upToSortKey); this.logger.debug('cache lookup', benchmark.elapsed()); benchmark.reset(); const evolvedSrcTxId = Evolve_1.Evolve.evolvedSrcTxId((_a = cachedState === null || cachedState === void 0 ? void 0 : cachedState.cachedValue) === null || _a === void 0 ? void 0 : _a.state); let handler, contractDefinition, sortedInteractions; this.logger.debug('Cached state', cachedState, upToSortKey); if (cachedState && cachedState.sortKey == upToSortKey) { this.logger.debug('State fully cached, not loading interactions.'); if (forceDefinitionLoad || evolvedSrcTxId) { contractDefinition = await definitionLoader.load(contractTxId, evolvedSrcTxId); handler = (await executorFactory.create(contractDefinition, this._evaluationOptions)); } } else { [contractDefinition, sortedInteractions] = await Promise.all([ definitionLoader.load(contractTxId, evolvedSrcTxId), interactions ? Promise.resolve(interactions) : await interactionsLoader.load(contractTxId, cachedState === null || cachedState === void 0 ? void 0 : cachedState.sortKey, // (1) we want to eagerly load dependant contract interactions and put them // in the interactions' loader cache // see: https://github.com/warp-contracts/warp/issues/198 this.getToSortKey(upToSortKey), this._evaluationOptions) ]); // (2) ...but we still need to return only interactions up to original "upToSortKey" if (cachedState === null || cachedState === void 0 ? void 0 : cachedState.sortKey) { sortedInteractions = sortedInteractions.filter((i) => i.sortKey.localeCompare(cachedState === null || cachedState === void 0 ? void 0 : cachedState.sortKey) > 0); } if (upToSortKey) { sortedInteractions = sortedInteractions.filter((i) => i.sortKey.localeCompare(upToSortKey) <= 0); } this.logger.debug('contract and interactions load', benchmark.elapsed()); if (this._parentContract == null && sortedInteractions.length) { // note: if the root contract has zero interactions, it still should be safe // - as no other contracts will be called. this._rootSortKey = sortedInteractions[sortedInteractions.length - 1].sortKey; } handler = (await executorFactory.create(contractDefinition, this._evaluationOptions)); } return { warp: this.warp, contract: this, contractDefinition, sortedInteractions, evaluationOptions: this._evaluationOptions, handler, cachedState, requestedSortKey: upToSortKey }; } getToSortKey(upToSortKey) { var _a; if ((_a = this._parentContract) === null || _a === void 0 ? void 0 : _a.rootSortKey) { if (!upToSortKey) { return this._parentContract.rootSortKey; } return this._parentContract.rootSortKey.localeCompare(upToSortKey) > 0 ? this._parentContract.rootSortKey : upToSortKey; } else { return upToSortKey; } } async createExecutionContextFromTx(contractTxId, transaction) { const caller = transaction.owner.address; const sortKey = transaction.sortKey; const baseContext = await this.createExecutionContext(contractTxId, sortKey, true); return { ...baseContext, caller }; } maybeResetRootContract() { if (this._parentContract == null) { this.logger.debug('Clearing call stack for the root contract'); this._callStack = new ContractCallStack_1.ContractCallStack(this.txId(), 0); this._rootSortKey = null; this.warp.interactionsLoader.clearCache(); } } async callContract(input, caller, sortKey, tags = [], transfer = CreateContract_1.emptyTransfer) { this.logger.info('Call contract input', input); this.maybeResetRootContract(); if (!this.signer) { this.logger.warn('Wallet not set.'); } const { arweave, stateEvaluator } = this.warp; // create execution context let executionContext = await this.createExecutionContext(this._contractTxId, sortKey, true); const currentBlockData = this.warp.environment == 'mainnet' ? await this._arweaveWrapper.warpGwBlock() : await arweave.blocks.getCurrent(); // add caller info to execution context let effectiveCaller; if (caller) { effectiveCaller = caller; } else if (this.signer) { const dummyTx = await arweave.createTransaction({ data: Math.random().toString().slice(-4), reward: '72600854', last_tx: 'p7vc1iSP6bvH_fCeUFa9LqoV5qiyW-jdEKouAT0XMoSwrNraB9mgpi29Q10waEpO' }); await this.signer(dummyTx); effectiveCaller = await arweave.wallets.ownerToAddress(dummyTx.owner); } else { effectiveCaller = ''; } this.logger.info('effectiveCaller', effectiveCaller); executionContext = { ...executionContext, caller: effectiveCaller }; // eval current state const evalStateResult = await stateEvaluator.eval(executionContext, []); this.logger.info('Current state', evalStateResult.cachedValue.state); // create interaction transaction const interaction = { input, caller: executionContext.caller }; this.logger.debug('interaction', interaction); const tx = await (0, create_interaction_tx_1.createInteractionTx)(arweave, this.signer, this._contractTxId, input, tags, transfer.target, transfer.winstonQty, true); const dummyTx = (0, create_interaction_tx_1.createDummyTx)(tx, executionContext.caller, currentBlockData); this.logger.debug('Creating sortKey for', { blockId: dummyTx.block.id, id: dummyTx.id, height: dummyTx.block.height }); dummyTx.sortKey = await this._sorter.createSortKey(dummyTx.block.id, dummyTx.id, dummyTx.block.height, true); const handleResult = await this.evalInteraction({ interaction, interactionTx: dummyTx, currentTx: [] }, executionContext, evalStateResult.cachedValue); if (handleResult.type !== 'ok') { this.logger.fatal('Error while interacting with contract', { type: handleResult.type, error: handleResult.errorMessage }); } return handleResult; } async callContractForTx(input, interactionTx, currentTx) { this.maybeResetRootContract(); const executionContext = await this.createExecutionContextFromTx(this._contractTxId, interactionTx); const evalStateResult = await this.warp.stateEvaluator.eval(executionContext, currentTx); this.logger.debug('callContractForTx - evalStateResult', { result: evalStateResult.cachedValue.state, txId: this._contractTxId }); const interaction = { input, caller: this._parentContract.txId() }; const interactionData = { interaction, interactionTx, currentTx }; const result = await this.evalInteraction(interactionData, executionContext, evalStateResult.cachedValue); result.originalValidity = evalStateResult.cachedValue.validity; result.originalErrorMessages = evalStateResult.cachedValue.errorMessages; return result; } async evalInteraction(interactionData, executionContext, evalStateResult) { const interactionCall = this.getCallStack().addInteractionData(interactionData); const benchmark = Benchmark_1.Benchmark.measure(); const result = await executionContext.handler.handle(executionContext, evalStateResult, interactionData); interactionCall.update({ cacheHit: false, outputState: this._evaluationOptions.stackTrace.saveState ? result.state : undefined, executionTime: benchmark.elapsed(true), valid: result.type === 'ok', errorMessage: result.errorMessage, gasUsed: result.gasUsed }); return result; } parent() { return this._parentContract; } callDepth() { return this._callDepth; } evaluationOptions() { return this._evaluationOptions; } lastReadStateStats() { return this._benchmarkStats; } stateHash(state) { const jsonState = (0, safe_stable_stringify_1.default)(state); // note: cannot reuse: // "The Hash object can not be used again after hash.digest() method has been called. // Multiple calls will cause an error to be thrown." const hash = crypto.createHash('sha256'); hash.update(jsonState); return hash.digest('hex'); } async syncState(externalUrl, params) { const { stateEvaluator } = this.warp; const response = await fetch(`${externalUrl}?${new URLSearchParams({ id: this._contractTxId, ...params })}`) .then((res) => { return res.ok ? res.json() : Promise.reject(res); }) .catch((error) => { var _a, _b; if ((_a = error.body) === null || _a === void 0 ? void 0 : _a.message) { this.logger.error(error.body.message); } throw new Error(`Unable to retrieve state. ${error.status}: ${(_b = error.body) === null || _b === void 0 ? void 0 : _b.message}`); }); await stateEvaluator.syncState(this._contractTxId, response.sortKey, response.state, response.validity); return this; } async evolve(newSrcTxId, options) { return await this.writeInteraction({ function: 'evolve', value: newSrcTxId }, options); } async save(sourceData) { if (!this.signer) { throw new Error("Wallet not connected. Use 'connect' method first."); } const { arweave } = this.warp; const source = new SourceImpl_1.SourceImpl(arweave); const srcTx = await source.save(sourceData, this.signer); return srcTx.id; } get callingInteraction() { return this._callingInteraction; } get rootSortKey() { return this._rootSortKey; } } exports.HandlerBasedContract = HandlerBasedContract; //# sourceMappingURL=HandlerBasedContract.js.map /***/ }), /***/ 8102: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InnerWritesEvaluator = void 0; class InnerWritesEvaluator { eval(callStack) { const result = []; callStack.interactions.forEach((interaction) => { this.evalForeignCalls(callStack.contractTxId, interaction, result); }); return result; } evalForeignCalls(rootContractTxId, interaction, result) { interaction.interactionInput.foreignContractCalls.forEach((foreignContractCall) => { foreignContractCall.interactions.forEach((foreignInteraction) => { if (foreignInteraction.interactionInput.dryWrite && !result.includes(foreignContractCall.contractTxId) && rootContractTxId !== foreignContractCall.contractTxId /*"write-backs"*/) { result.push(foreignContractCall.contractTxId); } this.evalForeignCalls(rootContractTxId, foreignInteraction, result); }); }); } } exports.InnerWritesEvaluator = InnerWritesEvaluator; //# sourceMappingURL=InnerWritesEvaluator.js.map /***/ }), /***/ 7665: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=PstContract.js.map /***/ }), /***/ 7819: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PstContractImpl = void 0; const HandlerBasedContract_1 = __webpack_require__(9692); class PstContractImpl extends HandlerBasedContract_1.HandlerBasedContract { async currentBalance(target) { const interactionResult = await this.viewState({ function: 'balance', target }); if (interactionResult.type !== 'ok') { throw Error(interactionResult.errorMessage); } return interactionResult.result; } async currentState() { return (await super.readState()).cachedValue.state; } async transfer(transfer, options) { return await this.writeInteraction({ function: 'transfer', ...transfer }, options); } } exports.PstContractImpl = PstContractImpl; //# sourceMappingURL=PstContractImpl.js.map /***/ }), /***/ 3611: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.emptyTransfer = void 0; exports.emptyTransfer = { target: '', winstonQty: '0' }; //# sourceMappingURL=CreateContract.js.map /***/ }), /***/ 4722: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=Source.js.map /***/ }), /***/ 5731: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DefaultCreateContract = void 0; const SmartWeaveTags_1 = __webpack_require__(7312); const WarpFactory_1 = __webpack_require__(8479); const LoggerFactory_1 = __webpack_require__(5913); const SourceImpl_1 = __webpack_require__(4217); class DefaultCreateContract { constructor(arweave, warp) { this.arweave = arweave; this.warp = warp; this.logger = LoggerFactory_1.LoggerFactory.INST.create('DefaultCreateContract'); this.deployFromSourceTx = this.deployFromSourceTx.bind(this); } async deploy(contractData, disableBundling) { const { wallet, initState, tags, transfer, data } = contractData; const effectiveUseBundler = disableBundling == undefined ? this.warp.definitionLoader.type() == 'warp' : !disableBundling; const source = new SourceImpl_1.SourceImpl(this.arweave); const srcTx = await source.save(contractData, wallet, effectiveUseBundler); this.logger.debug('Creating new contract'); return await this.deployFromSourceTx({ srcTxId: srcTx.id, wallet, initState, tags, transfer, data }, !effectiveUseBundler, srcTx); } async deployFromSourceTx(contractData, disableBundling, srcTx = null) { this.logger.debug('Creating new contract from src tx'); const { wallet, srcTxId, initState, tags, transfer, data } = contractData; const effectiveUseBundler = disableBundling == undefined ? this.warp.definitionLoader.type() == 'warp' : !disableBundling; let contractTX = await this.arweave.createTransaction({ data: (data === null || data === void 0 ? void 0 : data.body) || initState }, wallet); if (+(transfer === null || transfer === void 0 ? void 0 : transfer.winstonQty) > 0 && transfer.target.length) { this.logger.debug('Creating additional transaction with AR transfer', transfer); contractTX = await this.arweave.createTransaction({ data: (data === null || data === void 0 ? void 0 : data.body) || initState, target: transfer.target, quantity: transfer.winstonQty }, wallet); } if (tags === null || tags === void 0 ? void 0 : tags.length) { for (const tag of tags) { contractTX.addTag(tag.name.toString(), tag.value.toString()); } } contractTX.addTag(SmartWeaveTags_1.SmartWeaveTags.APP_NAME, 'SmartWeaveContract'); contractTX.addTag(SmartWeaveTags_1.SmartWeaveTags.APP_VERSION, '0.3.0'); contractTX.addTag(SmartWeaveTags_1.SmartWeaveTags.CONTRACT_SRC_TX_ID, srcTxId); contractTX.addTag(SmartWeaveTags_1.SmartWeaveTags.SDK, 'RedStone'); if (data) { contractTX.addTag(SmartWeaveTags_1.SmartWeaveTags.CONTENT_TYPE, data['Content-Type']); contractTX.addTag(SmartWeaveTags_1.SmartWeaveTags.INIT_STATE, initState); } else { contractTX.addTag(SmartWeaveTags_1.SmartWeaveTags.CONTENT_TYPE, 'application/json'); } await this.arweave.transactions.sign(contractTX, wallet); let responseOk; let response; if (effectiveUseBundler) { const result = await this.post(contractTX, srcTx); this.logger.debug(result); responseOk = true; } else { response = await this.arweave.transactions.post(contractTX); responseOk = response.status === 200 || response.status === 208; } if (responseOk) { return { contractTxId: contractTX.id, srcTxId }; } else { throw new Error(`Unable to write Contract. Arweave responded with status ${response.status}: ${response.statusText}`); } } async post(contractTx, srcTx = null) { let body = { contractTx }; if (srcTx) { body = { ...body, srcTx }; } const response = await fetch(`${WarpFactory_1.WARP_GW_URL}/gateway/contracts/deploy`, { method: 'POST', body: JSON.stringify(body), headers: { 'Accept-Encoding': 'gzip, deflate, br', 'Content-Type': 'application/json', Accept: 'application/json' } }); if (response.ok) { return response.json(); } else { throw new Error(`Error while posting contract. Sequencer responded with status ${response.status} ${response.statusText}`); } } } exports.DefaultCreateContract = DefaultCreateContract; //# sourceMappingURL=DefaultCreateContract.js.map /***/ }), /***/ 4217: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(8764)["Buffer"]; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SourceImpl = void 0; /* eslint-disable */ const redstone_wasm_metering_1 = __importDefault(__webpack_require__(8060)); const go_wasm_imports_1 = __webpack_require__(7170); const fs_1 = __importDefault(__webpack_require__(9827)); const wasm_bindgen_tools_1 = __webpack_require__(4742); const SmartWeaveTags_1 = __webpack_require__(7312); const LoggerFactory_1 = __webpack_require__(5913); const wasmTypeMapping = new Map([ [1, 'assemblyscript'], [2, 'rust'], [3, 'go'] /*[4, 'swift'], [5, 'c']*/ ]); class SourceImpl { constructor(arweave) { this.arweave = arweave; this.logger = LoggerFactory_1.LoggerFactory.INST.create('Source'); } async save(contractData, signer, useBundler = false) { this.logger.debug('Creating new contract source'); const { src, wasmSrcCodeDir, wasmGlueCode } = contractData; const contractType = src instanceof Buffer ? 'wasm' : 'js'; let srcTx; let wasmLang = null; let wasmVersion = null; const metadata = {}; const data = []; if (contractType == 'wasm') { const meteredWasmBinary = redstone_wasm_metering_1.default.meterWASM(src, { meterType: 'i32' }); data.push(meteredWasmBinary); const wasmModule = await WebAssembly.compile(src); const moduleImports = WebAssembly.Module.imports(wasmModule); let lang; if (this.isGoModule(moduleImports)) { const go = new go_wasm_imports_1.Go(null); const module = new WebAssembly.Instance(wasmModule, go.importObject); // DO NOT await here! go.run(module); lang = go.exports.lang(); wasmVersion = go.exports.version(); } else { const module = await WebAssembly.instantiate(src, dummyImports(moduleImports)); // @ts-ignore if (!module.instance.exports.lang) { throw new Error(`No info about source type in wasm binary. Did you forget to export "lang" function?`); } // @ts-ignore lang = module.instance.exports.lang(); // @ts-ignore wasmVersion = module.instance.exports.version(); if (!wasmTypeMapping.has(lang)) { throw new Error(`Unknown wasm source type ${lang}`); } } wasmLang = wasmTypeMapping.get(lang); if (wasmSrcCodeDir == null) { throw new Error('No path to original wasm contract source code'); } const zippedSourceCode = await this.zipContents(wasmSrcCodeDir); data.push(zippedSourceCode); if (wasmLang == 'rust') { if (!wasmGlueCode) { throw new Error('No path to generated wasm-bindgen js code'); } const wasmBindgenSrc = fs_1.default.readFileSync(wasmGlueCode, 'utf-8'); const dtor = (0, wasm_bindgen_tools_1.matchMutClosureDtor)(wasmBindgenSrc); metadata['dtor'] = parseInt(dtor); data.push(Buffer.from(wasmBindgenSrc)); } } const allData = contractType == 'wasm' ? this.joinBuffers(data) : src; if (typeof signer == 'function') { srcTx = await this.arweave.createTransaction({ data: allData }); } else { srcTx = await this.arweave.createTransaction({ data: allData }, signer); } srcTx.addTag(SmartWeaveTags_1.SmartWeaveTags.APP_NAME, 'SmartWeaveContractSource'); // TODO: version should be taken from the current package.json version. srcTx.addTag(SmartWeaveTags_1.SmartWeaveTags.APP_VERSION, '0.3.0'); srcTx.addTag(SmartWeaveTags_1.SmartWeaveTags.SDK, 'Warp'); srcTx.addTag(SmartWeaveTags_1.SmartWeaveTags.CONTENT_TYPE, contractType == 'js' ? 'application/javascript' : 'application/wasm'); if (contractType == 'wasm') { srcTx.addTag(SmartWeaveTags_1.SmartWeaveTags.WASM_LANG, wasmLang); srcTx.addTag(SmartWeaveTags_1.SmartWeaveTags.WASM_LANG_VERSION, wasmVersion); srcTx.addTag(SmartWeaveTags_1.SmartWeaveTags.WASM_META, JSON.stringify(metadata)); } if (typeof signer == 'function') { await signer(srcTx); } else { await this.arweave.transactions.sign(srcTx, signer); } this.logger.debug('Posting transaction with source'); // note: in case of useBundler = true, we're posting both // src tx and contract tx in one request. let responseOk = true; let response; if (!useBundler) { response = await this.arweave.transactions.post(srcTx); responseOk = response.status === 200 || response.status === 208; } if (responseOk) { return srcTx; } else { throw new Error(`Unable to write Contract Source. Arweave responded with status ${response.status}: ${response.statusText}`); } } isGoModule(moduleImports) { return moduleImports.some((moduleImport) => { return moduleImport.module == 'env' && moduleImport.name.startsWith('syscall/js'); }); } joinBuffers(buffers) { const length = buffers.length; const result = []; result.push(Buffer.from(length.toString())); result.push(Buffer.from('|')); buffers.forEach((b) => { result.push(Buffer.from(b.length.toString())); result.push(Buffer.from('|')); }); result.push(...buffers); return result.reduce((prev, b) => Buffer.concat([prev, b])); } async zipContents(source) { const archiver = __webpack_require__(1445), streamBuffers = __webpack_require__(4034); const outputStreamBuffer = new streamBuffers.WritableStreamBuffer({ initialSize: 1000 * 1024, incrementAmount: 1000 * 1024 // grow by 1000 kilobytes each time buffer overflows. }); const archive = archiver('zip', { zlib: { level: 9 } // Sets the compression level. }); archive.on('error', function (err) { throw err; }); archive.pipe(outputStreamBuffer); archive.directory(source.toString(), source.toString()); await archive.finalize(); outputStreamBuffer.end(); return outputStreamBuffer.getContents(); } } exports.SourceImpl = SourceImpl; function dummyImports(moduleImports) { const imports = {}; moduleImports.forEach((moduleImport) => { if (!Object.prototype.hasOwnProperty.call(imports, moduleImport.module)) { imports[moduleImport.module] = {}; } imports[moduleImport.module][moduleImport.name] = function () { }; }); return imports; } //# sourceMappingURL=SourceImpl.js.map /***/ }), /***/ 3667: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MigrationTool = void 0; const LexicographicalInteractionsSorter_1 = __webpack_require__(1967); const StateEvaluator_1 = __webpack_require__(7462); const knex_1 = __importDefault(__webpack_require__(771)); const LoggerFactory_1 = __webpack_require__(5913); class MigrationTool { constructor(arweave, levelDb) { this.arweave = arweave; this.levelDb = levelDb; this.logger = LoggerFactory_1.LoggerFactory.INST.create('MigrationTool'); this.sorter = new LexicographicalInteractionsSorter_1.LexicographicalInteractionsSorter(arweave); } async migrateSqlite(sqlitePath) { this.logger.info(`Migrating from sqlite ${sqlitePath} to leveldb.`); const knexDb = (0, knex_1.default)({ client: 'sqlite3', connection: { filename: sqlitePath }, useNullAsDefault: true }); const cache = await knexDb .select(['contract_id', 'height', 'state']) .from('states') .max('height') .groupBy(['contract_id']); this.logger.info(`Migrating ${cache === null || cache === void 0 ? void 0 : cache.length} contracts' state`); const result = []; for (const entry of cache) { const contractTxId = entry['contract_id']; const height = entry['height']; const state = JSON.parse(entry['state']); const sortKey = this.sorter.generateLastSortKey(parseInt(height)); this.logger.debug(`Migrating ${contractTxId} at height ${height}: ${sortKey}`); await this.levelDb.put({ contractTxId, sortKey }, new StateEvaluator_1.EvalStateResult(state.state, state.validity, {})); result.push({ contractTxId, height, sortKey }); } this.logger.info(`Migration done.`); return result; } } exports.MigrationTool = MigrationTool; //# sourceMappingURL=MigrationTool.js.map /***/ }), /***/ 4464: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Testing = void 0; class Testing { constructor(arweave) { this.arweave = arweave; } async mineBlock() { this.validateEnv(); await this.arweave.api.get('mine'); } async generateWallet() { this.validateEnv(); const wallet = await this.arweave.wallets.generate(); await this.addFunds(wallet); return wallet; } async addFunds(wallet) { const walletAddress = await this.arweave.wallets.getAddress(wallet); await this.arweave.api.get(`/mint/${walletAddress}/1000000000000000`); } validateEnv() { if (this.arweave.api.getConfig().host.includes('arweave')) { throw new Error('Testing features are not available in a non testing environment'); } } } exports.Testing = Testing; //# sourceMappingURL=Testing.js.map /***/ }), /***/ 5614: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InteractionOutput = exports.InteractionInput = exports.InteractionCall = exports.ContractCallStack = void 0; const utils_1 = __webpack_require__(5082); class ContractCallStack { constructor(contractTxId, depth, label = '') { this.contractTxId = contractTxId; this.depth = depth; this.label = label; this.interactions = new Map(); } addInteractionData(interactionData) { const { interaction, interactionTx } = interactionData; const interactionCall = InteractionCall.create(new InteractionInput(interactionTx.id, interactionTx.sortKey, interactionTx.block.height, interactionTx.block.timestamp, interaction === null || interaction === void 0 ? void 0 : interaction.caller, interaction === null || interaction === void 0 ? void 0 : interaction.input.function, interaction === null || interaction === void 0 ? void 0 : interaction.input, interactionTx.dry, new Map())); this.interactions.set(interactionTx.id, interactionCall); return interactionCall; } getInteraction(txId) { return this.interactions.get(txId); } print() { return JSON.stringify(this, utils_1.mapReplacer); } } exports.ContractCallStack = ContractCallStack; class InteractionCall { constructor(interactionInput) { this.interactionInput = interactionInput; } static create(interactionInput) { return new InteractionCall(interactionInput); } update(interactionOutput) { this.interactionOutput = interactionOutput; } } exports.InteractionCall = InteractionCall; class InteractionInput { constructor(txId, sortKey, blockHeight, blockTimestamp, caller, functionName, functionArguments, dryWrite, foreignContractCalls = new Map()) { this.txId = txId; this.sortKey = sortKey; this.blockHeight = blockHeight; this.blockTimestamp = blockTimestamp; this.caller = caller; this.functionName = functionName; this.functionArguments = functionArguments; this.dryWrite = dryWrite; this.foreignContractCalls = foreignContractCalls; } } exports.InteractionInput = InteractionInput; class InteractionOutput { constructor(cacheHit, outputState, executionTime, valid, errorMessage = '', gasUsed) { this.cacheHit = cacheHit; this.outputState = outputState; this.executionTime = executionTime; this.valid = valid; this.errorMessage = errorMessage; this.gasUsed = gasUsed; } } exports.InteractionOutput = InteractionOutput; //# sourceMappingURL=ContractCallStack.js.map /***/ }), /***/ 9305: /***/ (function(__unused_webpack_module, exports) { "use strict"; /** * This type contains all data and meta-data of the given contact. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContractMetadata = void 0; class ContractMetadata { } exports.ContractMetadata = ContractMetadata; //# sourceMappingURL=ContractDefinition.js.map /***/ }), /***/ 4805: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=ExecutionContext.js.map /***/ }), /***/ 8632: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=ExecutionContextModifier.js.map /***/ }), /***/ 7312: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SmartWeaveTags = void 0; /** * Definition of all transaction tags used by the SmartWeave "protocol" */ var SmartWeaveTags; (function (SmartWeaveTags) { SmartWeaveTags["APP_NAME"] = "App-Name"; SmartWeaveTags["APP_VERSION"] = "App-Version"; SmartWeaveTags["CONTRACT_TX_ID"] = "Contract"; SmartWeaveTags["INPUT"] = "Input"; SmartWeaveTags["CONTENT_TYPE"] = "Content-Type"; SmartWeaveTags["CONTRACT_SRC_TX_ID"] = "Contract-Src"; SmartWeaveTags["SDK"] = "SDK"; SmartWeaveTags["MIN_FEE"] = "Min-Fee"; SmartWeaveTags["INIT_STATE"] = "Init-State"; SmartWeaveTags["INIT_STATE_TX"] = "Init-State-TX"; SmartWeaveTags["INTERACT_WRITE"] = "Interact-Write"; SmartWeaveTags["WASM_LANG"] = "Wasm-Lang"; SmartWeaveTags["WASM_LANG_VERSION"] = "Wasm-Lang-Version"; SmartWeaveTags["WASM_META"] = "Wasm-Meta"; SmartWeaveTags["REQUEST_VRF"] = "Request-Vrf"; })(SmartWeaveTags = exports.SmartWeaveTags || (exports.SmartWeaveTags = {})); //# sourceMappingURL=SmartWeaveTags.js.map /***/ }), /***/ 2009: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Warp = void 0; const DefaultCreateContract_1 = __webpack_require__(5731); const HandlerBasedContract_1 = __webpack_require__(9692); const PstContractImpl_1 = __webpack_require__(7819); const MigrationTool_1 = __webpack_require__(3667); const Testing_1 = __webpack_require__(4464); const WarpBuilder_1 = __webpack_require__(9689); /** * The Warp "motherboard" ;-). * This is the base class that supplies the implementation of the SmartWeave protocol * Allows to plug-in different implementation of all the modules defined in the constructor. * * After being fully configured, it allows to "connect" to * contract and perform operations on them (see {@link Contract}) */ class Warp { constructor(arweave, levelDb, definitionLoader, interactionsLoader, executorFactory, stateEvaluator, environment = 'custom') { this.arweave = arweave; this.levelDb = levelDb; this.definitionLoader = definitionLoader; this.interactionsLoader = interactionsLoader; this.executorFactory = executorFactory; this.stateEvaluator = stateEvaluator; this.environment = environment; this.createContract = new DefaultCreateContract_1.DefaultCreateContract(arweave, this); this.migrationTool = new MigrationTool_1.MigrationTool(arweave, levelDb); this.testing = new Testing_1.Testing(arweave); } static builder(arweave, cache, environment) { return new WarpBuilder_1.WarpBuilder(arweave, cache, environment); } /** * Allows to connect to any contract using its transaction id. * @param contractTxId * @param callingContract */ contract(contractTxId, callingContract, callingInteraction) { return new HandlerBasedContract_1.HandlerBasedContract(contractTxId, this, callingContract, callingInteraction); } /** * Allows to connect to a contract that conforms to the Profit Sharing Token standard * @param contractTxId */ pst(contractTxId) { return new PstContractImpl_1.PstContractImpl(contractTxId, this); } } exports.Warp = Warp; //# sourceMappingURL=Warp.js.map /***/ }), /***/ 9689: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WarpBuilder = void 0; const MemCache_1 = __webpack_require__(1200); const DebuggableExecutorFactor_1 = __webpack_require__(4481); const ArweaveGatewayInteractionsLoader_1 = __webpack_require__(9564); const CacheableInteractionsLoader_1 = __webpack_require__(7346); const ContractDefinitionLoader_1 = __webpack_require__(7089); const WarpGatewayContractDefinitionLoader_1 = __webpack_require__(3187); const WarpGatewayInteractionsLoader_1 = __webpack_require__(1533); const Warp_1 = __webpack_require__(2009); class WarpBuilder { constructor(_arweave, _cache, _environment = 'custom') { this._arweave = _arweave; this._cache = _cache; this._environment = _environment; } setDefinitionLoader(value) { this._definitionLoader = value; return this; } setInteractionsLoader(value) { this._interactionsLoader = value; return this; } setExecutorFactory(value) { this._executorFactory = value; return this; } setStateEvaluator(value) { this._stateEvaluator = value; return this; } overwriteSource(sourceCode) { if (this._executorFactory == null) { throw new Error('Set base ExecutorFactory first'); } this._executorFactory = new DebuggableExecutorFactor_1.DebuggableExecutorFactory(this._executorFactory, sourceCode); return this.build(); } useWarpGateway(gatewayOptions) { this._interactionsLoader = new CacheableInteractionsLoader_1.CacheableInteractionsLoader(new WarpGatewayInteractionsLoader_1.WarpGatewayInteractionsLoader(gatewayOptions.address, gatewayOptions.confirmationStatus, gatewayOptions.source)); this._definitionLoader = new WarpGatewayContractDefinitionLoader_1.WarpGatewayContractDefinitionLoader(gatewayOptions.address, this._arweave, new MemCache_1.MemCache()); return this; } useArweaveGateway() { this._definitionLoader = new ContractDefinitionLoader_1.ContractDefinitionLoader(this._arweave, new MemCache_1.MemCache()); this._interactionsLoader = new CacheableInteractionsLoader_1.CacheableInteractionsLoader(new ArweaveGatewayInteractionsLoader_1.ArweaveGatewayInteractionsLoader(this._arweave)); return this; } build() { return new Warp_1.Warp(this._arweave, this._cache, this._definitionLoader, this._interactionsLoader, this._executorFactory, this._stateEvaluator, this._environment); } } exports.WarpBuilder = WarpBuilder; //# sourceMappingURL=WarpBuilder.js.map /***/ }), /***/ 8479: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WarpFactory = exports.defaultCacheOptions = exports.DEFAULT_LEVEL_DB_LOCATION = exports.defaultWarpGwOptions = exports.WARP_GW_URL = void 0; const arweave_1 = __importDefault(__webpack_require__(7386)); const LevelDbCache_1 = __webpack_require__(7563); const MemCache_1 = __webpack_require__(1200); const CacheableExecutorFactory_1 = __webpack_require__(7794); const Evolve_1 = __webpack_require__(2491); const CacheableStateEvaluator_1 = __webpack_require__(4286); const HandlerExecutorFactory_1 = __webpack_require__(9174); const Warp_1 = __webpack_require__(2009); exports.WARP_GW_URL = 'https://d1o5nlqr4okus2.cloudfront.net'; exports.defaultWarpGwOptions = { confirmationStatus: { notCorrupted: true }, source: null, address: exports.WARP_GW_URL }; exports.DEFAULT_LEVEL_DB_LOCATION = './cache/warp'; exports.defaultCacheOptions = { inMemory: false, dbLocation: exports.DEFAULT_LEVEL_DB_LOCATION }; /** * A factory that simplifies the process of creating different versions of {@link Warp}. * All versions use the {@link Evolve} plugin. */ class WarpFactory { /** * creates a Warp instance suitable for testing in a local environment * (e.g. usually using ArLocal) * @param arweave - an instance of Arweave * @param cacheOptions - optional cache options. By default, the in-memory cache is used. */ static forLocal(port = 1984, arweave = arweave_1.default.init({ host: 'localhost', port: port, protocol: 'http' }), cacheOptions = { ...exports.defaultCacheOptions, inMemory: true }) { return this.customArweaveGw(arweave, cacheOptions, 'local'); } /** * creates a Warp instance suitable for testing * with Warp testnet (https://testnet.redstone.tools/) */ static forTestnet(arweave = arweave_1.default.init({ host: 'testnet.redstone.tools', port: 443, protocol: 'https' }), cacheOptions = exports.defaultCacheOptions) { return this.customArweaveGw(arweave, cacheOptions, 'testnet'); } /** * creates a Warp instance suitable for use with mainnet. * By default, the Warp gateway (https://github.com/warp-contracts/gateway#warp-gateway) * is being used for: * 1. deploying contracts * 2. writing new transactions through Warp Sequencer * 3. loading contract interactions * * @param cacheOptions - cache options, defaults {@link defaultCacheOptions} * @param useArweaveGw - use arweave.net gateway for deploying contracts, * writing and loading interactions * @param arweave - custom Arweave instance */ static forMainnet(cacheOptions = exports.defaultCacheOptions, useArweaveGw = false, arweave = arweave_1.default.init({ host: 'arweave.net', port: 443, protocol: 'https' })) { if (useArweaveGw) { return this.customArweaveGw(arweave, cacheOptions, 'mainnet'); } else { console.log(exports.defaultWarpGwOptions); return this.customWarpGw(arweave, exports.defaultWarpGwOptions, cacheOptions, 'mainnet'); } } /** * returns an instance of {@link WarpBuilder} that allows to fully customize the Warp instance. * @param arweave * @param cacheOptions */ static custom(arweave, cacheOptions, environment) { const cache = new LevelDbCache_1.LevelDbCache({ ...cacheOptions, dbLocation: `${cacheOptions.dbLocation}/state` }); const executorFactory = new CacheableExecutorFactory_1.CacheableExecutorFactory(arweave, new HandlerExecutorFactory_1.HandlerExecutorFactory(arweave), new MemCache_1.MemCache()); const stateEvaluator = new CacheableStateEvaluator_1.CacheableStateEvaluator(arweave, cache, [new Evolve_1.Evolve()]); return Warp_1.Warp.builder(arweave, cache, environment) .setExecutorFactory(executorFactory) .setStateEvaluator(stateEvaluator); } static customArweaveGw(arweave, cacheOptions = exports.defaultCacheOptions, environment) { return this.custom(arweave, cacheOptions, environment).useArweaveGateway().build(); } static customWarpGw(arweave, gatewayOptions = exports.defaultWarpGwOptions, cacheOptions = exports.defaultCacheOptions, environment) { return this.custom(arweave, cacheOptions, environment).useWarpGateway(gatewayOptions).build(); } } exports.WarpFactory = WarpFactory; //# sourceMappingURL=WarpFactory.js.map /***/ }), /***/ 2656: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=DefinitionLoader.js.map /***/ }), /***/ 5368: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=ExecutorFactory.js.map /***/ }), /***/ 5765: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=InteractionsLoader.js.map /***/ }), /***/ 6769: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=InteractionsSorter.js.map /***/ }), /***/ 7462: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DefaultEvaluationOptions = exports.EvalStateResult = void 0; class EvalStateResult { constructor(state, validity, errorMessages) { this.state = state; this.validity = validity; this.errorMessages = errorMessages; } } exports.EvalStateResult = EvalStateResult; class DefaultEvaluationOptions { constructor() { // default = true - still cannot decide whether true or false should be the default. // "false" may lead to some fairly simple attacks on contract, if the contract // does not properly validate input data. // "true" may lead to wrongly calculated state, even without noticing the problem // (eg. when using unsafe client and Arweave does not respond properly for a while) this.ignoreExceptions = true; this.waitForConfirmation = false; this.updateCacheForEachInteraction = false; this.internalWrites = false; this.maxCallDepth = 7; // your lucky number... this.maxInteractionEvaluationTimeSeconds = 60; this.stackTrace = { saveState: false }; this.bundlerUrl = `https://d1o5nlqr4okus2.cloudfront.net/`; this.gasLimit = Number.MAX_SAFE_INTEGER; this.useFastCopy = true; this.useVM2 = false; this.allowUnsafeClient = false; this.allowBigInt = false; this.walletBalanceUrl = 'http://nyc-1.dev.arweave.net:1984/'; this.mineArLocalBlocks = true; } } exports.DefaultEvaluationOptions = DefaultEvaluationOptions; //# sourceMappingURL=StateEvaluator.js.map /***/ }), /***/ 9564: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ArweaveGatewayInteractionsLoader = exports.bundledTxsFilter = void 0; const SmartWeaveTags_1 = __webpack_require__(7312); const Benchmark_1 = __webpack_require__(9106); const LoggerFactory_1 = __webpack_require__(5913); const ArweaveWrapper_1 = __webpack_require__(9360); const utils_1 = __webpack_require__(5082); const LexicographicalInteractionsSorter_1 = __webpack_require__(1967); const MAX_REQUEST = 100; function bundledTxsFilter(tx) { var _a, _b; return !((_a = tx.node.parent) === null || _a === void 0 ? void 0 : _a.id) && !((_b = tx.node.bundledIn) === null || _b === void 0 ? void 0 : _b.id); } exports.bundledTxsFilter = bundledTxsFilter; class ArweaveGatewayInteractionsLoader { constructor(arweave) { this.arweave = arweave; this.logger = LoggerFactory_1.LoggerFactory.INST.create('ArweaveGatewayInteractionsLoader'); this.arweaveWrapper = new ArweaveWrapper_1.ArweaveWrapper(arweave); this.sorter = new LexicographicalInteractionsSorter_1.LexicographicalInteractionsSorter(arweave); } async load(contractId, fromSortKey, toSortKey, evaluationOptions) { this.logger.debug('Loading interactions for', { contractId, fromSortKey, toSortKey }); const fromBlockHeight = this.sorter.extractBlockHeight(fromSortKey); const toBlockHeight = this.sorter.extractBlockHeight(toSortKey); const mainTransactionsVariables = { tags: [ { name: SmartWeaveTags_1.SmartWeaveTags.APP_NAME, values: ['SmartWeaveAction'] }, { name: SmartWeaveTags_1.SmartWeaveTags.CONTRACT_TX_ID, values: [contractId] } ], blockFilter: { min: fromBlockHeight, max: toBlockHeight }, first: MAX_REQUEST }; const loadingBenchmark = Benchmark_1.Benchmark.measure(); let interactions = await this.loadPages(mainTransactionsVariables); loadingBenchmark.stop(); if (evaluationOptions.internalWrites) { const innerWritesVariables = { tags: [ { name: SmartWeaveTags_1.SmartWeaveTags.INTERACT_WRITE, values: [contractId] } ], blockFilter: { min: fromBlockHeight, max: toBlockHeight }, first: MAX_REQUEST }; const innerWritesInteractions = await this.loadPages(innerWritesVariables); this.logger.debug('Inner writes interactions length:', innerWritesInteractions.length); interactions = interactions.concat(innerWritesInteractions); } /** * Because the behaviour of the Arweave gateway in case of passing null to min/max block height * in the gql query params is unknown (https://discord.com/channels/908759493943394334/908766823342801007/983643012947144725) * - we're removing all the interactions, that have null block data. */ interactions = interactions.filter((i) => i.node.block && i.node.block.id && i.node.block.height); // note: this operation adds the "sortKey" to the interactions let sortedInteractions = await this.sorter.sort(interactions); if (fromSortKey && toSortKey) { sortedInteractions = sortedInteractions.filter((i) => { return i.node.sortKey.localeCompare(fromSortKey) > 0 && i.node.sortKey.localeCompare(toSortKey) <= 0; }); } else if (fromSortKey && !toSortKey) { sortedInteractions = sortedInteractions.filter((i) => { return i.node.sortKey.localeCompare(fromSortKey) > 0; }); } else if (!fromSortKey && toSortKey) { sortedInteractions = sortedInteractions.filter((i) => { return i.node.sortKey.localeCompare(toSortKey) <= 0; }); } this.logger.debug('All loaded interactions:', { from: fromSortKey, to: toSortKey, loaded: sortedInteractions.length, time: loadingBenchmark.elapsed() }); return sortedInteractions.map((i) => i.node); } async loadPages(variables) { let transactions = await this.getNextPage(variables); // note: according to https://discord.com/channels/357957786904166400/756557551234973696/920918240702660638 // protection against "bundledIn" should not be necessary..but..better safe than sorry :-) // note: it will be now necessary - with RedStone Sequencer const txInfos = transactions.edges.filter((tx) => bundledTxsFilter(tx)); while (transactions.pageInfo.hasNextPage) { const cursor = transactions.edges[MAX_REQUEST - 1].cursor; variables = { ...variables, after: cursor }; transactions = await this.getNextPage(variables); txInfos.push(...transactions.edges.filter((tx) => bundledTxsFilter(tx))); } return txInfos; } async getNextPage(variables) { const benchmark = Benchmark_1.Benchmark.measure(); let response = await this.arweaveWrapper.gql(ArweaveGatewayInteractionsLoader.query, variables); this.logger.debug('GQL page load:', benchmark.elapsed()); while (response.status === 403) { this.logger.warn(`GQL rate limiting, waiting ${ArweaveGatewayInteractionsLoader._30seconds}ms before next try.`); await (0, utils_1.sleep)(ArweaveGatewayInteractionsLoader._30seconds); response = await this.arweaveWrapper.gql(ArweaveGatewayInteractionsLoader.query, variables); } if (response.status !== 200) { throw new Error(`Unable to retrieve transactions. Arweave gateway responded with status ${response.status}.`); } if (response.data.errors) { this.logger.error(response.data.errors); throw new Error('Error while loading interaction transactions'); } const data = response.data; const txs = data.data.transactions; return txs; } type() { return 'arweave'; } clearCache() { // noop } } exports.ArweaveGatewayInteractionsLoader = ArweaveGatewayInteractionsLoader; ArweaveGatewayInteractionsLoader.query = `query Transactions($tags: [TagFilter!]!, $blockFilter: BlockFilter!, $first: Int!, $after: String) { transactions(tags: $tags, block: $blockFilter, first: $first, sort: HEIGHT_ASC, after: $after) { pageInfo { hasNextPage } edges { node { id owner { address } recipient tags { name value } block { height id timestamp } fee { winston } quantity { winston } parent { id } bundledIn { id } } cursor } } }`; ArweaveGatewayInteractionsLoader._30seconds = 30 * 1000; //# sourceMappingURL=ArweaveGatewayInteractionsLoader.js.map /***/ }), /***/ 7346: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheableInteractionsLoader = void 0; const LoggerFactory_1 = __webpack_require__(5913); class CacheableInteractionsLoader { constructor(delegate) { this.delegate = delegate; this.logger = LoggerFactory_1.LoggerFactory.INST.create('CacheableInteractionsLoader'); this.interactionsCache = new Map(); } async load(contractTxId, fromSortKey, toSortKey, evaluationOptions) { this.logger.debug(`Loading interactions for`, { contractTxId, fromSortKey, toSortKey }); if (!this.interactionsCache.has(contractTxId)) { const interactions = await this.delegate.load(contractTxId, fromSortKey, toSortKey, evaluationOptions); if (interactions.length) { this.interactionsCache.set(contractTxId, interactions); } return interactions; } else { const cachedInteractions = this.interactionsCache.get(contractTxId); if (cachedInteractions === null || cachedInteractions === void 0 ? void 0 : cachedInteractions.length) { const lastCachedKey = cachedInteractions[cachedInteractions.length - 1].sortKey; if (lastCachedKey.localeCompare(toSortKey) < 0) { const missingInteractions = await this.delegate.load(contractTxId, lastCachedKey, toSortKey, evaluationOptions); const allInteractions = cachedInteractions.concat(missingInteractions); this.interactionsCache.set(contractTxId, allInteractions); return allInteractions; } } return cachedInteractions; } } type() { return this.delegate.type(); } clearCache() { this.interactionsCache.clear(); } } exports.CacheableInteractionsLoader = CacheableInteractionsLoader; //# sourceMappingURL=CacheableInteractionsLoader.js.map /***/ }), /***/ 4286: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheableStateEvaluator = void 0; const SortKeyCache_1 = __webpack_require__(345); const LoggerFactory_1 = __webpack_require__(5913); const utils_1 = __webpack_require__(5082); const StateEvaluator_1 = __webpack_require__(7462); const DefaultStateEvaluator_1 = __webpack_require__(4929); const LexicographicalInteractionsSorter_1 = __webpack_require__(1967); /** * An implementation of DefaultStateEvaluator that adds caching capabilities. * * The main responsibility of this class is to compute whether there are * any interaction transactions, for which the state hasn't been evaluated yet - * if so - it generates a list of such transactions and evaluates the state * for them - taking as an input state the last cached state. */ class CacheableStateEvaluator extends DefaultStateEvaluator_1.DefaultStateEvaluator { constructor(arweave, cache, executionContextModifiers = []) { super(arweave, executionContextModifiers); this.cache = cache; this.cLogger = LoggerFactory_1.LoggerFactory.INST.create('CacheableStateEvaluator'); } async eval(executionContext, currentTx) { var _a, _b, _c, _d; const cachedState = executionContext.cachedState; if (cachedState && cachedState.sortKey == executionContext.requestedSortKey) { this.cLogger.info(`Exact cache hit for sortKey ${(_a = executionContext === null || executionContext === void 0 ? void 0 : executionContext.contractDefinition) === null || _a === void 0 ? void 0 : _a.txId}:${cachedState.sortKey}`); (_b = executionContext.handler) === null || _b === void 0 ? void 0 : _b.initState(cachedState.cachedValue.state); return cachedState; } const missingInteractions = executionContext.sortedInteractions; // TODO: this is tricky part, needs proper description // for now: it prevents from infinite loop calls between calls that are making // internal interact writes. const contractTxId = executionContext.contractDefinition.txId; // sanity check... if (!contractTxId) { throw new Error('Contract tx id not set in the execution context'); } for (const entry of currentTx || []) { if (entry.contractTxId === executionContext.contractDefinition.txId) { const index = missingInteractions.findIndex((tx) => tx.id === entry.interactionTxId); if (index !== -1) { this.cLogger.debug('Inf. Loop fix - removing interaction', { height: missingInteractions[index].block.height, contractTxId: entry.contractTxId, interactionTxId: entry.interactionTxId, sortKey: missingInteractions[index].sortKey }); missingInteractions.splice(index); } } } if (missingInteractions.length == 0) { this.cLogger.info(`No missing interactions ${contractTxId}`); if (cachedState) { (_c = executionContext.handler) === null || _c === void 0 ? void 0 : _c.initState(cachedState.cachedValue.state); return cachedState; } else { (_d = executionContext.handler) === null || _d === void 0 ? void 0 : _d.initState(executionContext.contractDefinition.initState); this.cLogger.debug('Inserting initial state into cache'); const stateToCache = new StateEvaluator_1.EvalStateResult(executionContext.contractDefinition.initState, {}, {}); // no real sort-key - as we're returning the initial state await this.cache.put(new SortKeyCache_1.CacheKey(contractTxId, LexicographicalInteractionsSorter_1.genesisSortKey), stateToCache); return new SortKeyCache_1.SortKeyCacheResult(LexicographicalInteractionsSorter_1.genesisSortKey, stateToCache); } } const baseState = cachedState == null ? executionContext.contractDefinition.initState : cachedState.cachedValue.state; const baseValidity = cachedState == null ? {} : cachedState.cachedValue.validity; const baseErrorMessages = cachedState == null ? {} : cachedState.cachedValue.errorMessages; this.cLogger.debug('Base state', baseState); // eval state for the missing transactions - starting from the latest value from cache. return await this.doReadState(missingInteractions, new StateEvaluator_1.EvalStateResult(baseState, baseValidity, baseErrorMessages || {}), executionContext, currentTx); } async onStateEvaluated(transaction, executionContext, state) { const contractTxId = executionContext.contractDefinition.txId; this.cLogger.debug(`${(0, utils_1.indent)(executionContext.contract.callDepth())}onStateEvaluated: cache update for contract ${contractTxId} [${transaction.sortKey}]`); // this will be problematic if we decide to cache only "onStateEvaluated" and containsInteractionsFromSequencer = true // as a workaround, we're now caching every 100 interactions await this.putInCache(contractTxId, transaction, state); } async onStateUpdate(transaction, executionContext, state, force = false) { if (executionContext.evaluationOptions.updateCacheForEachInteraction || force) { this.cLogger.debug(`onStateUpdate: cache update for contract ${executionContext.contractDefinition.txId} [${transaction.sortKey}]`, { contract: executionContext.contractDefinition.txId, state: state.state, sortKey: transaction.sortKey }); await this.putInCache(executionContext.contractDefinition.txId, transaction, state); } } async latestAvailableState(contractTxId, sortKey) { this.cLogger.debug('Searching for', { contractTxId, sortKey }); if (sortKey) { const stateCache = (await this.cache.getLessOrEqual(contractTxId, sortKey)); if (stateCache) { this.cLogger.debug(`Latest available state at ${contractTxId}: ${stateCache.sortKey}`); } return stateCache; } else { return (await this.cache.getLast(contractTxId)); } } async onInternalWriteStateUpdate(transaction, contractTxId, state) { this.cLogger.debug('Internal write state update:', { sortKey: transaction.sortKey, dry: transaction.dry, contractTxId, state: state.state }); await this.putInCache(contractTxId, transaction, state); } async onContractCall(transaction, executionContext, state) { var _a; if (((_a = executionContext.sortedInteractions) === null || _a === void 0 ? void 0 : _a.length) == 0) { return; } const txIndex = executionContext.sortedInteractions.indexOf(transaction); if (txIndex < 1) { return; } await this.putInCache(executionContext.contractDefinition.txId, executionContext.sortedInteractions[txIndex - 1], state); } async putInCache(contractTxId, transaction, state) { if (transaction.dry) { return; } if (transaction.confirmationStatus !== undefined && transaction.confirmationStatus !== 'confirmed') { return; } const stateToCache = new StateEvaluator_1.EvalStateResult(state.state, state.validity, state.errorMessages || {}); this.cLogger.debug('Putting into cache', { contractTxId, transaction: transaction.id, sortKey: transaction.sortKey, dry: transaction.dry, state: stateToCache.state, validity: stateToCache.validity }); await this.cache.put(new SortKeyCache_1.CacheKey(contractTxId, transaction.sortKey), stateToCache); } async syncState(contractTxId, sortKey, state, validity) { const stateToCache = new StateEvaluator_1.EvalStateResult(state, validity, {}); await this.cache.put(new SortKeyCache_1.CacheKey(contractTxId, sortKey), stateToCache); } async dumpCache() { return await this.cache.dump(); } async internalWriteState(contractTxId, sortKey) { return (await this.cache.get(contractTxId, sortKey)); } async hasContractCached(contractTxId) { return (await this.cache.getLast(contractTxId)) != null; } async lastCachedSortKey() { return await this.cache.getLastSortKey(); } async allCachedContracts() { return await this.cache.allContracts(); } } exports.CacheableStateEvaluator = CacheableStateEvaluator; //# sourceMappingURL=CacheableStateEvaluator.js.map /***/ }), /***/ 7089: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContractDefinitionLoader = void 0; const SmartWeaveTags_1 = __webpack_require__(7312); const utils_1 = __webpack_require__(3633); const Benchmark_1 = __webpack_require__(9106); const LoggerFactory_1 = __webpack_require__(5913); const ArweaveWrapper_1 = __webpack_require__(9360); const WasmSrc_1 = __webpack_require__(6105); const supportedSrcContentTypes = ['application/javascript', 'application/wasm']; class ContractDefinitionLoader { constructor(arweave, // TODO: cache should be removed from the core layer and implemented in a wrapper of the core implementation cache) { this.arweave = arweave; this.cache = cache; this.logger = LoggerFactory_1.LoggerFactory.INST.create('ContractDefinitionLoader'); this.arweaveWrapper = new ArweaveWrapper_1.ArweaveWrapper(arweave); } async load(contractTxId, evolvedSrcTxId) { var _a, _b, _c; if (!evolvedSrcTxId && ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.contains(contractTxId))) { this.logger.debug('ContractDefinitionLoader: Hit from cache!'); return Promise.resolve((_b = this.cache) === null || _b === void 0 ? void 0 : _b.get(contractTxId)); } const benchmark = Benchmark_1.Benchmark.measure(); const contract = await this.doLoad(contractTxId, evolvedSrcTxId); this.logger.info(`Contract definition loaded in: ${benchmark.elapsed()}`); (_c = this.cache) === null || _c === void 0 ? void 0 : _c.put(contractTxId, contract); return contract; } async doLoad(contractTxId, forcedSrcTxId) { const benchmark = Benchmark_1.Benchmark.measure(); const contractTx = await this.arweaveWrapper.tx(contractTxId); const owner = await this.arweave.wallets.ownerToAddress(contractTx.owner); this.logger.debug('Contract tx and owner', benchmark.elapsed()); benchmark.reset(); const contractSrcTxId = forcedSrcTxId ? forcedSrcTxId : (0, utils_1.getTag)(contractTx, SmartWeaveTags_1.SmartWeaveTags.CONTRACT_SRC_TX_ID); const minFee = (0, utils_1.getTag)(contractTx, SmartWeaveTags_1.SmartWeaveTags.MIN_FEE); this.logger.debug('Tags decoding', benchmark.elapsed()); benchmark.reset(); const s = await this.evalInitialState(contractTx); this.logger.debug('init state', s); const initState = JSON.parse(await this.evalInitialState(contractTx)); this.logger.debug('Parsing src and init state', benchmark.elapsed()); const { src, srcBinary, srcWasmLang, contractType, metadata, srcTx } = await this.loadContractSource(contractSrcTxId); return { txId: contractTxId, srcTxId: contractSrcTxId, src, srcBinary, srcWasmLang, initState, minFee, owner, contractType, metadata, contractTx: contractTx.toJSON(), srcTx }; } async loadContractSource(contractSrcTxId) { const benchmark = Benchmark_1.Benchmark.measure(); const contractSrcTx = await this.arweaveWrapper.tx(contractSrcTxId); const srcContentType = (0, utils_1.getTag)(contractSrcTx, SmartWeaveTags_1.SmartWeaveTags.CONTENT_TYPE); if (!supportedSrcContentTypes.includes(srcContentType)) { throw new Error(`Contract source content type ${srcContentType} not supported`); } const contractType = srcContentType == 'application/javascript' ? 'js' : 'wasm'; const src = contractType == 'js' ? await this.arweaveWrapper.txDataString(contractSrcTxId) : await this.arweaveWrapper.txData(contractSrcTxId); let srcWasmLang; let wasmSrc; let srcMetaData; if (contractType == 'wasm') { wasmSrc = new WasmSrc_1.WasmSrc(src); srcWasmLang = (0, utils_1.getTag)(contractSrcTx, SmartWeaveTags_1.SmartWeaveTags.WASM_LANG); if (!srcWasmLang) { throw new Error(`Wasm lang not set for wasm contract src ${contractSrcTxId}`); } srcMetaData = JSON.parse((0, utils_1.getTag)(contractSrcTx, SmartWeaveTags_1.SmartWeaveTags.WASM_META)); } this.logger.debug('Contract src tx load', benchmark.elapsed()); benchmark.reset(); return { src: contractType == 'js' ? src : null, srcBinary: contractType == 'wasm' ? wasmSrc.wasmBinary() : null, srcWasmLang, contractType, metadata: srcMetaData, srcTx: contractSrcTx.toJSON() }; } async evalInitialState(contractTx) { if ((0, utils_1.getTag)(contractTx, SmartWeaveTags_1.SmartWeaveTags.INIT_STATE)) { return (0, utils_1.getTag)(contractTx, SmartWeaveTags_1.SmartWeaveTags.INIT_STATE); } else if ((0, utils_1.getTag)(contractTx, SmartWeaveTags_1.SmartWeaveTags.INIT_STATE_TX)) { const stateTX = (0, utils_1.getTag)(contractTx, SmartWeaveTags_1.SmartWeaveTags.INIT_STATE_TX); return this.arweaveWrapper.txDataString(stateTX); } else { return this.arweaveWrapper.txDataString(contractTx.id); } } type() { return 'arweave'; } } exports.ContractDefinitionLoader = ContractDefinitionLoader; //# sourceMappingURL=ContractDefinitionLoader.js.map /***/ }), /***/ 4929: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DefaultStateEvaluator = void 0; const vrf_js_1 = __webpack_require__(8161); const elliptic_1 = __importDefault(__webpack_require__(6266)); const SortKeyCache_1 = __webpack_require__(345); const Benchmark_1 = __webpack_require__(9106); const LoggerFactory_1 = __webpack_require__(5913); const utils_1 = __webpack_require__(5082); const StateEvaluator_1 = __webpack_require__(7462); const StateCache_1 = __webpack_require__(2138); const TagsParser_1 = __webpack_require__(8996); const EC = new elliptic_1.default.ec('secp256k1'); /** * This class contains the base functionality of evaluating the contracts state - according * to the SmartWeave protocol. * Marked as abstract - as without help of any cache - the evaluation in real-life applications * would be really slow - so using this class without any caching ({@link CacheableStateEvaluator}) * mechanism built on top makes no sense. */ class DefaultStateEvaluator { constructor(arweave, executionContextModifiers = []) { this.arweave = arweave; this.executionContextModifiers = executionContextModifiers; this.logger = LoggerFactory_1.LoggerFactory.INST.create('DefaultStateEvaluator'); this.tagsParser = new TagsParser_1.TagsParser(); } async eval(executionContext, currentTx) { return this.doReadState(executionContext.sortedInteractions, new StateEvaluator_1.EvalStateResult(executionContext.contractDefinition.initState, {}, {}), executionContext, currentTx); } async doReadState(missingInteractions, baseState, executionContext, currentTx) { var _a; const { ignoreExceptions, stackTrace, internalWrites } = executionContext.evaluationOptions; const { contract, contractDefinition, sortedInteractions } = executionContext; let currentState = baseState.state; let currentSortKey = null; const validity = baseState.validity; const errorMessages = baseState.errorMessages; executionContext === null || executionContext === void 0 ? void 0 : executionContext.handler.initState(currentState); const depth = executionContext.contract.callDepth(); this.logger.info(`${(0, utils_1.indent)(depth)}Evaluating state for ${contractDefinition.txId} [${missingInteractions.length} non-cached of ${sortedInteractions.length} all]`); let errorMessage = null; let lastConfirmedTxState = null; const missingInteractionsLength = missingInteractions.length; executionContext.handler.initState(currentState); for (let i = 0; i < missingInteractionsLength; i++) { const missingInteraction = missingInteractions[i]; const singleInteractionBenchmark = Benchmark_1.Benchmark.measure(); currentSortKey = missingInteraction.sortKey; if (missingInteraction.vrf) { if (!this.verifyVrf(missingInteraction.vrf, missingInteraction.sortKey, this.arweave)) { throw new Error('Vrf verification failed.'); } } this.logger.debug(`${(0, utils_1.indent)(depth)}[${contractDefinition.txId}][${missingInteraction.id}][${missingInteraction.block.height}]: ${missingInteractions.indexOf(missingInteraction) + 1}/${missingInteractions.length} [of all:${sortedInteractions.length}]`); const isInteractWrite = this.tagsParser.isInteractWrite(missingInteraction, contractDefinition.txId); // other contract makes write ("writing contract") on THIS contract if (isInteractWrite && internalWrites) { // evaluating txId of the contract that is writing on THIS contract const writingContractTxId = this.tagsParser.getContractTag(missingInteraction); this.logger.debug(`${(0, utils_1.indent)(depth)}Internal Write - Loading writing contract`, writingContractTxId); const interactionCall = contract .getCallStack() .addInteractionData({ interaction: null, interactionTx: missingInteraction, currentTx }); // creating a Contract instance for the "writing" contract const writingContract = executionContext.warp.contract(writingContractTxId, executionContext.contract, missingInteraction); await this.onContractCall(missingInteraction, executionContext, new StateEvaluator_1.EvalStateResult(currentState, validity, errorMessages)); this.logger.debug(`${(0, utils_1.indent)(depth)}Reading state of the calling contract at`, missingInteraction.sortKey); /** Reading the state of the writing contract. This in turn will cause the state of THIS contract to be updated in cache - see {@link ContractHandlerApi.assignWrite} */ await writingContract.readState(missingInteraction.sortKey, [ ...(currentTx || []), { contractTxId: contractDefinition.txId, interactionTxId: missingInteraction.id } ]); // loading latest state of THIS contract from cache const newState = await this.internalWriteState(contractDefinition.txId, missingInteraction.sortKey); if (newState !== null) { currentState = newState.cachedValue.state; // we need to update the state in the wasm module executionContext === null || executionContext === void 0 ? void 0 : executionContext.handler.initState(currentState); validity[missingInteraction.id] = newState.cachedValue.validity[missingInteraction.id]; if ((_a = newState.cachedValue.errorMessages) === null || _a === void 0 ? void 0 : _a[missingInteraction.id]) { errorMessages[missingInteraction.id] = newState.cachedValue.errorMessages[missingInteraction.id]; } const toCache = new StateEvaluator_1.EvalStateResult(currentState, validity, errorMessages); await this.onStateUpdate(missingInteraction, executionContext, toCache); if ((0, StateCache_1.canBeCached)(missingInteraction)) { lastConfirmedTxState = { tx: missingInteraction, state: toCache }; } } else { validity[missingInteraction.id] = false; } interactionCall.update({ cacheHit: false, outputState: stackTrace.saveState ? currentState : undefined, executionTime: singleInteractionBenchmark.elapsed(true), valid: validity[missingInteraction.id], errorMessage: errorMessage, gasUsed: 0 // TODO... }); } else { // "direct" interaction with this contract - "standard" processing const inputTag = this.tagsParser.getInputTag(missingInteraction, executionContext.contractDefinition.txId); if (!inputTag) { this.logger.error(`${(0, utils_1.indent)(depth)}Skipping tx - Input tag not found for ${missingInteraction.id}`); continue; } const input = this.parseInput(inputTag); if (!input) { this.logger.error(`${(0, utils_1.indent)(depth)}Skipping tx - invalid Input tag - ${missingInteraction.id}`); continue; } const interaction = { input, caller: missingInteraction.owner.address }; const interactionData = { interaction, interactionTx: missingInteraction, currentTx }; this.logger.debug(`${(0, utils_1.indent)(depth)}Interaction:`, interaction); const interactionCall = contract.getCallStack().addInteractionData(interactionData); const result = await executionContext.handler.handle(executionContext, new StateEvaluator_1.EvalStateResult(currentState, validity, errorMessages), interactionData); errorMessage = result.errorMessage; if (result.type !== 'ok') { errorMessages[missingInteraction.id] = errorMessage; } this.logResult(result, missingInteraction, executionContext); this.logger.debug(`${(0, utils_1.indent)(depth)}Interaction evaluation`, singleInteractionBenchmark.elapsed()); interactionCall.update({ cacheHit: false, outputState: stackTrace.saveState ? currentState : undefined, executionTime: singleInteractionBenchmark.elapsed(true), valid: validity[missingInteraction.id], errorMessage: errorMessage, gasUsed: result.gasUsed }); if (result.type === 'exception' && ignoreExceptions !== true) { throw new Error(`Exception while processing ${JSON.stringify(interaction)}:\n${result.errorMessage}`); } validity[missingInteraction.id] = result.type === 'ok'; currentState = result.state; const toCache = new StateEvaluator_1.EvalStateResult(currentState, validity, errorMessages); if ((0, StateCache_1.canBeCached)(missingInteraction)) { lastConfirmedTxState = { tx: missingInteraction, state: toCache }; } await this.onStateUpdate(missingInteraction, executionContext, toCache); } for (const { modify } of this.executionContextModifiers) { executionContext = await modify(currentState, executionContext); } } const evalStateResult = new StateEvaluator_1.EvalStateResult(currentState, validity, errorMessages); // state could have been fully retrieved from cache // or there were no interactions below requested block height if (lastConfirmedTxState !== null) { await this.onStateEvaluated(lastConfirmedTxState.tx, executionContext, lastConfirmedTxState.state); } return new SortKeyCache_1.SortKeyCacheResult(currentSortKey, evalStateResult); } verifyVrf(vrf, sortKey, arweave) { const keys = EC.keyFromPublic(vrf.pubkey, 'hex'); let hash; try { // ProofHoHash throws its own 'invalid vrf' exception hash = (0, vrf_js_1.ProofHoHash)(keys.getPublic(), arweave.utils.stringToBuffer(sortKey), arweave.utils.b64UrlToBuffer(vrf.proof)); } catch (e) { return false; } return arweave.utils.bufferTob64Url(hash) == vrf.index; } logResult(result, currentTx, executionContext) { if (result.type === 'exception') { this.logger.error(`Executing of interaction: [${executionContext.contractDefinition.txId} -> ${currentTx.id}] threw exception:`, `${result.errorMessage}`); } if (result.type === 'error') { this.logger.warn(`Executing of interaction: [${executionContext.contractDefinition.txId} -> ${currentTx.id}] returned error:`, result.errorMessage); } } parseInput(inputTag) { try { return JSON.parse(inputTag.value); } catch (e) { this.logger.error(e); return null; } } } exports.DefaultStateEvaluator = DefaultStateEvaluator; //# sourceMappingURL=DefaultStateEvaluator.js.map /***/ }), /***/ 9174: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; 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.HandlerExecutorFactory = void 0; const loader_1 = __importDefault(__webpack_require__(7605)); const as_wasm_imports_1 = __webpack_require__(1692); const rust_wasm_imports_1 = __webpack_require__(6505); const go_wasm_imports_1 = __webpack_require__(7170); const bignumber_js_1 = __importDefault(__webpack_require__(4431)); const vm2 = __importStar(__webpack_require__(7840)); const smartweave_global_1 = __webpack_require__(8563); const Benchmark_1 = __webpack_require__(9106); const LoggerFactory_1 = __webpack_require__(5913); const JsHandlerApi_1 = __webpack_require__(1515); const WasmHandlerApi_1 = __webpack_require__(3425); const normalize_source_1 = __webpack_require__(4965); const MemCache_1 = __webpack_require__(1200); class ContractError extends Error { constructor(message) { super(message); this.name = 'ContractError'; } } /** * A factory that produces handlers that are compatible with the "current" style of * writing SW contracts (i.e. using "handle" function). */ class HandlerExecutorFactory { constructor(arweave) { this.arweave = arweave; this.logger = LoggerFactory_1.LoggerFactory.INST.create('HandlerExecutorFactory'); // TODO: cache compiled wasm binaries here. this.cache = new MemCache_1.MemCache(); } async create(contractDefinition, evaluationOptions) { const swGlobal = new smartweave_global_1.SmartWeaveGlobal(this.arweave, { id: contractDefinition.txId, owner: contractDefinition.owner }, evaluationOptions); if (contractDefinition.contractType == 'wasm') { this.logger.info('Creating handler for wasm contract', contractDefinition.txId); const benchmark = Benchmark_1.Benchmark.measure(); let wasmInstance; let jsExports = null; const wasmResponse = generateResponse(contractDefinition.srcBinary); switch (contractDefinition.srcWasmLang) { case 'assemblyscript': { const wasmInstanceExports = { exports: null }; wasmInstance = await loader_1.default.instantiateStreaming(wasmResponse, (0, as_wasm_imports_1.asWasmImports)(swGlobal, wasmInstanceExports)); // note: well, exports are required by some imports // - e.g. those that use wasmModule.exports.__newString underneath (like Block.indep_hash) wasmInstanceExports.exports = wasmInstance.exports; break; } case 'rust': { const wasmInstanceExports = { exports: null, modifiedExports: { wasm_bindgen__convert__closures__invoke2_mut__: null, _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__: null } }; /** * wasm-bindgen mangles import function names (adds some random number after "base name") * - that's why we cannot statically build the imports in the SDK. * Instead - we need to first compile the module and check the generated * import function names (all imports from the "__wbindgen_placeholder__" import module). * Having those generated function names - we need to then map them to import functions - * see {@link rustWasmImports} * * That's probably a temporary solution - it would be the best to force the wasm-bindgen * to NOT mangle the import function names - unfortunately that is not currently possible * - https://github.com/rustwasm/wasm-bindgen/issues/1128 */ const wasmModule = await getWasmModule(wasmResponse, contractDefinition.srcBinary); const moduleImports = WebAssembly.Module.imports(wasmModule); const wbindgenImports = moduleImports .filter((imp) => { return imp.module === '__wbindgen_placeholder__'; }) .map((imp) => imp.name); const { imports, exports } = (0, rust_wasm_imports_1.rustWasmImports)(swGlobal, wbindgenImports, wasmInstanceExports, contractDefinition.metadata.dtor); jsExports = exports; wasmInstance = await WebAssembly.instantiate(wasmModule, imports); wasmInstanceExports.exports = wasmInstance.exports; const moduleExports = Object.keys(wasmInstance.exports); // ... no comments ... moduleExports.forEach((moduleExport) => { if (moduleExport.startsWith('wasm_bindgen__convert__closures__invoke2_mut__')) { wasmInstanceExports.modifiedExports.wasm_bindgen__convert__closures__invoke2_mut__ = wasmInstance.exports[moduleExport]; } if (moduleExport.startsWith('_dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__')) { wasmInstanceExports.modifiedExports._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__ = wasmInstance.exports[moduleExport]; } }); break; } case 'go': { const go = new go_wasm_imports_1.Go(swGlobal); go.importObject.metering = { usegas: function (value) { swGlobal.useGas(value); } }; const wasmModule = await getWasmModule(wasmResponse, contractDefinition.srcBinary); wasmInstance = await WebAssembly.instantiate(wasmModule, go.importObject); // nope - DO NOT await here! go.run(wasmInstance); jsExports = go.exports; break; } default: { throw new Error(`Support for ${contractDefinition.srcWasmLang} not implemented yet.`); } } this.logger.info(`WASM ${contractDefinition.srcWasmLang} handler created in ${benchmark.elapsed()}`); return new WasmHandlerApi_1.WasmHandlerApi(swGlobal, contractDefinition, jsExports || wasmInstance.exports); } else { this.logger.info('Creating handler for js contract', contractDefinition.txId); const normalizedSource = (0, normalize_source_1.normalizeContractSource)(contractDefinition.src, evaluationOptions.useVM2); if (!evaluationOptions.allowUnsafeClient) { if (normalizedSource.includes('SmartWeave.unsafeClient')) { throw new Error('Using unsafeClient is not allowed by default. Use EvaluationOptions.allowUnsafeClient flag.'); } } if (!evaluationOptions.allowBigInt) { if (normalizedSource.includes('BigInt')) { throw new Error('Using BigInt is not allowed by default. Use EvaluationOptions.allowBigInt flag.'); } } if (evaluationOptions.useVM2) { const vmScript = new vm2.VMScript(normalizedSource); const vm = new vm2.NodeVM({ console: 'off', sandbox: { SmartWeave: swGlobal, BigNumber: bignumber_js_1.default, logger: this.logger, ContractError: ContractError, ContractAssert: function (cond, message) { if (!cond) throw new ContractError(message); } }, compiler: 'javascript', eval: false, wasm: false, allowAsync: true, wrapper: 'commonjs' }); return new JsHandlerApi_1.JsHandlerApi(swGlobal, contractDefinition, vm.run(vmScript)); } else { const contractFunction = new Function(normalizedSource); const handler = contractFunction(swGlobal, bignumber_js_1.default, LoggerFactory_1.LoggerFactory.INST.create(swGlobal.contract.id)); return new JsHandlerApi_1.JsHandlerApi(swGlobal, contractDefinition, handler); } } } } exports.HandlerExecutorFactory = HandlerExecutorFactory; function generateResponse(wasmBinary) { const init = { status: 200, statusText: 'OK', headers: { 'Content-Type': 'application/wasm' } }; return new Response(wasmBinary, init); } async function getWasmModule(wasmResponse, binary) { if (WebAssembly.compileStreaming) { return await WebAssembly.compileStreaming(wasmResponse); } else { return await WebAssembly.compile(binary); } } //# sourceMappingURL=HandlerExecutorFactory.js.map /***/ }), /***/ 1967: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LexicographicalInteractionsSorter = exports.genesisSortKey = exports.sortingLast = exports.sortingFirst = void 0; const utils_1 = __webpack_require__(3633); const LoggerFactory_1 = __webpack_require__(5913); const WarpGatewayInteractionsLoader_1 = __webpack_require__(1533); // note: this (i.e. padding to 13 digits) should be safe between years ~1966 and ~2286 const firstSortKeyMs = ''.padEnd(13, '0'); const lastSortKeyMs = ''.padEnd(13, '9'); const defaultArweaveMs = ''.padEnd(13, '0'); exports.sortingFirst = ''.padEnd(64, '0'); exports.sortingLast = ''.padEnd(64, 'z'); exports.genesisSortKey = `${''.padStart(12, '0')},${firstSortKeyMs},${exports.sortingFirst}`; /** * implementation that is based on current's SDK sorting alg. */ class LexicographicalInteractionsSorter { constructor(arweave) { this.arweave = arweave; this.logger = LoggerFactory_1.LoggerFactory.INST.create('LexicographicalInteractionsSorter'); } async sort(transactions) { const copy = [...transactions]; const addKeysFuncs = copy.map((tx) => this.addSortKey(tx)); await Promise.all(addKeysFuncs); return copy.sort((a, b) => a.node.sortKey.localeCompare(b.node.sortKey)); } async createSortKey(blockId, transactionId, blockHeight, dummy = false) { const blockHashBytes = this.arweave.utils.b64UrlToBuffer(blockId); const txIdBytes = this.arweave.utils.b64UrlToBuffer(transactionId); const concatenated = this.arweave.utils.concatBuffers([blockHashBytes, txIdBytes]); const hashed = (0, utils_1.arrayToHex)(await this.arweave.crypto.hash(concatenated)); const blockHeightString = `${blockHeight}`.padStart(12, '0'); const arweaveMs = dummy ? lastSortKeyMs : defaultArweaveMs; return `${blockHeightString},${arweaveMs},${hashed}`; } extractBlockHeight(sortKey) { // I feel sorry for myself... return sortKey ? parseInt(sortKey.split(',')[0]) : null; } async addSortKey(txInfo) { const { node } = txInfo; // might have been already set by the Warp Sequencer if (txInfo.node.sortKey !== undefined && txInfo.node.source == WarpGatewayInteractionsLoader_1.SourceType.WARP_SEQUENCER) { this.logger.debug('Using sortKey from sequencer', txInfo.node.sortKey); } else { txInfo.node.sortKey = await this.createSortKey(node.block.id, node.id, node.block.height); } } generateLastSortKey(blockHeight) { const blockHeightString = `${blockHeight}`.padStart(12, '0'); return `${blockHeightString},${lastSortKeyMs},${exports.sortingLast}`; } } exports.LexicographicalInteractionsSorter = LexicographicalInteractionsSorter; //# sourceMappingURL=LexicographicalInteractionsSorter.js.map /***/ }), /***/ 2138: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.canBeCached = void 0; //export type StateCache = Array>; function canBeCached(tx) { // in case of using non-redstone gateway if (tx.confirmationStatus === undefined) { return true; } else { return tx.confirmationStatus === 'confirmed'; } } exports.canBeCached = canBeCached; //# sourceMappingURL=StateCache.js.map /***/ }), /***/ 8996: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TagsParser = void 0; const SmartWeaveTags_1 = __webpack_require__(7312); const LoggerFactory_1 = __webpack_require__(5913); /** * A class that is responsible for retrieving "input" tag from the interaction transaction. * Two tags formats are allowed: * 1. "multiple interactions in one tx" format - where "Input" tag MUST be next to the "Contract" tag * See more at https://github.com/ArweaveTeam/SmartWeave/pull/51 * 2. "traditional" format - one interaction per one transaction - where tags order does not matter. * * More on Discord: https://discord.com/channels/357957786904166400/756557551234973696/885388585023463424 */ class TagsParser { constructor() { this.logger = LoggerFactory_1.LoggerFactory.INST.create('TagsParser'); } getInputTag(interactionTransaction, contractTxId) { // this is the part to retain compatibility with https://github.com/ArweaveTeam/SmartWeave/pull/51 if (TagsParser.hasMultipleInteractions(interactionTransaction)) { this.logger.debug('Interaction transaction is using multiple input tx tag format.'); const contractTagIndex = interactionTransaction.tags.findIndex((tag) => tag.name === SmartWeaveTags_1.SmartWeaveTags.CONTRACT_TX_ID && tag.value === contractTxId); // if "Contract" is the last tag if (interactionTransaction.tags.length - 1 === contractTagIndex) { this.logger.warn("Wrong tags format: 'Contract' is the last tag"); return undefined; } // in this case the "Input" tag MUST be right after the "Contract" tag const inputTag = interactionTransaction.tags[contractTagIndex + 1]; // if the tag after "Contract" tag has wrong name if (inputTag.name !== SmartWeaveTags_1.SmartWeaveTags.INPUT) { this.logger.warn(`No 'Input' tag found after 'Contract' tag. Instead ${inputTag.name} was found`); return undefined; } return inputTag; } else { // the "old way" - i.e. tags ordering does not matter, // if there is at most one "Contract" tag // - so returning the first occurrence of "Input" tag. return interactionTransaction.tags.find((tag) => tag.name === SmartWeaveTags_1.SmartWeaveTags.INPUT); } } isInteractWrite(interactionTransaction, contractTxId) { return interactionTransaction.tags.some((tag) => tag.name === SmartWeaveTags_1.SmartWeaveTags.INTERACT_WRITE && tag.value === contractTxId); } getInteractWritesContracts(interactionTransaction) { return interactionTransaction.tags.filter((tag) => tag.name === SmartWeaveTags_1.SmartWeaveTags.INTERACT_WRITE).map((t) => t.value); } getContractTag(interactionTransaction) { var _a; return (_a = interactionTransaction.tags.find((tag) => tag.name === SmartWeaveTags_1.SmartWeaveTags.CONTRACT_TX_ID)) === null || _a === void 0 ? void 0 : _a.value; } getContractsWithInputs(interactionTransaction) { const result = new Map(); const contractTags = interactionTransaction.tags.filter((tag) => tag.name === SmartWeaveTags_1.SmartWeaveTags.CONTRACT_TX_ID); contractTags.forEach((contractTag) => { result.set(contractTag.value, this.getInputTag(interactionTransaction, contractTag.value)); }); return result; } static hasMultipleInteractions(interactionTransaction) { return interactionTransaction.tags.filter((tag) => tag.name === SmartWeaveTags_1.SmartWeaveTags.CONTRACT_TX_ID).length > 1; } } exports.TagsParser = TagsParser; //# sourceMappingURL=TagsParser.js.map /***/ }), /***/ 3187: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(8764)["Buffer"]; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WarpGatewayContractDefinitionLoader = void 0; const ContractDefinitionLoader_1 = __webpack_require__(7089); __webpack_require__(9180); const WasmSrc_1 = __webpack_require__(6105); const transaction_1 = __importDefault(__webpack_require__(7241)); const SmartWeaveTags_1 = __webpack_require__(7312); const utils_1 = __webpack_require__(3633); const Benchmark_1 = __webpack_require__(9106); const LoggerFactory_1 = __webpack_require__(5913); const ArweaveWrapper_1 = __webpack_require__(9360); const utils_2 = __webpack_require__(5082); /** * An extension to {@link ContractDefinitionLoader} that makes use of * Warp Gateway ({@link https://github.com/redstone-finance/redstone-sw-gateway}) * to load Contract Data. * * If the contract data is not available on Warp Gateway - it fallbacks to default implementation * in {@link ContractDefinitionLoader} - i.e. loads the definition from Arweave gateway. */ class WarpGatewayContractDefinitionLoader { constructor(baseUrl, arweave, cache) { this.baseUrl = baseUrl; this.cache = cache; this.rLogger = LoggerFactory_1.LoggerFactory.INST.create('WarpGatewayContractDefinitionLoader'); this.baseUrl = (0, utils_2.stripTrailingSlash)(baseUrl); this.contractDefinitionLoader = new ContractDefinitionLoader_1.ContractDefinitionLoader(arweave, cache); this.arweaveWrapper = new ArweaveWrapper_1.ArweaveWrapper(arweave); } async load(contractTxId, evolvedSrcTxId) { var _a, _b, _c; if (!evolvedSrcTxId && ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.contains(contractTxId))) { this.rLogger.debug('WarpGatewayContractDefinitionLoader: Hit from cache!'); return Promise.resolve((_b = this.cache) === null || _b === void 0 ? void 0 : _b.get(contractTxId)); } const benchmark = Benchmark_1.Benchmark.measure(); const contract = await this.doLoad(contractTxId, evolvedSrcTxId); this.rLogger.info(`Contract definition loaded in: ${benchmark.elapsed()}`); (_c = this.cache) === null || _c === void 0 ? void 0 : _c.put(contractTxId, contract); return contract; } async doLoad(contractTxId, forcedSrcTxId) { try { const result = await fetch(`${this.baseUrl}/gateway/contract?txId=${contractTxId}${forcedSrcTxId ? `&srcTxId=${forcedSrcTxId}` : ''}`) .then((res) => { return res.ok ? res.json() : Promise.reject(res); }) .catch((error) => { var _a, _b; if ((_a = error.body) === null || _a === void 0 ? void 0 : _a.message) { this.rLogger.error(error.body.message); } throw new Error(`Unable to retrieve contract data. Warp gateway responded with status ${error.status}:${(_b = error.body) === null || _b === void 0 ? void 0 : _b.message}`); }); if (result.srcBinary != null && !(result.srcBinary instanceof Buffer)) { result.srcBinary = Buffer.from(result.srcBinary.data); } if (result.srcBinary) { const wasmSrc = new WasmSrc_1.WasmSrc(result.srcBinary); result.srcBinary = wasmSrc.wasmBinary(); let sourceTx; if (result.srcTx) { sourceTx = new transaction_1.default({ ...result.srcTx }); } else { sourceTx = await this.arweaveWrapper.tx(result.srcTxId); } const srcMetaData = JSON.parse((0, utils_1.getTag)(sourceTx, SmartWeaveTags_1.SmartWeaveTags.WASM_META)); result.metadata = srcMetaData; } result.contractType = result.src ? 'js' : 'wasm'; return result; } catch (e) { this.rLogger.warn('Falling back to default contracts loader', e); return await this.contractDefinitionLoader.doLoad(contractTxId, forcedSrcTxId); } } async loadContractSource(contractSrcTxId) { return await this.contractDefinitionLoader.loadContractSource(contractSrcTxId); } type() { return 'warp'; } } exports.WarpGatewayContractDefinitionLoader = WarpGatewayContractDefinitionLoader; //# sourceMappingURL=WarpGatewayContractDefinitionLoader.js.map /***/ }), /***/ 1533: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WarpGatewayInteractionsLoader = exports.SourceType = void 0; const Benchmark_1 = __webpack_require__(9106); const LoggerFactory_1 = __webpack_require__(5913); __webpack_require__(9180); const utils_1 = __webpack_require__(5082); var SourceType; (function (SourceType) { SourceType["ARWEAVE"] = "arweave"; SourceType["WARP_SEQUENCER"] = "redstone-sequencer"; })(SourceType = exports.SourceType || (exports.SourceType = {})); /** * The aim of this implementation of the {@link InteractionsLoader} is to make use of * Warp Gateway ({@link https://github.com/redstone-finance/redstone-sw-gateway}) * endpoint and retrieve contracts' interactions. * * Optionally - it is possible to pass: * 1. {@link ConfirmationStatus.confirmed} flag - to receive only confirmed interactions - ie. interactions with * enough confirmations, whose existence is confirmed by at least 3 Arweave peers. * 2. {@link ConfirmationStatus.notCorrupted} flag - to receive both already confirmed and not yet confirmed (ie. latest) * interactions. * 3. {@link SourceType} - to receive interactions based on their origin ({@link SourceType.ARWEAVE} or {@link SourceType.REDSTONE_SEQUENCER}). * If not set, interactions from all sources will be loaded. * * Passing no flag is the "backwards compatible" mode (ie. it will behave like the original Arweave GQL gateway endpoint). * Note that this may result in returning corrupted and/or forked interactions * - read more {@link https://github.com/warp-contracts/redstone-sw-gateway#corrupted-transactions}. */ class WarpGatewayInteractionsLoader { constructor(baseUrl, confirmationStatus = null, source = null) { this.baseUrl = baseUrl; this.confirmationStatus = confirmationStatus; this.source = source; this.logger = LoggerFactory_1.LoggerFactory.INST.create('WarpGatewayInteractionsLoader'); this.baseUrl = (0, utils_1.stripTrailingSlash)(baseUrl); Object.assign(this, confirmationStatus); this.source = source; } async load(contractId, fromSortKey, toSortKey, evaluationOptions) { this.logger.debug('Loading interactions: for ', { contractId, fromSortKey, toSortKey }); const interactions = []; let page = 0; let limit = 0; let items = 0; const benchmarkTotalTime = Benchmark_1.Benchmark.measure(); do { const benchmarkRequestTime = Benchmark_1.Benchmark.measure(); const url = `${this.baseUrl}/gateway/v2/interactions-sort-key`; const response = await fetch(`${url}?${new URLSearchParams({ contractId: contractId, ...(fromSortKey ? { from: fromSortKey } : ''), ...(toSortKey ? { to: toSortKey } : ''), page: (++page).toString(), fromSdk: 'true', ...(this.confirmationStatus && this.confirmationStatus.confirmed ? { confirmationStatus: 'confirmed' } : ''), ...(this.confirmationStatus && this.confirmationStatus.notCorrupted ? { confirmationStatus: 'not_corrupted' } : ''), ...(this.source ? { source: this.source } : '') })}`) .then((res) => { return res.ok ? res.json() : Promise.reject(res); }) .catch((error) => { var _a; if ((_a = error.body) === null || _a === void 0 ? void 0 : _a.message) { this.logger.error(error.body.message); } throw new Error(`Unable to retrieve transactions. Warp gateway responded with status ${error.status}.`); }); this.logger.debug(`Loading interactions: page ${page} loaded in ${benchmarkRequestTime.elapsed()}`); interactions.push(...response.interactions); limit = response.paging.limit; items = response.paging.items; this.logger.debug(`Loaded interactions length: ${interactions.length}, from: ${fromSortKey}, to: ${toSortKey}`); } while (items == limit); // note: items < limit means that we're on the last page this.logger.debug('All loaded interactions:', { from: fromSortKey, to: toSortKey, loaded: interactions.length, time: benchmarkTotalTime.elapsed() }); return interactions; } type() { return 'warp'; } clearCache() { // noop } } exports.WarpGatewayInteractionsLoader = WarpGatewayInteractionsLoader; //# sourceMappingURL=WarpGatewayInteractionsLoader.js.map /***/ }), /***/ 3233: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AbstractContractHandler = void 0; const LoggerFactory_1 = __webpack_require__(5913); const utils_1 = __webpack_require__(5082); class AbstractContractHandler { constructor(swGlobal, contractDefinition) { this.swGlobal = swGlobal; this.contractDefinition = contractDefinition; this.logger = LoggerFactory_1.LoggerFactory.INST.create('ContractHandler'); this.assignReadContractState = this.assignReadContractState.bind(this); this.assignViewContractState = this.assignViewContractState.bind(this); this.assignWrite = this.assignWrite.bind(this); this.assignRefreshState = this.assignRefreshState.bind(this); } async dispose() { // noop by default; } assignWrite(executionContext, currentTx) { this.swGlobal.contracts.write = async (contractTxId, input) => { if (!executionContext.evaluationOptions.internalWrites) { throw new Error("Internal writes feature switched off. Change EvaluationOptions.internalWrites flag to 'true'"); } this.logger.debug('swGlobal.write call:', { from: this.contractDefinition.txId, to: contractTxId, input }); // The contract that we want to call and modify its state const calleeContract = executionContext.warp.contract(contractTxId, executionContext.contract, this.swGlobal._activeTx); const result = await calleeContract.dryWriteFromTx(input, this.swGlobal._activeTx, [ ...(currentTx || []), { contractTxId: this.contractDefinition.txId, interactionTxId: this.swGlobal.transaction.id } ]); this.logger.debug('Cache result?:', !this.swGlobal._activeTx.dry); await executionContext.warp.stateEvaluator.onInternalWriteStateUpdate(this.swGlobal._activeTx, contractTxId, { state: result.state, validity: { ...result.originalValidity, [this.swGlobal._activeTx.id]: result.type == 'ok' }, errorMessages: { ...result.originalErrorMessages, [this.swGlobal._activeTx.id]: result.errorMessage } }); return result; }; } assignViewContractState(executionContext) { this.swGlobal.contracts.viewContractState = async (contractTxId, input) => { this.logger.debug('swGlobal.viewContractState call:', { from: this.contractDefinition.txId, to: contractTxId, input }); const childContract = executionContext.warp.contract(contractTxId, executionContext.contract, this.swGlobal._activeTx); return await childContract.viewStateForTx(input, this.swGlobal._activeTx); }; } assignReadContractState(executionContext, currentTx, currentResult, interactionTx) { this.swGlobal.contracts.readContractState = async (contractTxId, returnValidity) => { this.logger.debug('swGlobal.readContractState call:', { from: this.contractDefinition.txId, to: contractTxId, sortKey: interactionTx.sortKey, transaction: this.swGlobal.transaction.id }); const { stateEvaluator } = executionContext.warp; const childContract = executionContext.warp.contract(contractTxId, executionContext.contract, interactionTx); await stateEvaluator.onContractCall(interactionTx, executionContext, currentResult); const stateWithValidity = await childContract.readState(interactionTx.sortKey, [ ...(currentTx || []), { contractTxId: this.contractDefinition.txId, interactionTxId: this.swGlobal.transaction.id } ]); // TODO: it should be up to the client's code to decide which part of the result to use // (by simply using destructuring operator)... // but this (i.e. returning always stateWithValidity from here) would break backwards compatibility // in current contract's source code..:/ return returnValidity ? (0, utils_1.deepCopy)(stateWithValidity) : (0, utils_1.deepCopy)(stateWithValidity.cachedValue.state); }; } assignRefreshState(executionContext) { this.swGlobal.contracts.refreshState = async () => { const stateEvaluator = executionContext.warp.stateEvaluator; const result = await stateEvaluator.latestAvailableState(this.swGlobal.contract.id, this.swGlobal._activeTx.sortKey); return result === null || result === void 0 ? void 0 : result.cachedValue.state; }; } } exports.AbstractContractHandler = AbstractContractHandler; //# sourceMappingURL=AbstractContractHandler.js.map /***/ }), /***/ 1515: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JsHandlerApi = void 0; const utils_1 = __webpack_require__(5082); const AbstractContractHandler_1 = __webpack_require__(3233); class JsHandlerApi extends AbstractContractHandler_1.AbstractContractHandler { constructor(swGlobal, contractDefinition, // eslint-disable-next-line contractFunction) { super(swGlobal, contractDefinition); this.contractFunction = contractFunction; } async handle(executionContext, currentResult, interactionData) { const { timeoutId, timeoutPromise } = (0, utils_1.timeout)(executionContext.evaluationOptions.maxInteractionEvaluationTimeSeconds); try { const { interaction, interactionTx, currentTx } = interactionData; const stateCopy = (0, utils_1.deepCopy)(currentResult.state, executionContext.evaluationOptions.useFastCopy); this.swGlobal._activeTx = interactionTx; this.swGlobal.caller = interaction.caller; // either contract tx id (for internal writes) or transaction.owner this.assignReadContractState(executionContext, currentTx, currentResult, interactionTx); this.assignViewContractState(executionContext); this.assignWrite(executionContext, currentTx); this.assignRefreshState(executionContext); const handlerResult = await Promise.race([timeoutPromise, this.contractFunction(stateCopy, interaction)]); if (handlerResult && (handlerResult.state !== undefined || handlerResult.result !== undefined)) { return { type: 'ok', result: handlerResult.result, state: handlerResult.state || currentResult.state }; } // Will be caught below as unexpected exception. throw new Error(`Unexpected result from contract: ${JSON.stringify(handlerResult)}`); } catch (err) { switch (err.name) { case 'ContractError': return { type: 'error', errorMessage: err.message, state: currentResult.state, // note: previous version was writing error message to a "result" field, // which fucks-up the HandlerResult type definition - // HandlerResult.result had to be declared as 'Result | string' - and that led to a poor dev exp. // TODO: this might be breaking change! result: null }; default: return { type: 'exception', errorMessage: `${(err && err.stack) || (err && err.message) || err}`, state: currentResult.state, result: null }; } } finally { if (timeoutId !== null) { // it is important to clear the timeout promise // - promise.race won't "cancel" it automatically if the "handler" promise "wins" // - and this would ofc. cause a waste in cpu cycles // (+ Jest complains about async operations not being stopped properly). clearTimeout(timeoutId); } } } initState(state) { // nth to do in this impl... } } exports.JsHandlerApi = JsHandlerApi; //# sourceMappingURL=JsHandlerApi.js.map /***/ }), /***/ 3425: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WasmHandlerApi = void 0; const safe_stable_stringify_1 = __importDefault(__webpack_require__(7668)); const AbstractContractHandler_1 = __webpack_require__(3233); class WasmHandlerApi extends AbstractContractHandler_1.AbstractContractHandler { constructor(swGlobal, // eslint-disable-next-line contractDefinition, wasmExports) { super(swGlobal, contractDefinition); this.wasmExports = wasmExports; } async handle(executionContext, currentResult, interactionData) { try { const { interaction, interactionTx, currentTx } = interactionData; this.swGlobal._activeTx = interactionTx; this.swGlobal.caller = interaction.caller; // either contract tx id (for internal writes) or transaction.owner this.swGlobal.gasLimit = executionContext.evaluationOptions.gasLimit; this.swGlobal.gasUsed = 0; this.assignReadContractState(executionContext, currentTx, currentResult, interactionTx); this.assignWrite(executionContext, currentTx); const handlerResult = await this.doHandle(interaction); return { type: 'ok', result: handlerResult, state: this.doGetCurrentState(), gasUsed: this.swGlobal.gasUsed }; } catch (e) { // note: as exceptions handling in WASM is currently somewhat non-existent // https://www.assemblyscript.org/status.html#exceptions // and since we have to somehow differentiate different types of exceptions // - each exception message has to have a proper prefix added. // exceptions with prefix [RE:] ("Runtime Exceptions") should break the execution immediately // - eg: [RE:OOG] - [RuntimeException: OutOfGas] // exception with prefix [CE:] ("Contract Exceptions") should be logged, but should not break // the state evaluation - as they are considered as contracts' business exception (eg. validation errors) // - eg: [CE:ITT] - [ContractException: InvalidTokenTransfer] const result = { errorMessage: e.message, state: currentResult.state, result: null }; if (e.message.startsWith('[RE:')) { this.logger.fatal(e); return { ...result, type: 'exception' }; } else { return { ...result, type: 'error' }; } } } initState(state) { switch (this.contractDefinition.srcWasmLang) { case 'assemblyscript': { const statePtr = this.wasmExports.__newString((0, safe_stable_stringify_1.default)(state)); this.wasmExports.initState(statePtr); break; } case 'rust': { this.wasmExports.initState(state); break; } case 'go': { this.wasmExports.initState((0, safe_stable_stringify_1.default)(state)); break; } default: { throw new Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`); } } } async doHandle(action) { switch (this.contractDefinition.srcWasmLang) { case 'assemblyscript': { const actionPtr = this.wasmExports.__newString((0, safe_stable_stringify_1.default)(action.input)); const resultPtr = this.wasmExports.handle(actionPtr); const result = this.wasmExports.__getString(resultPtr); return JSON.parse(result); } case 'rust': { let handleResult = await this.wasmExports.handle(action.input); if (!handleResult) { return; } if (Object.prototype.hasOwnProperty.call(handleResult, 'Ok')) { return handleResult.Ok; } else { this.logger.debug('Error from rust', handleResult.Err); let errorKey; let errorArgs = ''; if (typeof handleResult.Err === 'string' || handleResult.Err instanceof String) { errorKey = handleResult.Err; } else { errorKey = Object.keys(handleResult.Err)[0]; errorArgs = ' ' + handleResult.Err[errorKey]; } if (errorKey == 'RuntimeError') { throw new Error(`[RE:RE]${errorArgs}`); } else { throw new Error(`[CE:${errorKey}${errorArgs}]`); } } } case 'go': { const result = await this.wasmExports.handle((0, safe_stable_stringify_1.default)(action.input)); return JSON.parse(result); } default: { throw new Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`); } } } doGetCurrentState() { switch (this.contractDefinition.srcWasmLang) { case 'assemblyscript': { const currentStatePtr = this.wasmExports.currentState(); return JSON.parse(this.wasmExports.__getString(currentStatePtr)); } case 'rust': { return this.wasmExports.currentState(); } case 'go': { const result = this.wasmExports.currentState(); return JSON.parse(result); } default: { throw new Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`); } } } } exports.WasmHandlerApi = WasmHandlerApi; //# sourceMappingURL=WasmHandlerApi.js.map /***/ }), /***/ 4965: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.normalizeContractSource = void 0; function normalizeContractSource(contractSrc, useVM2) { // Convert from ES Module format to something we can run inside a Function. // Removes the `export` keyword and adds ;return handle to the end of the function. // Additionally it removes 'IIFE' declarations // (which may be generated when bundling multiple sources into one output file // - eg. using esbuild's "IIFE" bundle format). // We also assign the passed in SmartWeaveGlobal to SmartWeave, and declare // the ContractError exception. // We then use `new Function()` which we can call and get back the returned handle function // which has access to the per-instance globals. const lines = contractSrc.trim().split('\n'); const first = lines[0]; const last = lines[lines.length - 1]; if ((/\(\s*\(\)\s*=>\s*{/g.test(first) || /\s*\(\s*function\s*\(\)\s*{/g.test(first)) && /}\s*\)\s*\(\)\s*;/g.test(last)) { lines.shift(); lines.pop(); contractSrc = lines.join('\n'); } contractSrc = contractSrc .replace(/export\s+async\s+function\s+handle/gmu, 'async function handle') .replace(/export\s+function\s+handle/gmu, 'function handle'); if (useVM2) { return ` ${contractSrc} module.exports = handle;`; } else { return ` const [SmartWeave, BigNumber, logger] = arguments; class ContractError extends Error { constructor(message) { super(message); this.name = 'ContractError' } }; function ContractAssert(cond, message) { if (!cond) throw new ContractError(message) }; ${contractSrc}; return handle; `; } } exports.normalizeContractSource = normalizeContractSource; //# sourceMappingURL=normalize-source.js.map /***/ }), /***/ 6105: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WasmSrc = void 0; const unzipit_1 = __webpack_require__(3931); const redstone_isomorphic_1 = __webpack_require__(9180); const LoggerFactory_1 = __webpack_require__(5913); class WasmSrc { constructor(src) { this.src = src; this.logger = LoggerFactory_1.LoggerFactory.INST.create('WasmSrc'); this.splitted = this.splitBuffer(src); this.logger.debug(`Buffer splitted into ${this.splitted.length} parts`); } wasmBinary() { return this.splitted[0]; } async sourceCode() { const { entries } = await (0, unzipit_1.unzip)(this.splitted[1]); const result = new Map(); for (const [name, entry] of Object.entries(entries)) { if (entry.isDirectory) { continue; } const content = await entry.text(); result.set(name, content); } return result; } additionalCode() { if (this.splitted.length == 2) { return null; } return this.splitted[2].toString(); } splitBuffer(inputBuffer) { let header = ''; const elements = parseInt(inputBuffer.toString('utf8', 0, 1)); this.logger.debug(`Number of elements: ${elements}`); const l = inputBuffer.length; let delimiters = 0; let dataStart = 0; for (let i = 2; i < l; i++) { const element = inputBuffer.toString('utf8', i, i + 1); if (element == '|') { delimiters++; } if (delimiters == elements) { dataStart = i + 1; break; } header += element; } this.logger.debug(`Parsed:`, { header, dataStart }); const lengths = header.split('|').map((l) => parseInt(l)); this.logger.debug('Lengths', lengths); const result = []; for (const length of lengths) { const buffer = redstone_isomorphic_1.Buffer.alloc(length); const end = dataStart + length; inputBuffer.copy(buffer, 0, dataStart, end); dataStart = end; result.push(buffer); } return result; } } exports.WasmSrc = WasmSrc; //# sourceMappingURL=WasmSrc.js.map /***/ }), /***/ 1692: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.asWasmImports = void 0; const LoggerFactory_1 = __webpack_require__(5913); const asWasmImports = (swGlobal, wasmInstance) => { const wasmLogger = LoggerFactory_1.LoggerFactory.INST.create('WASM:AS'); return { metering: { usegas: swGlobal.useGas }, console: { 'console.log': function (msgPtr) { wasmLogger.debug(`${swGlobal.contract.id}: ${wasmInstance.exports.__getString(msgPtr)}`); }, 'console.logO': function (msgPtr, objPtr) { wasmLogger.debug(`${swGlobal.contract.id}: ${wasmInstance.exports.__getString(msgPtr)}`, JSON.parse(wasmInstance.exports.__getString(objPtr))); } }, block: { 'Block.height': function () { return swGlobal.block.height; }, 'Block.indep_hash': function () { return wasmInstance.exports.__newString(swGlobal.block.indep_hash); }, 'Block.timestamp': function () { return swGlobal.block.timestamp; } }, transaction: { 'Transaction.id': function () { return wasmInstance.exports.__newString(swGlobal.transaction.id); }, 'Transaction.owner': function () { return wasmInstance.exports.__newString(swGlobal.transaction.owner); }, 'Transaction.target': function () { return wasmInstance.exports.__newString(swGlobal.transaction.target); } }, contract: { 'Contract.id': function () { return wasmInstance.exports.__newString(swGlobal.contract.id); }, 'Contract.owner': function () { return wasmInstance.exports.__newString(swGlobal.contract.owner); } }, api: { _readContractState: (fnIndex, contractTxIdPtr) => { const contractTxId = wasmInstance.exports.__getString(contractTxIdPtr); const callbackFn = getFn(fnIndex); console.log('Simulating read state of', contractTxId); return setTimeout(() => { console.log('calling callback'); callbackFn(wasmInstance.exports.__newString(JSON.stringify({ contractTxId }))); }, 1000); }, clearTimeout }, env: { abort(messagePtr, fileNamePtr, line, column) { const message = wasmInstance.exports.__getString(messagePtr); wasmLogger.error('--------------------- Error message from AssemblyScript ----------------------\n'); wasmLogger.error(' ' + message); wasmLogger.error(' In file "' + wasmInstance.exports.__getString(fileNamePtr) + '"'); wasmLogger.error(` on line ${line}, column ${column}.`); wasmLogger.error('------------------------------------------------------------------------------\n'); throw new Error(message); } } }; function getFn(idx) { return wasmInstance.exports.table.get(idx); } }; exports.asWasmImports = asWasmImports; //# sourceMappingURL=as-wasm-imports.js.map /***/ }), /***/ 7170: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var process = __webpack_require__(3957); // Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // // This file has been modified for use by the TinyGo compiler. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Go = void 0; const LoggerFactory_1 = __webpack_require__(5913); // note: this file has been further modified to be used // with Warp SDK. /* tslint:disable */ /* eslint-disable */ /* YOLO */ const encoder = new TextEncoder(); const decoder = new TextDecoder('utf-8'); let logLine = []; let globalJsModule; // crying while committing... (function (global) { globalJsModule = global; globalJsModule.redstone = { go: {} }; }.call(this, typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {})); class Go { constructor(swGlobal) { this._callbackTimeouts = new Map(); this._nextCallbackTimeoutID = 1; const wasmLogger = LoggerFactory_1.LoggerFactory.INST.create('WASM:Go'); let go = this; // it is safe to redeclare this for each new module in the global scope // - this function is called only during module initialization. globalJsModule.redstone.go = { WasmModule: { registerWasmModule: function (moduleId) { go._id = moduleId; go.exports = globalJsModule[moduleId]; delete globalJsModule[moduleId]; globalJsModule.redstone.go[moduleId] = {}; globalJsModule.redstone.go[moduleId].imports = { console: { log: function (...args) { wasmLogger.debug(args[0], ...args.slice(1)); } }, Transaction: { id: function () { return swGlobal.transaction.id; }, owner: function () { return swGlobal.transaction.owner; }, target: function () { return swGlobal.transaction.target; } }, Block: { indep_hash: function () { return swGlobal.block.indep_hash; }, height: function () { return swGlobal.block.height; }, timestamp: function () { return swGlobal.block.timestamp; } }, Contract: { id: function () { return swGlobal.contract.id; }, owner: function () { return swGlobal.contract.owner; } }, SmartWeave: { readContractState: async function (contractTxId) { return await swGlobal.contracts.readContractState(contractTxId); } } }; } } }; const mem = () => { // The buffer may change when requesting more memory. return new DataView(this._inst.exports.memory.buffer); }; const setInt64 = (addr, v) => { mem().setUint32(addr + 0, v, true); mem().setUint32(addr + 4, Math.floor(v / 4294967296), true); }; const getInt64 = (addr) => { const low = mem().getUint32(addr + 0, true); const high = mem().getInt32(addr + 4, true); return low + high * 4294967296; }; const loadValue = (addr) => { const f = mem().getFloat64(addr, true); if (f === 0) { return undefined; } if (!isNaN(f)) { return f; } const id = mem().getUint32(addr, true); return this._values[id]; }; const storeValue = (addr, v) => { const nanHead = 0x7ff80000; if (typeof v === 'number') { if (isNaN(v)) { mem().setUint32(addr + 4, nanHead, true); mem().setUint32(addr, 0, true); return; } if (v === 0) { mem().setUint32(addr + 4, nanHead, true); mem().setUint32(addr, 1, true); return; } mem().setFloat64(addr, v, true); return; } switch (v) { case undefined: mem().setFloat64(addr, 0, true); return; case null: mem().setUint32(addr + 4, nanHead, true); mem().setUint32(addr, 2, true); return; case true: mem().setUint32(addr + 4, nanHead, true); mem().setUint32(addr, 3, true); return; case false: mem().setUint32(addr + 4, nanHead, true); mem().setUint32(addr, 4, true); return; } let id = this._ids.get(v); if (id === undefined) { id = this._idPool.pop(); if (id === undefined) { id = this._values.length; } this._values[id] = v; this._goRefCounts[id] = 0; this._ids.set(v, id); } this._goRefCounts[id]++; let typeFlag = 1; switch (typeof v) { case 'string': typeFlag = 2; break; case 'symbol': typeFlag = 3; break; case 'function': typeFlag = 4; break; } mem().setUint32(addr + 4, nanHead | typeFlag, true); mem().setUint32(addr, id, true); }; const loadSlice = (array, len, cap = null) => { return new Uint8Array(this._inst.exports.memory.buffer, array, len); }; const loadSliceOfValues = (array, len, cap) => { const a = new Array(len); for (let i = 0; i < len; i++) { a[i] = loadValue(array + i * 8); } return a; }; const loadString = (ptr, len) => { return decoder.decode(new DataView(this._inst.exports.memory.buffer, ptr, len)); }; const timeOrigin = Date.now() - performance.now(); this.importObject = { wasi_snapshot_preview1: { // https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#fd_write fd_write: function (fd, iovs_ptr, iovs_len, nwritten_ptr) { let nwritten = 0; if (fd == 1) { for (let iovs_i = 0; iovs_i < iovs_len; iovs_i++) { let iov_ptr = iovs_ptr + iovs_i * 8; // assuming wasm32 let ptr = mem().getUint32(iov_ptr + 0, true); let len = mem().getUint32(iov_ptr + 4, true); nwritten += len; for (let i = 0; i < len; i++) { let c = mem().getUint8(ptr + i); if (c == 13) { // CR // ignore } else if (c == 10) { // LF // write line let line = decoder.decode(new Uint8Array(logLine)); logLine = []; console.log(line); } else { logLine.push(c); } } } } else { console.error('invalid file descriptor:', fd); } mem().setUint32(nwritten_ptr, nwritten, true); return 0; }, fd_close: () => 0, fd_fdstat_get: () => 0, fd_seek: () => 0, proc_exit: (code) => { // @ts-ignore if (__webpack_require__.g.process) { // Node.js process.exit(code); } else { // Can't exit in a browser. throw 'trying to exit with code ' + code; } }, random_get: (bufPtr, bufLen) => { crypto.getRandomValues(loadSlice(bufPtr, bufLen, null)); return 0; } }, env: { // func ticks() float64 'runtime.ticks': () => { return timeOrigin + performance.now(); }, // func sleepTicks(timeout float64) 'runtime.sleepTicks': (timeout) => { // Do not sleep, only reactivate scheduler after the given timeout. setTimeout(this._inst.exports.go_scheduler, timeout); }, // func finalizeRef(v ref) // https://github.com/tinygo-org/tinygo/issues/1140#issuecomment-718145455 'syscall/js.finalizeRef': (v_addr) => { // Note: TinyGo does not support finalizers so this is only called // for one specific case, by js.go:jsString. const id = mem().getUint32(v_addr, true); this._goRefCounts[id]--; if (this._goRefCounts[id] === 0) { const v = this._values[id]; this._values[id] = null; this._ids.delete(v); this._idPool.push(id); } }, // func stringVal(value string) ref 'syscall/js.stringVal': (ret_ptr, value_ptr, value_len) => { const s = loadString(value_ptr, value_len); storeValue(ret_ptr, s); }, // func valueGet(v ref, p string) ref 'syscall/js.valueGet': (retval, v_addr, p_ptr, p_len) => { let prop = loadString(p_ptr, p_len); let value = loadValue(v_addr); let result = Reflect.get(value, prop); storeValue(retval, result); }, // func valueSet(v ref, p string, x ref) 'syscall/js.valueSet': (v_addr, p_ptr, p_len, x_addr) => { const v = loadValue(v_addr); const p = loadString(p_ptr, p_len); const x = loadValue(x_addr); Reflect.set(v, p, x); }, // func valueDelete(v ref, p string) 'syscall/js.valueDelete': (v_addr, p_ptr, p_len) => { const v = loadValue(v_addr); const p = loadString(p_ptr, p_len); Reflect.deleteProperty(v, p); }, // func valueIndex(v ref, i int) ref 'syscall/js.valueIndex': (ret_addr, v_addr, i) => { storeValue(ret_addr, Reflect.get(loadValue(v_addr), i)); }, // valueSetIndex(v ref, i int, x ref) 'syscall/js.valueSetIndex': (v_addr, i, x_addr) => { Reflect.set(loadValue(v_addr), i, loadValue(x_addr)); }, // func valueCall(v ref, m string, args []ref) (ref, bool) 'syscall/js.valueCall': (ret_addr, v_addr, m_ptr, m_len, args_ptr, args_len, args_cap) => { const v = loadValue(v_addr); const name = loadString(m_ptr, m_len); const args = loadSliceOfValues(args_ptr, args_len, args_cap); try { const m = Reflect.get(v, name); storeValue(ret_addr, Reflect.apply(m, v, args)); mem().setUint8(ret_addr + 8, 1); } catch (err) { storeValue(ret_addr, err); mem().setUint8(ret_addr + 8, 0); } }, // func valueInvoke(v ref, args []ref) (ref, bool) 'syscall/js.valueInvoke': (ret_addr, v_addr, args_ptr, args_len, args_cap) => { try { const v = loadValue(v_addr); const args = loadSliceOfValues(args_ptr, args_len, args_cap); storeValue(ret_addr, Reflect.apply(v, undefined, args)); mem().setUint8(ret_addr + 8, 1); } catch (err) { storeValue(ret_addr, err); mem().setUint8(ret_addr + 8, 0); } }, // func valueNew(v ref, args []ref) (ref, bool) 'syscall/js.valueNew': (ret_addr, v_addr, args_ptr, args_len, args_cap) => { const v = loadValue(v_addr); const args = loadSliceOfValues(args_ptr, args_len, args_cap); try { storeValue(ret_addr, Reflect.construct(v, args)); mem().setUint8(ret_addr + 8, 1); } catch (err) { storeValue(ret_addr, err); mem().setUint8(ret_addr + 8, 0); } }, // func valueLength(v ref) int 'syscall/js.valueLength': (v_addr) => { return loadValue(v_addr).length; }, // valuePrepareString(v ref) (ref, int) 'syscall/js.valuePrepareString': (ret_addr, v_addr) => { const s = String(loadValue(v_addr)); const str = encoder.encode(s); storeValue(ret_addr, str); setInt64(ret_addr + 8, str.length); }, // valueLoadString(v ref, b []byte) 'syscall/js.valueLoadString': (v_addr, slice_ptr, slice_len, slice_cap) => { const str = loadValue(v_addr); loadSlice(slice_ptr, slice_len, slice_cap).set(str); }, // func valueInstanceOf(v ref, t ref) bool 'syscall/js.valueInstanceOf': (v_addr, t_addr) => { return loadValue(v_addr) instanceof loadValue(t_addr); }, // func copyBytesToGo(dst []byte, src ref) (int, bool) 'syscall/js.copyBytesToGo': (ret_addr, dest_addr, dest_len, dest_cap, source_addr) => { let num_bytes_copied_addr = ret_addr; let returned_status_addr = ret_addr + 4; // Address of returned boolean status variable const dst = loadSlice(dest_addr, dest_len); const src = loadValue(source_addr); if (!(src instanceof Uint8Array)) { mem().setUint8(returned_status_addr, 0); // Return "not ok" status return; } const toCopy = src.subarray(0, dst.length); dst.set(toCopy); setInt64(num_bytes_copied_addr, toCopy.length); mem().setUint8(returned_status_addr, 1); // Return "ok" status }, // copyBytesToJS(dst ref, src []byte) (int, bool) // Originally copied from upstream Go project, then modified: // https://github.com/golang/go/blob/3f995c3f3b43033013013e6c7ccc93a9b1411ca9/misc/wasm/wasm_exec.js#L404-L416 'syscall/js.copyBytesToJS': (ret_addr, dest_addr, source_addr, source_len, source_cap) => { let num_bytes_copied_addr = ret_addr; let returned_status_addr = ret_addr + 4; // Address of returned boolean status variable const dst = loadValue(dest_addr); const src = loadSlice(source_addr, source_len); if (!(dst instanceof Uint8Array)) { mem().setUint8(returned_status_addr, 0); // Return "not ok" status return; } const toCopy = src.subarray(0, dst.length); dst.set(toCopy); setInt64(num_bytes_copied_addr, toCopy.length); mem().setUint8(returned_status_addr, 1); // Return "ok" status } } }; } async run(instance) { this._inst = instance; this._values = [ // JS values that Go currently has references to, indexed by reference id NaN, 0, null, true, false, __webpack_require__.g, this ]; this._goRefCounts = []; // number of references that Go has to a JS value, indexed by reference id this._ids = new Map(); // mapping from JS values to reference ids this._idPool = []; // unused ids that have been garbage collected this.exited = false; // whether the Go program has exited const mem = new DataView(this._inst.exports.memory.buffer); while (true) { const callbackPromise = new Promise((resolve) => { this._resolveCallbackPromise = () => { if (this.exited) { throw new Error('bad callback: Go program has already exited'); } setTimeout(resolve, 0); // make sure it is asynchronous }; }); this._inst.exports._start(); if (this.exited) { break; } await callbackPromise; } } _resume() { if (this.exited) { throw new Error('Go program has already exited'); } this._inst.exports.resume(); if (this.exited) { this._resolveExitPromise(); } } _makeFuncWrapper(id) { const go = this; return function () { const event = { id: id, this: this, args: arguments }; go._pendingEvent = event; go._resume(); // @ts-ignore return event.result; }; } _resolveExitPromise() { } } exports.Go = Go; //# sourceMappingURL=go-wasm-imports.js.map /***/ }), /***/ 6505: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* tslint:disable */ /* eslint-disable */ /* a kind of magic */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.rustWasmImports = void 0; const LoggerFactory_1 = __webpack_require__(5913); // note: this is (somewhat heavily) modified code // of the js that is normally generated by the wasm-bindgen const rustWasmImports = (swGlobal, wbindgenImports, wasmInstance, dtorValue) => { const wasmLogger = LoggerFactory_1.LoggerFactory.INST.create('WASM:Rust'); // the raw functions, that we want to make available from the // wasm module const rawImports = { metering: { usegas: swGlobal.useGas }, console: { log: function (value) { wasmLogger.debug(`${swGlobal.contract.id}: ${value}`); } }, Block: { height: function () { return swGlobal.block.height; }, indep_hash: function () { return swGlobal.block.indep_hash; }, timestamp: function () { return swGlobal.block.timestamp; } }, Transaction: { id: function () { return swGlobal.transaction.id; }, owner: function () { return swGlobal.transaction.owner; }, target: function () { return swGlobal.transaction.target; } }, Contract: { id: function () { return swGlobal.contract.id; }, owner: function () { return swGlobal.contract.owner; } }, SmartWeave: { caller: function () { return swGlobal.caller; }, readContractState: async function (contractTxId) { return await swGlobal.contracts.readContractState(contractTxId); }, write: async function (contractId, input) { return await swGlobal.contracts.write(contractId, input); } }, Vrf: { value: function () { return swGlobal.vrf.value; }, randomInt: function (maxValue) { return swGlobal.vrf.randomInt(maxValue); } } }; // mapping from base function names (without mangled suffixes) // to functions normally generated by the wasm-bindgen // - the "glue" code between js and wasm. const baseImports = { __wbg_log_: function (arg0, arg1) { rawImports.console.log(getStringFromWasm0(arg0, arg1)); }, __wbindgen_json_parse: function (arg0, arg1) { var ret = JSON.parse(getStringFromWasm0(arg0, arg1)); return addHeapObject(ret); }, __wbindgen_json_serialize: function (arg0, arg1) { const obj = getObject(arg1); var ret = JSON.stringify(obj === undefined ? null : obj); var ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); var len0 = WASM_VECTOR_LEN; getInt32Memory0()[arg0 / 4 + 1] = len0; getInt32Memory0()[arg0 / 4 + 0] = ptr0; }, __wbindgen_object_drop_ref: function (arg0) { takeObject(arg0); }, __wbindgen_cb_drop: function (arg0) { const obj = takeObject(arg0).original; if (obj.cnt-- == 1) { obj.a = 0; return true; } var ret = false; return ret; }, __wbg_readContractState: function (arg0, arg1) { var ret = rawImports.SmartWeave.readContractState(getStringFromWasm0(arg0, arg1)); return addHeapObject(ret); }, __wbg_viewContractState: function (arg0, arg1) { // TODO }, __wbg_caller: function (arg0) { var ret = rawImports.SmartWeave.caller(); var ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); var len0 = WASM_VECTOR_LEN; getInt32Memory0()[arg0 / 4 + 1] = len0; getInt32Memory0()[arg0 / 4 + 0] = ptr0; }, __wbg_write: function (arg0, arg1, arg2) { var ret = rawImports.SmartWeave.write(getStringFromWasm0(arg0, arg1), takeObject(arg2)); return addHeapObject(ret); }, __wbg_refreshState: function (arg0, arg1) { // TODO }, __wbg_indephash: function (arg0) { var ret = rawImports.Block.indep_hash(); var ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); var len0 = WASM_VECTOR_LEN; getInt32Memory0()[arg0 / 4 + 1] = len0; getInt32Memory0()[arg0 / 4 + 0] = ptr0; }, __wbg_height: function () { var ret = rawImports.Block.height(); return ret; }, __wbg_timestamp: function () { var ret = rawImports.Block.timestamp(); return ret; }, __wbg_id: function (arg0) { var ret = rawImports.Transaction.id(); var ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); var len0 = WASM_VECTOR_LEN; getInt32Memory0()[arg0 / 4 + 1] = len0; getInt32Memory0()[arg0 / 4 + 0] = ptr0; }, __wbg_contractOwner: function (arg0) { var ret = rawImports.Contract.owner(); var ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); var len0 = WASM_VECTOR_LEN; getInt32Memory0()[arg0 / 4 + 1] = len0; getInt32Memory0()[arg0 / 4 + 0] = ptr0; }, __wbg_contractId: function (arg0) { var ret = rawImports.Contract.id(); var ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); var len0 = WASM_VECTOR_LEN; getInt32Memory0()[arg0 / 4 + 1] = len0; getInt32Memory0()[arg0 / 4 + 0] = ptr0; }, __wbg_owner: function (arg0) { var ret = rawImports.Transaction.owner(); var ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); var len0 = WASM_VECTOR_LEN; getInt32Memory0()[arg0 / 4 + 1] = len0; getInt32Memory0()[arg0 / 4 + 0] = ptr0; }, __wbg_target: function (arg0) { var ret = rawImports.Transaction.target(); var ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); var len0 = WASM_VECTOR_LEN; getInt32Memory0()[arg0 / 4 + 1] = len0; getInt32Memory0()[arg0 / 4 + 0] = ptr0; }, __wbg_call: function () { return handleError(function (arg0, arg1, arg2) { var ret = getObject(arg0).call(getObject(arg1), getObject(arg2)); return addHeapObject(ret); }, arguments); }, __wbg_new: function (arg0, arg1) { try { var state0 = { a: arg0, b: arg1 }; var cb0 = (arg0, arg1) => { const a = state0.a; state0.a = 0; try { return __wbg_adapter_42(a, state0.b, arg0, arg1); } finally { state0.a = a; } }; var ret = new Promise(cb0); return addHeapObject(ret); } finally { state0.a = state0.b = 0; } }, __wbg_resolve: function (arg0) { var ret = Promise.resolve(getObject(arg0)); return addHeapObject(ret); }, __wbg_then_a: function (arg0, arg1) { var ret = getObject(arg0).then(getObject(arg1)); return addHeapObject(ret); }, __wbg_then_5: function (arg0, arg1, arg2) { var ret = getObject(arg0).then(getObject(arg1), getObject(arg2)); return addHeapObject(ret); }, __wbindgen_debug_string: function (arg0, arg1) { var ret = debugString(getObject(arg1)); var ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); var len0 = WASM_VECTOR_LEN; getInt32Memory0()[arg0 / 4 + 1] = len0; getInt32Memory0()[arg0 / 4 + 0] = ptr0; }, __wbindgen_throw: function (arg0, arg1) { throw new Error(getStringFromWasm0(arg0, arg1)); }, __wbindgen_closure_wrapper: function (arg0, arg1, arg2) { var ret = makeMutClosure(arg0, arg1, dtorValue, __wbg_adapter_14); return addHeapObject(ret); }, __wbindgen_string_new: function (arg0, arg1) { var ret = getStringFromWasm0(arg0, arg1); return addHeapObject(ret); }, __wbg_value: function (arg0) { var ret = rawImports.Vrf.value(); var ptr0 = passStringToWasm0(ret, wasmInstance.exports.__wbindgen_malloc, wasmInstance.exports.__wbindgen_realloc); var len0 = WASM_VECTOR_LEN; getInt32Memory0()[arg0 / 4 + 1] = len0; getInt32Memory0()[arg0 / 4 + 0] = ptr0; }, __wbg_randomInt: function (arg0, arg1) { var ret = rawImports.Vrf.randomInt(arg1); return ret; } }; const baseImportsKeys = Object.keys(baseImports); // assigning functions to "real" import names from the currently // compiled wasm module let module = wbindgenImports.reduce((acc, wbindgenKey) => { const baseImportsKey = baseImportsKeys.find((key) => wbindgenKey.startsWith(key)); if (baseImportsKey === undefined) { throw new Error(`Cannot find import mapping for ${wbindgenKey}`); } acc[wbindgenKey] = baseImports[baseImportsKey]; return acc; }, {}); // the rest of the code is basically left untouched from what // wasm-bindgen generates let imports = {}; imports['__wbindgen_placeholder__'] = module; let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); cachedTextDecoder.decode(); let cachegetUint8Memory0 = null; function getUint8Memory0() { if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasmInstance.exports.memory.buffer) { cachegetUint8Memory0 = new Uint8Array(wasmInstance.exports.memory.buffer); } return cachegetUint8Memory0; } function getStringFromWasm0(ptr, len) { return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); } const heap = new Array(32).fill(undefined); heap.push(undefined, null, true, false); let heap_next = heap.length; function addHeapObject(obj) { if (heap_next === heap.length) heap.push(heap.length + 1); const idx = heap_next; heap_next = heap[idx]; heap[idx] = obj; return idx; } function getObject(idx) { return heap[idx]; } let WASM_VECTOR_LEN = 0; // @ts-ignore let cachedTextEncoder = new TextEncoder('utf-8'); const encodeString = typeof cachedTextEncoder.encodeInto === 'function' ? function (arg, view) { return cachedTextEncoder.encodeInto(arg, view); } : function (arg, view) { const buf = cachedTextEncoder.encode(arg); view.set(buf); return { read: arg.length, written: buf.length }; }; function passStringToWasm0(arg, malloc, realloc) { if (realloc === undefined) { const buf = cachedTextEncoder.encode(arg); const ptr = malloc(buf.length); getUint8Memory0() .subarray(ptr, ptr + buf.length) .set(buf); WASM_VECTOR_LEN = buf.length; return ptr; } let len = arg.length; let ptr = malloc(len); const mem = getUint8Memory0(); let offset = 0; for (; offset < len; offset++) { const code = arg.charCodeAt(offset); if (code > 0x7f) break; mem[ptr + offset] = code; } if (offset !== len) { if (offset !== 0) { arg = arg.slice(offset); } ptr = realloc(ptr, len, (len = offset + arg.length * 3)); const view = getUint8Memory0().subarray(ptr + offset, ptr + len); const ret = encodeString(arg, view); offset += ret.written; } WASM_VECTOR_LEN = offset; return ptr; } let cachegetInt32Memory0 = null; function getInt32Memory0() { if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasmInstance.exports.memory.buffer) { cachegetInt32Memory0 = new Int32Array(wasmInstance.exports.memory.buffer); } return cachegetInt32Memory0; } function dropObject(idx) { if (idx < 36) return; heap[idx] = heap_next; heap_next = idx; } function takeObject(idx) { const ret = getObject(idx); dropObject(idx); return ret; } function debugString(val) { // primitive types const type = typeof val; if (type == 'number' || type == 'boolean' || val == null) { return `${val}`; } if (type == 'string') { return `"${val}"`; } if (type == 'symbol') { const description = val.description; if (description == null) { return 'Symbol'; } else { return `Symbol(${description})`; } } if (type == 'function') { const name = val.name; if (typeof name == 'string' && name.length > 0) { return `Function(${name})`; } else { return 'Function'; } } // objects if (Array.isArray(val)) { const length = val.length; let debug = '['; if (length > 0) { debug += debugString(val[0]); } for (let i = 1; i < length; i++) { debug += ', ' + debugString(val[i]); } debug += ']'; return debug; } // Test for built-in const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); let className; if (builtInMatches.length > 1) { className = builtInMatches[1]; } else { // Failed to match the standard '[object ClassName]' return toString.call(val); } if (className == 'Object') { // we're a user defined class or Object // JSON.stringify avoids problems with cycles, and is generally much // easier than looping through ownProperties of `val`. try { return 'Object(' + JSON.stringify(val) + ')'; } catch (_) { return 'Object'; } } // errors if (val instanceof Error) { return `${val.name}: ${val.message}\n${val.stack}`; } // TODO we could test for more things here, like `Set`s and `Map`s. return className; } function makeMutClosure(arg0, arg1, dtor, f) { const state = { a: arg0, b: arg1, cnt: 1, dtor }; const real = (...args) => { // First up with a closure we increment the internal reference // count. This ensures that the Rust closure environment won't // be deallocated while we're invoking it. state.cnt++; const a = state.a; state.a = 0; try { return f(a, state.b, ...args); } finally { if (--state.cnt === 0) { wasmInstance.exports.__wbindgen_export_2.get(state.dtor)(a, state.b); } else { state.a = a; } } }; real.original = state; return real; } function __wbg_adapter_14(arg0, arg1, arg2) { wasmInstance.modifiedExports._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__(arg0, arg1, addHeapObject(arg2)); } /** * @param {any} interaction * @returns {Promise} */ module.handle = function (interaction) { var ret = wasmInstance.exports.handle(addHeapObject(interaction)); return takeObject(ret); }; let stack_pointer = 32; function addBorrowedObject(obj) { if (stack_pointer == 1) throw new Error('out of js stack'); heap[--stack_pointer] = obj; return stack_pointer; } /** * @param {any} state */ module.initState = function (state) { try { wasmInstance.exports.initState(addBorrowedObject(state)); } finally { heap[stack_pointer++] = undefined; } }; /** * @returns {any} */ module.currentState = function () { var ret = wasmInstance.exports.currentState(); return takeObject(ret); }; /** * @returns {string} */ module.lang = function () { try { const retptr = wasmInstance.exports.__wbindgen_add_to_stack_pointer(-16); wasmInstance.exports.lang(retptr); var r0 = getInt32Memory0()[retptr / 4 + 0]; var r1 = getInt32Memory0()[retptr / 4 + 1]; return getStringFromWasm0(r0, r1); } finally { wasmInstance.exports.__wbindgen_add_to_stack_pointer(16); wasmInstance.exports.__wbindgen_free(r0, r1); } }; /** * @returns {number} */ module.type = function () { var ret = wasmInstance.exports.type(); return ret; }; function handleError(f, args) { try { return f.apply(this, args); } catch (e) { wasmInstance.exports.__wbindgen_exn_store(addHeapObject(e)); } } function __wbg_adapter_42(arg0, arg1, arg2, arg3) { wasmInstance.modifiedExports.wasm_bindgen__convert__closures__invoke2_mut__(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3)); } /** */ class StateWrapper { __destroy_into_raw() { // @ts-ignore const ptr = this.ptr; // @ts-ignore this.ptr = 0; return ptr; } free() { const ptr = this.__destroy_into_raw(); wasmInstance.exports.__wbg_statewrapper_free(ptr); } } module.StateWrapper = StateWrapper; imports.metering = rawImports.metering; return { imports, exports: module }; }; exports.rustWasmImports = rustWasmImports; //# sourceMappingURL=rust-wasm-imports.js.map /***/ }), /***/ 4742: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.matchMutClosureDtor = void 0; function matchMutClosureDtor(source) { const regexp = /var ret = makeMutClosure\(arg0, arg1, (\d+?), __wbg_adapter/; const match = source.match(regexp); return match[1]; } exports.matchMutClosureDtor = matchMutClosureDtor; //# sourceMappingURL=wasm-bindgen-tools.js.map /***/ }), /***/ 702: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; 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 __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); __exportStar(__webpack_require__(183), exports); __exportStar(__webpack_require__(4089), exports); __exportStar(__webpack_require__(2393), exports); __exportStar(__webpack_require__(5913), exports); __exportStar(__webpack_require__(5629), exports); __exportStar(__webpack_require__(9106), exports); __exportStar(__webpack_require__(2656), exports); __exportStar(__webpack_require__(5368), exports); __exportStar(__webpack_require__(5765), exports); __exportStar(__webpack_require__(6769), exports); __exportStar(__webpack_require__(7462), exports); __exportStar(__webpack_require__(7089), exports); __exportStar(__webpack_require__(3187), exports); __exportStar(__webpack_require__(9564), exports); __exportStar(__webpack_require__(1533), exports); __exportStar(__webpack_require__(7346), exports); __exportStar(__webpack_require__(4929), exports); __exportStar(__webpack_require__(4286), exports); __exportStar(__webpack_require__(9174), exports); __exportStar(__webpack_require__(1967), exports); __exportStar(__webpack_require__(8996), exports); __exportStar(__webpack_require__(4965), exports); __exportStar(__webpack_require__(2138), exports); __exportStar(__webpack_require__(6105), exports); __exportStar(__webpack_require__(3233), exports); __exportStar(__webpack_require__(1515), exports); __exportStar(__webpack_require__(3425), exports); __exportStar(__webpack_require__(8632), exports); __exportStar(__webpack_require__(7312), exports); __exportStar(__webpack_require__(4805), exports); __exportStar(__webpack_require__(9305), exports); __exportStar(__webpack_require__(5614), exports); __exportStar(__webpack_require__(8479), exports); __exportStar(__webpack_require__(2009), exports); __exportStar(__webpack_require__(9689), exports); __exportStar(__webpack_require__(8469), exports); __exportStar(__webpack_require__(9692), exports); __exportStar(__webpack_require__(7665), exports); __exportStar(__webpack_require__(7819), exports); __exportStar(__webpack_require__(8102), exports); __exportStar(__webpack_require__(4722), exports); __exportStar(__webpack_require__(4217), exports); __exportStar(__webpack_require__(5731), exports); __exportStar(__webpack_require__(3611), exports); __exportStar(__webpack_require__(4708), exports); __exportStar(__webpack_require__(8563), exports); __exportStar(__webpack_require__(9925), exports); __exportStar(__webpack_require__(3633), exports); __exportStar(__webpack_require__(40), exports); __exportStar(__webpack_require__(5082), exports); __exportStar(__webpack_require__(9360), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 40: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unpackTags = exports.createDummyTx = exports.createInteractionTx = void 0; const SmartWeaveTags_1 = __webpack_require__(7312); async function createInteractionTx(arweave, signer, contractId, input, tags, target = '', winstonQty = '0', dummy = false, reward) { const options = { data: Math.random().toString().slice(-4) }; if (target && target.length) { options.target = target.toString(); if (winstonQty && +winstonQty > 0) { options.quantity = winstonQty.toString(); } } // both reward and last_tx are irrelevant in case of interactions // that are bundled. So to speed up the procees (and prevent the arweave-js // from calling /tx_anchor and /price endpoints) - we're presetting theses // values here if (dummy) { options.reward = '72600854'; options.last_tx = 'p7vc1iSP6bvH_fCeUFa9LqoV5qiyW-jdEKouAT0XMoSwrNraB9mgpi29Q10waEpO'; } if (reward && reward.length) { options.reward = reward; } const interactionTx = await arweave.createTransaction(options); if (!input) { throw new Error(`Input should be a truthy value: ${JSON.stringify(input)}`); } if (tags && tags.length) { for (const tag of tags) { interactionTx.addTag(tag.name.toString(), tag.value.toString()); } } interactionTx.addTag(SmartWeaveTags_1.SmartWeaveTags.APP_NAME, 'SmartWeaveAction'); // use real SDK version here? interactionTx.addTag(SmartWeaveTags_1.SmartWeaveTags.APP_VERSION, '0.3.0'); interactionTx.addTag(SmartWeaveTags_1.SmartWeaveTags.SDK, 'Warp'); interactionTx.addTag(SmartWeaveTags_1.SmartWeaveTags.CONTRACT_TX_ID, contractId); interactionTx.addTag(SmartWeaveTags_1.SmartWeaveTags.INPUT, JSON.stringify(input)); if (signer) { await signer(interactionTx); } return interactionTx; } exports.createInteractionTx = createInteractionTx; function createDummyTx(tx, from, block) { // transactions loaded from gateway (either arweave.net GQL or Warp) have the tags decoded // - so to be consistent, the "dummy" tx, which is used for viewState and dryWrites, also has to have // the tags decoded. const decodedTags = unpackTags(tx); return { id: tx.id, owner: { address: from, key: '' }, recipient: tx.target, tags: decodedTags, fee: { winston: tx.reward, ar: '' }, quantity: { winston: tx.quantity, ar: '' }, block: { id: block.indep_hash, height: block.height, timestamp: block.timestamp, previous: null }, // note: calls within dry runs cannot be cached (per block - like the state cache)! // that's super important, as the block height used for // the dry-run is the current network block height // - and not the block height of the real transaction that // will be mined on Arweave. // If we start caching results of the dry-runs, we can completely fuck-up // the consecutive state evaluations. // - that's why we're setting "dry" flag to true here // - this prevents the caching layer from saving // the state evaluated for such interaction in cache. dry: true, anchor: null, signature: null, data: null, parent: null, bundledIn: null }; } exports.createDummyTx = createDummyTx; function unpackTags(tx) { const tags = tx.get('tags'); const result = []; for (const tag of tags) { try { const name = tag.get('name', { decode: true, string: true }); const value = tag.get('value', { decode: true, string: true }); result.push({ name, value }); } catch (e) { // ignore tags with invalid utf-8 strings in key or value. } } return result; } exports.unpackTags = unpackTags; //# sourceMappingURL=create-interaction-tx.js.map /***/ }), /***/ 9925: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SmartWeaveError = exports.SmartWeaveErrorType = void 0; var SmartWeaveErrorType; (function (SmartWeaveErrorType) { SmartWeaveErrorType["CONTRACT_NOT_FOUND"] = "CONTRACT_NOT_FOUND"; })(SmartWeaveErrorType = exports.SmartWeaveErrorType || (exports.SmartWeaveErrorType = {})); class SmartWeaveError extends Error { constructor(type, optional = {}) { if (optional.message) { super(optional.message); } else { super(); } this.type = type; this.otherInfo = optional; } getType() { return this.type; } } exports.SmartWeaveError = SmartWeaveError; //# sourceMappingURL=errors.js.map /***/ }), /***/ 4708: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=gqlResult.js.map /***/ }), /***/ 8563: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SmartWeaveGlobal = void 0; /** * * This class is exposed as a global for contracts * as 'SmartWeave' and provides an API for getting further * information or using utility and crypto functions from * inside the contracts execution. * * It provides an api: * * - SmartWeave.transaction.id * - SmartWeave.transaction.reward * - SmartWeave.block.height * - SmartWeave.block.timestamp * - etc * * and access to some of the arweave utils: * - SmartWeave.arweave.utils * - SmartWeave.arweave.crypto * - SmartWeave.arweave.wallets * - SmartWeave.arweave.ar * * as well as access to the potentially non-deterministic full client: * - SmartWeave.unsafeClient * */ class SmartWeaveGlobal { constructor(arweave, contract, evaluationOptions) { this.gasUsed = 0; this.gasLimit = Number.MAX_SAFE_INTEGER; this.unsafeClient = arweave; this.arweave = { ar: arweave.ar, utils: arweave.utils, wallets: arweave.wallets, crypto: arweave.crypto }; this.evaluationOptions = evaluationOptions; this.contract = contract; this.transaction = new Transaction(this); this.block = new Block(this); this.contracts = { readContractState: (contractId, height, returnValidity) => { throw new Error('Not implemented - should be set by HandlerApi implementor'); }, viewContractState: (contractId, input) => { throw new Error('Not implemented - should be set by HandlerApi implementor'); }, write: (contractId, input) => { throw new Error('Not implemented - should be set by HandlerApi implementor'); }, refreshState: () => { throw new Error('Not implemented - should be set by HandlerApi implementor'); } }; this.vrf = new Vrf(this); this.useGas = this.useGas.bind(this); this.getBalance = this.getBalance.bind(this); } useGas(gas) { if (gas < 0) { throw new Error(`[RE:GNE] Gas number exception - gas < 0.`); } this.gasUsed += gas; if (this.gasUsed > this.gasLimit) { throw new Error(`[RE:OOG] Out of gas! Used: ${this.gasUsed}, limit: ${this.gasLimit}`); } } async getBalance(address, height) { if (!this._activeTx) { throw new Error('Cannot read balance - active tx is not set.'); } if (!this.block.height) { throw new Error('Cannot read balance - block height not set.'); } const effectiveHeight = height || this.block.height; // http://nyc-1.dev.arweave.net:1984/block/height/914387/wallet/M-mpNeJbg9h7mZ-uHaNsa5jwFFRAq0PsTkNWXJ-ojwI/balance return await fetch(`${this.evaluationOptions.walletBalanceUrl}block/height/${effectiveHeight}/wallet/${address}/balance`) .then((res) => { return res.ok ? res.text() : Promise.reject(res); }) .catch((error) => { var _a; throw new Error(`Unable to read wallet balance. ${error.status}. ${(_a = error.body) === null || _a === void 0 ? void 0 : _a.message}`); }); } } exports.SmartWeaveGlobal = SmartWeaveGlobal; // tslint:disable-next-line: max-classes-per-file class Transaction { constructor(smartWeaveGlobal) { this.smartWeaveGlobal = smartWeaveGlobal; } get id() { if (!this.smartWeaveGlobal._activeTx) { throw new Error('No current Tx'); } return this.smartWeaveGlobal._activeTx.id; } get owner() { if (!this.smartWeaveGlobal._activeTx) { throw new Error('No current Tx'); } return this.smartWeaveGlobal._activeTx.owner.address; } get target() { if (!this.smartWeaveGlobal._activeTx) { throw new Error('No current Tx'); } return this.smartWeaveGlobal._activeTx.recipient; } get tags() { if (!this.smartWeaveGlobal._activeTx) { throw new Error('No current Tx'); } return this.smartWeaveGlobal._activeTx.tags; } get quantity() { if (!this.smartWeaveGlobal._activeTx) { throw new Error('No current Tx'); } return this.smartWeaveGlobal._activeTx.quantity.winston; } get reward() { if (!this.smartWeaveGlobal._activeTx) { throw new Error('No current Tx'); } return this.smartWeaveGlobal._activeTx.fee.winston; } } // tslint:disable-next-line: max-classes-per-file class Block { constructor(smartWeaveGlobal) { this.smartWeaveGlobal = smartWeaveGlobal; } get height() { if (!this.smartWeaveGlobal._activeTx) { throw new Error('No current Tx'); } return this.smartWeaveGlobal._activeTx.block.height; } get indep_hash() { if (!this.smartWeaveGlobal._activeTx) { throw new Error('No current Tx'); } return this.smartWeaveGlobal._activeTx.block.id; } get timestamp() { if (!this.smartWeaveGlobal._activeTx) { throw new Error('No current tx'); } return this.smartWeaveGlobal._activeTx.block.timestamp; } } class Vrf { constructor(smartWeaveGlobal) { this.smartWeaveGlobal = smartWeaveGlobal; } get data() { return this.smartWeaveGlobal._activeTx.vrf; } // returns the original generated random number as a BigInt string; get value() { return this.smartWeaveGlobal._activeTx.vrf.bigint; } // returns a random value in a range from 1 to maxValue randomInt(maxValue) { if (!Number.isInteger(maxValue)) { throw new Error('Integer max value required for random integer generation'); } const result = (BigInt(this.smartWeaveGlobal._activeTx.vrf.bigint) % BigInt(maxValue)) + BigInt(1); if (result > Number.MAX_SAFE_INTEGER || result < Number.MIN_SAFE_INTEGER) { throw new Error('Random int cannot be cast to number'); } return Number(result); } } //# sourceMappingURL=smartweave-global.js.map /***/ }), /***/ 3633: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.arrayToHex = exports.getTag = void 0; function getTag(tx, name) { const tags = tx.get('tags'); for (const tag of tags) { // decoding tags can throw on invalid utf8 data. try { if (tag.get('name', { decode: true, string: true }) === name) { return tag.get('value', { decode: true, string: true }); } // eslint-disable-next-line no-empty } catch (e) { } } return false; } exports.getTag = getTag; function arrayToHex(arr) { let str = ''; for (const a of arr) { str += ('0' + a.toString(16)).slice(-2); } return str; } exports.arrayToHex = arrayToHex; //# sourceMappingURL=utils.js.map /***/ }), /***/ 9106: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Benchmark = void 0; class Benchmark { constructor() { this.start = Date.now(); this.end = null; // noop } static measure() { return new Benchmark(); } reset() { this.start = Date.now(); this.end = null; } stop() { this.end = Date.now(); } elapsed(rawValue = false) { if (this.end === null) { this.end = Date.now(); } const result = this.end - this.start; return rawValue ? result : `${(this.end - this.start).toFixed(0)}ms`; } } exports.Benchmark = Benchmark; //# sourceMappingURL=Benchmark.js.map /***/ }), /***/ 5913: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LoggerFactory = void 0; const ConsoleLoggerFactory_1 = __webpack_require__(4089); class LoggerFactory { constructor() { // not instantiable from outside } setOptions(newOptions, moduleName) { LoggerFactory.INST.setOptions(newOptions, moduleName); } getOptions(moduleName) { return LoggerFactory.INST.getOptions(moduleName); } logLevel(level, moduleName) { LoggerFactory.INST.logLevel(level, moduleName); } create(moduleName) { return LoggerFactory.INST.create(moduleName); } static use(logger) { LoggerFactory.INST = logger; } } exports.LoggerFactory = LoggerFactory; LoggerFactory.INST = new ConsoleLoggerFactory_1.ConsoleLoggerFactory(); //# sourceMappingURL=LoggerFactory.js.map /***/ }), /***/ 5629: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.lvlToOrder = exports.LogLevelOrder = void 0; exports.LogLevelOrder = { silly: 0, trace: 1, debug: 2, info: 3, warn: 4, error: 5, fatal: 6 }; function lvlToOrder(logLevel) { return exports.LogLevelOrder[logLevel]; } exports.lvlToOrder = lvlToOrder; //# sourceMappingURL=LoggerSettings.js.map /***/ }), /***/ 2393: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=WarpLogger.js.map /***/ }), /***/ 183: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* eslint-disable */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ConsoleLogger = void 0; const LoggerSettings_1 = __webpack_require__(5629); class ConsoleLogger { constructor(moduleName, settings) { this.moduleName = moduleName; this.settings = settings; } trace(message, ...optionalParams) { if (this.shouldLog('trace')) { // note: no 'trace' for console logger console.debug(this.message('trace', message), optionalParams); } } error(message, ...optionalParams) { if (this.shouldLog('error')) { console.error(this.message('error', message), optionalParams); } } info(message, ...optionalParams) { if (this.shouldLog('info')) { console.info(this.message('info', message), optionalParams); } } silly(message, ...optionalParams) { if (this.shouldLog('silly')) { // note: no silly level for console logger console.debug(this.message('silly', message), optionalParams); } } debug(message, ...optionalParams) { if (this.shouldLog('debug')) { console.debug(this.message('debug', message), optionalParams); } } warn(message, ...optionalParams) { if (this.shouldLog('warn')) { console.warn(this.message('warn', message), optionalParams); } } log(message, ...optionalParams) { if (this.shouldLog('info')) { console.info(this.message('info', message), optionalParams); } } fatal(message, ...optionalParams) { if (this.shouldLog('fatal')) { console.error(this.message('fatal', message), optionalParams); } } shouldLog(logLevel) { return (0, LoggerSettings_1.lvlToOrder)(logLevel) >= (0, LoggerSettings_1.lvlToOrder)(this.settings.minLevel); } setSettings(settings) { this.settings = settings; } message(lvl, message) { return `${new Date().toISOString()} ${lvl.toUpperCase()} [${this.moduleName}] ${message}`; } } exports.ConsoleLogger = ConsoleLogger; //# sourceMappingURL=ConsoleLogger.js.map /***/ }), /***/ 4089: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ConsoleLoggerFactory = void 0; const ConsoleLogger_1 = __webpack_require__(183); class ConsoleLoggerFactory { constructor() { this.registeredLoggers = {}; this.registeredOptions = {}; this.defOptions = { minLevel: 'info' }; this.setOptions = this.setOptions.bind(this); this.getOptions = this.getOptions.bind(this); this.create = this.create.bind(this); this.logLevel = this.logLevel.bind(this); } setOptions(newOptions, moduleName) { // FIXME: c/p from TsLogFactory... // if moduleName not specified if (!moduleName) { // update default options this.defOptions = newOptions; // update options for all already registered loggers Object.keys(this.registeredLoggers).forEach((key) => { this.registeredLoggers[key].setSettings({ ...this.registeredLoggers[key].settings, ...newOptions }); }); } else { // if logger already registered if (this.registeredLoggers[moduleName]) { // update its options this.registeredLoggers[moduleName].setSettings({ ...this.registeredLoggers[moduleName].settings, ...newOptions }); } else { // if logger not yet registered - save options that will be used for its creation this.registeredOptions[moduleName] = { ...this.defOptions, ...newOptions }; } } } getOptions(moduleName) { // FIXME: c/p from TsLogFactory... if (!moduleName) { return this.defOptions; } else { if (this.registeredLoggers[moduleName]) { return this.registeredLoggers[moduleName].settings; } else if (this.registeredOptions[moduleName]) { return this.registeredOptions[moduleName]; } else { return this.defOptions; } } } logLevel(level, moduleName) { // FIXME: c/p from TsLogFactory... this.setOptions({ minLevel: level }, moduleName); } create(moduleName = 'SWC') { if (!Object.prototype.hasOwnProperty.call(this.registeredLoggers, moduleName)) { this.registeredLoggers[moduleName] = new ConsoleLogger_1.ConsoleLogger(moduleName, this.getOptions(moduleName)); } return this.registeredLoggers[moduleName]; } } exports.ConsoleLoggerFactory = ConsoleLoggerFactory; //# sourceMappingURL=ConsoleLoggerFactory.js.map /***/ }), /***/ 7794: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheableExecutorFactory = void 0; const LoggerFactory_1 = __webpack_require__(5913); /** * An implementation of ExecutorFactory that adds caching capabilities */ class CacheableExecutorFactory { constructor(arweave, baseImplementation, cache) { this.arweave = arweave; this.baseImplementation = baseImplementation; this.cache = cache; this.logger = LoggerFactory_1.LoggerFactory.INST.create('CacheableExecutorFactory'); } async create(contractDefinition, evaluationOptions) { return await this.baseImplementation.create(contractDefinition, evaluationOptions); // warn: do not cache on the contractDefinition.srcTxId. This might look like a good optimisation // (as many contracts share the same source code), but unfortunately this is causing issues // with the same SwGlobal object being cached for all contracts with the same source code // (eg. SwGlobal.contract.id field - which of course should have different value for different contracts // that share the same source). // warn#2: cache key MUST be a combination of both txId and srcTxId - // as "evolve" feature changes the srcTxId for the given txId... // switching off caching for now // - https://github.com/redstone-finance/redstone-smartcontracts/issues/53 // probably should be cached on a lower level - i.e. either handler function (for js contracts) // or wasm module. } } exports.CacheableExecutorFactory = CacheableExecutorFactory; //# sourceMappingURL=CacheableExecutorFactory.js.map /***/ }), /***/ 4481: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DebuggableExecutorFactory = void 0; /** * An ExecutorFactory that allows to substitute original contract's source code. * Useful for debugging purposes (eg. to quickly add some console.logs in contract * or to test a fix or a new feature - without the need of redeploying a new contract on Arweave); * * Not meant to be used in production env! ;-) */ class DebuggableExecutorFactory { constructor(baseImplementation, // contract source code before default "normalization" sourceCode) { this.baseImplementation = baseImplementation; this.sourceCode = sourceCode; } async create(contractDefinition, evaluationOptions) { if (Object.prototype.hasOwnProperty.call(this.sourceCode, contractDefinition.txId)) { contractDefinition = { ...contractDefinition, src: this.sourceCode[contractDefinition.txId] }; } return await this.baseImplementation.create(contractDefinition, evaluationOptions); } } exports.DebuggableExecutorFactory = DebuggableExecutorFactory; //# sourceMappingURL=DebuggableExecutorFactor.js.map /***/ }), /***/ 2491: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Evolve = void 0; const LoggerFactory_1 = __webpack_require__(5913); const errors_1 = __webpack_require__(9925); function isEvolveCompatible(state) { if (!state) { return false; } const settings = evalSettings(state); return state.evolve !== undefined || settings.has('evolve'); } class Evolve { constructor() { this.logger = LoggerFactory_1.LoggerFactory.INST.create('Evolve'); this.modify = this.modify.bind(this); } async modify(state, executionContext) { const { definitionLoader, executorFactory } = executionContext.warp; const contractTxId = executionContext.contractDefinition.txId; const evolvedSrcTxId = Evolve.evolvedSrcTxId(state); const currentSrcTxId = executionContext.contractDefinition.srcTxId; if (evolvedSrcTxId) { this.logger.debug('Checking evolve:', { current: currentSrcTxId, evolvedSrcTxId }); if (currentSrcTxId !== evolvedSrcTxId) { try { // note: that's really nasty IMO - loading original contract definition, // but forcing different sourceTxId... this.logger.info('Evolving to: ', evolvedSrcTxId); const newContractDefinition = await definitionLoader.load(contractTxId, evolvedSrcTxId); const newHandler = (await executorFactory.create(newContractDefinition, executionContext.evaluationOptions)); //FIXME: side-effect... executionContext.contractDefinition = newContractDefinition; executionContext.handler = newHandler; executionContext.handler.initState(state); this.logger.debug('evolved to:', { evolve: evolvedSrcTxId, newSrcTxId: executionContext.contractDefinition.srcTxId, current: currentSrcTxId, txId: executionContext.contractDefinition.txId }); return executionContext; } catch (e) { throw new errors_1.SmartWeaveError(errors_1.SmartWeaveErrorType.CONTRACT_NOT_FOUND, { message: `Contract having txId: ${contractTxId} not found`, requestedTxId: contractTxId }); } } } return executionContext; } static evolvedSrcTxId(state) { if (!isEvolveCompatible(state)) { return undefined; } const settings = evalSettings(state); // note: from my understanding - this variable holds the id of the transaction with updated source code. const evolve = state.evolve || settings.get('evolve'); let canEvolve = state.canEvolve || settings.get('canEvolve'); // By default, contracts can evolve if there's not an explicit `false`. if (canEvolve === undefined || canEvolve === null) { canEvolve = true; } if (evolve && /[a-z0-9_-]{43}/i.test(evolve) && canEvolve) { return evolve; } return undefined; } } exports.Evolve = Evolve; function evalSettings(state) { // default - empty let settings = new Map(); if (state.settings) { // for Iterable format if (isIterable(state.settings)) { settings = new Map(state.settings); // for Object format } else if (isObject(state.settings)) { settings = new Map(Object.entries(state.settings)); } } return settings; } function isIterable(obj) { // checks for null and undefined if (obj == null) { return false; } return typeof obj[Symbol.iterator] === 'function'; } function isObject(obj) { return typeof obj === 'object' && obj !== null && !Array.isArray(obj); } //# sourceMappingURL=Evolve.js.map /***/ }), /***/ 9360: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ArweaveWrapper = void 0; const arweave_1 = __importDefault(__webpack_require__(7386)); const transaction_1 = __importDefault(__webpack_require__(7241)); const redstone_isomorphic_1 = __webpack_require__(9180); const WarpFactory_1 = __webpack_require__(8479); const LoggerFactory_1 = __webpack_require__(5913); class ArweaveWrapper { constructor(arweave) { this.arweave = arweave; this.logger = LoggerFactory_1.LoggerFactory.INST.create('ArweaveWrapper'); this.baseUrl = `${arweave.api.config.protocol}://${arweave.api.config.host}:${arweave.api.config.port}`; this.logger.debug('baseurl', this.baseUrl); } async warpGwInfo() { return await this.doFetchInfo(`${WarpFactory_1.WARP_GW_URL}/gateway/arweave/info`); } async warpGwBlock() { this.logger.debug('Calling warp gw block info'); return await this.doFetchInfo(`${WarpFactory_1.WARP_GW_URL}/gateway/arweave/block`); } async info() { return await this.doFetchInfo(`${this.baseUrl}/info`); } async gql(query, variables) { try { const data = JSON.stringify({ query: query, variables: variables }); const response = await fetch(`${this.baseUrl}/graphql`, { method: 'POST', body: data, headers: { 'Accept-Encoding': 'gzip, deflate, br', 'Content-Type': 'application/json', Accept: 'application/json' } }) .then((res) => { return res.ok ? res.json() : Promise.reject(res); }) .catch((error) => { var _a, _b; if ((_a = error.body) === null || _a === void 0 ? void 0 : _a.message) { this.logger.error(error.body.message); } throw new Error(`Unable to retrieve gql page. ${error.status}: ${(_b = error.body) === null || _b === void 0 ? void 0 : _b.message}`); }); return { data: response, status: 200 }; } catch (e) { this.logger.error('Error while loading gql', e); throw e; } } async tx(id) { const response = await fetch(`${this.baseUrl}/tx/${id}`) .then((res) => { return res.ok ? res.json() : Promise.reject(res); }) .catch((error) => { var _a, _b; if ((_a = error.body) === null || _a === void 0 ? void 0 : _a.message) { this.logger.error(error.body.message); } throw new Error(`Unable to retrieve tx ${id}. ${error.status}. ${(_b = error.body) === null || _b === void 0 ? void 0 : _b.message}`); }); return new transaction_1.default({ ...response }); } async txData(id) { // note: this is using arweave.net cache - // not very safe and clever, but fast... const response = await fetch(`${this.baseUrl}/${id}`); if (!response.ok) { this.logger.warn(`Unable to load data from arweave.net/${id} endpoint, falling back to arweave.js`); // fallback to arweave-js as a last resort.. const txData = (await this.arweave.transactions.getData(id, { decode: true })); return redstone_isomorphic_1.Buffer.from(txData); } else { const buffer = await response.arrayBuffer(); return redstone_isomorphic_1.Buffer.from(buffer); } } async txDataString(id) { const buffer = await this.txData(id); return arweave_1.default.utils.bufferToString(buffer); } async doFetchInfo(url) { try { const response = await fetch(url) .then((res) => { return res.ok ? res.json() : Promise.reject(res); }) .catch((error) => { var _a, _b; if ((_a = error.body) === null || _a === void 0 ? void 0 : _a.message) { this.logger.error(error.body.message); } throw new Error(`Unable to retrieve info. ${error.status}: ${(_b = error.body) === null || _b === void 0 ? void 0 : _b.message}`); }); return response; } catch (e) { this.logger.error('Error while loading info', e); throw e; } } } exports.ArweaveWrapper = ArweaveWrapper; //# sourceMappingURL=ArweaveWrapper.js.map /***/ }), /***/ 5082: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.indent = exports.stripTrailingSlash = exports.timeout = exports.descS = exports.desc = exports.ascS = exports.asc = exports.mapReviver = exports.mapReplacer = exports.deepCopy = exports.sleep = void 0; /* eslint-disable */ const cloneDeep_1 = __importDefault(__webpack_require__(361)); const fast_copy_1 = __importDefault(__webpack_require__(3346)); const sleep = (ms) => { return new Promise((resolve) => setTimeout(resolve, ms)); }; exports.sleep = sleep; const deepCopy = (input, useFastCopy = false) => { return useFastCopy ? (0, fast_copy_1.default)(input) : (0, cloneDeep_1.default)(input); }; exports.deepCopy = deepCopy; const mapReplacer = (key, value) => { if (value instanceof Map) { return { dataType: 'Map', value: Array.from(value.entries()) }; } else { return value; } }; exports.mapReplacer = mapReplacer; const mapReviver = (key, value) => { if (typeof value === 'object' && value !== null) { if (value.dataType === 'Map') { return new Map(value.value); } } return value; }; exports.mapReviver = mapReviver; const asc = (a, b) => a - b; exports.asc = asc; const ascS = (a, b) => +a - +b; exports.ascS = ascS; const desc = (a, b) => b - a; exports.desc = desc; const descS = (a, b) => +b - +a; exports.descS = descS; function timeout(s) { let timeoutId = null; const timeoutPromise = new Promise((resolve, reject) => { timeoutId = setTimeout(() => { clearTimeout(timeoutId); reject('timeout'); }, s * 1000); }); return { timeoutId, timeoutPromise }; } exports.timeout = timeout; function stripTrailingSlash(str) { return str.endsWith('/') ? str.slice(0, -1) : str; } exports.stripTrailingSlash = stripTrailingSlash; function indent(callDepth) { return ''.padEnd(callDepth * 2, ' '); } exports.indent = indent; //# sourceMappingURL=utils.js.map /***/ }), /***/ 6430: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var forEach = __webpack_require__(4029); var availableTypedArrays = __webpack_require__(3083); var callBound = __webpack_require__(1924); var $toString = callBound('Object.prototype.toString'); var hasToStringTag = __webpack_require__(6410)(); var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; var typedArrays = availableTypedArrays(); var $slice = callBound('String.prototype.slice'); var toStrTags = {}; var gOPD = __webpack_require__(882); var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); if (hasToStringTag && gOPD && getPrototypeOf) { forEach(typedArrays, function (typedArray) { if (typeof g[typedArray] === 'function') { var arr = new g[typedArray](); if (Symbol.toStringTag in arr) { var proto = getPrototypeOf(arr); var descriptor = gOPD(proto, Symbol.toStringTag); if (!descriptor) { var superProto = getPrototypeOf(proto); descriptor = gOPD(superProto, Symbol.toStringTag); } toStrTags[typedArray] = descriptor.get; } } }); } var tryTypedArrays = function tryAllTypedArrays(value) { var foundName = false; forEach(toStrTags, function (getter, typedArray) { if (!foundName) { try { var name = getter.call(value); if (name === typedArray) { foundName = name; } } catch (e) {} } }); return foundName; }; var isTypedArray = __webpack_require__(5692); module.exports = function whichTypedArray(value) { if (!isTypedArray(value)) { return false; } if (!hasToStringTag || !(Symbol.toStringTag in value)) { return $slice($toString(value), 8, -1); } return tryTypedArrays(value); }; /***/ }), /***/ 7605: /***/ (function(module, exports) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// GENERATED FILE. DO NOT EDIT. var loader = (function(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; exports.demangle = demangle; exports.instantiate = instantiate; exports.instantiateStreaming = instantiateStreaming; exports.instantiateSync = instantiateSync; // Runtime header offsets const ID_OFFSET = -8; const SIZE_OFFSET = -4; // Runtime ids const ARRAYBUFFER_ID = 0; const STRING_ID = 1; // const ARRAYBUFFERVIEW_ID = 2; // Runtime type information const ARRAYBUFFERVIEW = 1 << 0; const ARRAY = 1 << 1; const STATICARRAY = 1 << 2; // const SET = 1 << 3; // const MAP = 1 << 4; const VAL_ALIGN_OFFSET = 6; // const VAL_ALIGN = 1 << VAL_ALIGN_OFFSET; const VAL_SIGNED = 1 << 11; const VAL_FLOAT = 1 << 12; // const VAL_NULLABLE = 1 << 13; const VAL_MANAGED = 1 << 14; // const KEY_ALIGN_OFFSET = 15; // const KEY_ALIGN = 1 << KEY_ALIGN_OFFSET; // const KEY_SIGNED = 1 << 20; // const KEY_FLOAT = 1 << 21; // const KEY_NULLABLE = 1 << 22; // const KEY_MANAGED = 1 << 23; // Array(BufferView) layout const ARRAYBUFFERVIEW_BUFFER_OFFSET = 0; const ARRAYBUFFERVIEW_DATASTART_OFFSET = 4; const ARRAYBUFFERVIEW_BYTELENGTH_OFFSET = 8; const ARRAYBUFFERVIEW_SIZE = 12; const ARRAY_LENGTH_OFFSET = 12; const ARRAY_SIZE = 16; const E_NO_EXPORT_TABLE = "Operation requires compiling with --exportTable"; const E_NO_EXPORT_RUNTIME = "Operation requires compiling with --exportRuntime"; const F_NO_EXPORT_RUNTIME = () => { throw Error(E_NO_EXPORT_RUNTIME); }; const BIGINT = typeof BigUint64Array !== "undefined"; const THIS = Symbol(); const STRING_SMALLSIZE = 192; // break-even point in V8 const STRING_CHUNKSIZE = 1024; // mitigate stack overflow const utf16 = new TextDecoder("utf-16le", { fatal: true }); // != wtf16 /** polyfill for Object.hasOwn */ Object.hasOwn = Object.hasOwn || function (obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }; /** Gets a string from memory. */ function getStringImpl(buffer, ptr) { let len = new Uint32Array(buffer)[ptr + SIZE_OFFSET >>> 2] >>> 1; const wtf16 = new Uint16Array(buffer, ptr, len); if (len <= STRING_SMALLSIZE) return String.fromCharCode(...wtf16); try { return utf16.decode(wtf16); } catch { let str = "", off = 0; while (len - off > STRING_CHUNKSIZE) { str += String.fromCharCode(...wtf16.subarray(off, off += STRING_CHUNKSIZE)); } return str + String.fromCharCode(...wtf16.subarray(off)); } } /** Prepares the base module prior to instantiation. */ function preInstantiate(imports) { const extendedExports = {}; function getString(memory, ptr) { if (!memory) return ""; return getStringImpl(memory.buffer, ptr); } // add common imports used by stdlib for convenience const env = imports.env = imports.env || {}; env.abort = env.abort || function abort(msg, file, line, colm) { const memory = extendedExports.memory || env.memory; // prefer exported, otherwise try imported throw Error(`abort: ${getString(memory, msg)} at ${getString(memory, file)}:${line}:${colm}`); }; env.trace = env.trace || function trace(msg, n, ...args) { const memory = extendedExports.memory || env.memory; console.log(`trace: ${getString(memory, msg)}${n ? " " : ""}${args.slice(0, n).join(", ")}`); }; env.seed = env.seed || Date.now; imports.Math = imports.Math || Math; imports.Date = imports.Date || Date; return extendedExports; } /** Prepares the final module once instantiation is complete. */ function postInstantiate(extendedExports, instance) { const exports = instance.exports; const memory = exports.memory; const table = exports.table; const __new = exports.__new || F_NO_EXPORT_RUNTIME; const __pin = exports.__pin || F_NO_EXPORT_RUNTIME; const __unpin = exports.__unpin || F_NO_EXPORT_RUNTIME; const __collect = exports.__collect || F_NO_EXPORT_RUNTIME; const __rtti_base = exports.__rtti_base; const getRttiCount = __rtti_base ? arr => arr[__rtti_base >>> 2] : F_NO_EXPORT_RUNTIME; extendedExports.__new = __new; extendedExports.__pin = __pin; extendedExports.__unpin = __unpin; extendedExports.__collect = __collect; /** Gets the runtime type info for the given id. */ function getRttInfo(id) { const U32 = new Uint32Array(memory.buffer); if ((id >>>= 0) >= getRttiCount(U32)) throw Error(`invalid id: ${id}`); return U32[(__rtti_base + 4 >>> 2) + (id << 1)]; } /** Gets the runtime base id for the given id. */ function getRttBase(id) { const U32 = new Uint32Array(memory.buffer); if ((id >>>= 0) >= getRttiCount(U32)) throw Error(`invalid id: ${id}`); return U32[(__rtti_base + 4 >>> 2) + (id << 1) + 1]; } /** Gets and validate runtime type info for the given id for array like objects */ function getArrayInfo(id) { const info = getRttInfo(id); if (!(info & (ARRAYBUFFERVIEW | ARRAY | STATICARRAY))) throw Error(`not an array: ${id}, flags=${info}`); return info; } /** Gets the runtime alignment of a collection's values. */ function getValueAlign(info) { return 31 - Math.clz32(info >>> VAL_ALIGN_OFFSET & 31); // -1 if none } /** Gets the runtime alignment of a collection's keys. */ // function getKeyAlign(info) { // return 31 - Math.clz32((info >>> KEY_ALIGN_OFFSET) & 31); // -1 if none // } /** Allocates a new string in the module's memory and returns its pointer. */ function __newString(str) { if (str == null) return 0; const length = str.length; const ptr = __new(length << 1, STRING_ID); const U16 = new Uint16Array(memory.buffer); for (var i = 0, p = ptr >>> 1; i < length; ++i) U16[p + i] = str.charCodeAt(i); return ptr; } extendedExports.__newString = __newString; /** Allocates a new ArrayBuffer in the module's memory and returns its pointer. */ function __newArrayBuffer(buf) { if (buf == null) return 0; const bufview = new Uint8Array(buf); const ptr = __new(bufview.length, ARRAYBUFFER_ID); const U8 = new Uint8Array(memory.buffer); U8.set(bufview, ptr); return ptr; } extendedExports.__newArrayBuffer = __newArrayBuffer; /** Reads a string from the module's memory by its pointer. */ function __getString(ptr) { if (!ptr) return null; const buffer = memory.buffer; const id = new Uint32Array(buffer)[ptr + ID_OFFSET >>> 2]; if (id !== STRING_ID) throw Error(`not a string: ${ptr}`); return getStringImpl(buffer, ptr); } extendedExports.__getString = __getString; /** Gets the view matching the specified alignment, signedness and floatness. */ function getView(alignLog2, signed, float) { const buffer = memory.buffer; if (float) { switch (alignLog2) { case 2: return new Float32Array(buffer); case 3: return new Float64Array(buffer); } } else { switch (alignLog2) { case 0: return new (signed ? Int8Array : Uint8Array)(buffer); case 1: return new (signed ? Int16Array : Uint16Array)(buffer); case 2: return new (signed ? Int32Array : Uint32Array)(buffer); case 3: return new (signed ? BigInt64Array : BigUint64Array)(buffer); } } throw Error(`unsupported align: ${alignLog2}`); } /** Allocates a new array in the module's memory and returns its pointer. */ function __newArray(id, valuesOrCapacity = 0) { const input = valuesOrCapacity; const info = getArrayInfo(id); const align = getValueAlign(info); const isArrayLike = typeof input !== "number"; const length = isArrayLike ? input.length : input; const buf = __new(length << align, info & STATICARRAY ? id : ARRAYBUFFER_ID); let result; if (info & STATICARRAY) { result = buf; } else { __pin(buf); const arr = __new(info & ARRAY ? ARRAY_SIZE : ARRAYBUFFERVIEW_SIZE, id); __unpin(buf); const U32 = new Uint32Array(memory.buffer); U32[arr + ARRAYBUFFERVIEW_BUFFER_OFFSET >>> 2] = buf; U32[arr + ARRAYBUFFERVIEW_DATASTART_OFFSET >>> 2] = buf; U32[arr + ARRAYBUFFERVIEW_BYTELENGTH_OFFSET >>> 2] = length << align; if (info & ARRAY) U32[arr + ARRAY_LENGTH_OFFSET >>> 2] = length; result = arr; } if (isArrayLike) { const view = getView(align, info & VAL_SIGNED, info & VAL_FLOAT); const start = buf >>> align; if (info & VAL_MANAGED) { for (let i = 0; i < length; ++i) { view[start + i] = input[i]; } } else { view.set(input, start); } } return result; } extendedExports.__newArray = __newArray; /** Gets a live view on an array's values in the module's memory. Infers the array type from RTTI. */ function __getArrayView(arr) { const U32 = new Uint32Array(memory.buffer); const id = U32[arr + ID_OFFSET >>> 2]; const info = getArrayInfo(id); const align = getValueAlign(info); let buf = info & STATICARRAY ? arr : U32[arr + ARRAYBUFFERVIEW_DATASTART_OFFSET >>> 2]; const length = info & ARRAY ? U32[arr + ARRAY_LENGTH_OFFSET >>> 2] : U32[buf + SIZE_OFFSET >>> 2] >>> align; return getView(align, info & VAL_SIGNED, info & VAL_FLOAT).subarray(buf >>>= align, buf + length); } extendedExports.__getArrayView = __getArrayView; /** Copies an array's values from the module's memory. Infers the array type from RTTI. */ function __getArray(arr) { const input = __getArrayView(arr); const len = input.length; const out = new Array(len); for (let i = 0; i < len; i++) out[i] = input[i]; return out; } extendedExports.__getArray = __getArray; /** Copies an ArrayBuffer's value from the module's memory. */ function __getArrayBuffer(ptr) { const buffer = memory.buffer; const length = new Uint32Array(buffer)[ptr + SIZE_OFFSET >>> 2]; return buffer.slice(ptr, ptr + length); } extendedExports.__getArrayBuffer = __getArrayBuffer; /** Gets a function from poiner which contain table's index. */ function __getFunction(ptr) { if (!table) throw Error(E_NO_EXPORT_TABLE); const index = new Uint32Array(memory.buffer)[ptr >>> 2]; return table.get(index); } extendedExports.__getFunction = __getFunction; /** Copies a typed array's values from the module's memory. */ function getTypedArray(Type, alignLog2, ptr) { return new Type(getTypedArrayView(Type, alignLog2, ptr)); } /** Gets a live view on a typed array's values in the module's memory. */ function getTypedArrayView(Type, alignLog2, ptr) { const buffer = memory.buffer; const U32 = new Uint32Array(buffer); return new Type(buffer, U32[ptr + ARRAYBUFFERVIEW_DATASTART_OFFSET >>> 2], U32[ptr + ARRAYBUFFERVIEW_BYTELENGTH_OFFSET >>> 2] >>> alignLog2); } /** Attach a set of get TypedArray and View functions to the exports. */ function attachTypedArrayFunctions(ctor, name, align) { extendedExports[`__get${name}`] = getTypedArray.bind(null, ctor, align); extendedExports[`__get${name}View`] = getTypedArrayView.bind(null, ctor, align); } [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array].forEach(ctor => { attachTypedArrayFunctions(ctor, ctor.name, 31 - Math.clz32(ctor.BYTES_PER_ELEMENT)); }); if (BIGINT) { [BigUint64Array, BigInt64Array].forEach(ctor => { attachTypedArrayFunctions(ctor, ctor.name.slice(3), 3); }); } /** Tests whether an object is an instance of the class represented by the specified base id. */ function __instanceof(ptr, baseId) { const U32 = new Uint32Array(memory.buffer); let id = U32[ptr + ID_OFFSET >>> 2]; if (id <= getRttiCount(U32)) { do { if (id == baseId) return true; id = getRttBase(id); } while (id); } return false; } extendedExports.__instanceof = __instanceof; // Pull basic exports to extendedExports so code in preInstantiate can use them extendedExports.memory = extendedExports.memory || memory; extendedExports.table = extendedExports.table || table; // Demangle exports and provide the usual utility on the prototype return demangle(exports, extendedExports); } function isResponse(src) { return typeof Response !== "undefined" && src instanceof Response; } function isModule(src) { return src instanceof WebAssembly.Module; } /** Asynchronously instantiates an AssemblyScript module from anything that can be instantiated. */ async function instantiate(source, imports = {}) { if (isResponse(source = await source)) return instantiateStreaming(source, imports); const module = isModule(source) ? source : await WebAssembly.compile(source); const extended = preInstantiate(imports); const instance = await WebAssembly.instantiate(module, imports); const exports = postInstantiate(extended, instance); return { module, instance, exports }; } /** Synchronously instantiates an AssemblyScript module from a WebAssembly.Module or binary buffer. */ function instantiateSync(source, imports = {}) { const module = isModule(source) ? source : new WebAssembly.Module(source); const extended = preInstantiate(imports); const instance = new WebAssembly.Instance(module, imports); const exports = postInstantiate(extended, instance); return { module, instance, exports }; } /** Asynchronously instantiates an AssemblyScript module from a response, i.e. as obtained by `fetch`. */ async function instantiateStreaming(source, imports = {}) { if (!WebAssembly.instantiateStreaming) { return instantiate(isResponse(source = await source) ? source.arrayBuffer() : source, imports); } const extended = preInstantiate(imports); const result = await WebAssembly.instantiateStreaming(source, imports); const exports = postInstantiate(extended, result.instance); return { ...result, exports }; } /** Demangles an AssemblyScript module's exports to a friendly object structure. */ function demangle(exports, extendedExports = {}) { const setArgumentsLength = exports["__argumentsLength"] ? length => { exports["__argumentsLength"].value = length; } : exports["__setArgumentsLength"] || exports["__setargc"] || (() => { /* nop */ }); for (let internalName of Object.keys(exports)) { const elem = exports[internalName]; let parts = internalName.split("."); let curr = extendedExports; while (parts.length > 1) { let part = parts.shift(); if (!Object.hasOwn(curr, part)) curr[part] = {}; curr = curr[part]; } let name = parts[0]; let hash = name.indexOf("#"); if (hash >= 0) { const className = name.substring(0, hash); const classElem = curr[className]; if (typeof classElem === "undefined" || !classElem.prototype) { const ctor = function (...args) { return ctor.wrap(ctor.prototype.constructor(0, ...args)); }; ctor.prototype = { valueOf() { return this[THIS]; } }; ctor.wrap = function (thisValue) { return Object.create(ctor.prototype, { [THIS]: { value: thisValue, writable: false } }); }; if (classElem) Object.getOwnPropertyNames(classElem).forEach(name => Object.defineProperty(ctor, name, Object.getOwnPropertyDescriptor(classElem, name))); curr[className] = ctor; } name = name.substring(hash + 1); curr = curr[className].prototype; if (/^(get|set):/.test(name)) { if (!Object.hasOwn(curr, name = name.substring(4))) { let getter = exports[internalName.replace("set:", "get:")]; let setter = exports[internalName.replace("get:", "set:")]; Object.defineProperty(curr, name, { get() { return getter(this[THIS]); }, set(value) { setter(this[THIS], value); }, enumerable: true }); } } else { if (name === 'constructor') { (curr[name] = function (...args) { setArgumentsLength(args.length); return elem(...args); }).original = elem; } else { // instance method (curr[name] = function (...args) { // ! setArgumentsLength(args.length); return elem(this[THIS], ...args); }).original = elem; } } } else { if (/^(get|set):/.test(name)) { if (!Object.hasOwn(curr, name = name.substring(4))) { Object.defineProperty(curr, name, { get: exports[internalName.replace("set:", "get:")], set: exports[internalName.replace("get:", "set:")], enumerable: true }); } } else if (typeof elem === "function" && elem !== setArgumentsLength) { (curr[name] = (...args) => { setArgumentsLength(args.length); return elem(...args); }).original = elem; } else { curr[name] = elem; } } } return extendedExports; } var _default = { instantiate, instantiateSync, instantiateStreaming, demangle }; exports.default = _default; return "default" in exports ? exports.default : exports; })({}); if (true) !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { return loader; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); else {} /***/ }), /***/ 3083: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var possibleNames = [ 'BigInt64Array', 'BigUint64Array', 'Float32Array', 'Float64Array', 'Int16Array', 'Int32Array', 'Int8Array', 'Uint16Array', 'Uint32Array', 'Uint8Array', 'Uint8ClampedArray' ]; var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; module.exports = function availableTypedArrays() { var out = []; for (var i = 0; i < possibleNames.length; i++) { if (typeof g[possibleNames[i]] === 'function') { out[out.length] = possibleNames[i]; } } return out; }; /***/ }), /***/ 882: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var GetIntrinsic = __webpack_require__(210); var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); if ($gOPD) { try { $gOPD([], 'length'); } catch (e) { // IE 8 has a broken gOPD $gOPD = null; } } module.exports = $gOPD; /***/ }), /***/ 7568: /***/ (function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "Z": function() { return /* binding */ _asyncToGenerator; } /* harmony export */ }); function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } /***/ }), /***/ 9396: /***/ (function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "Z": function() { return /* binding */ _objectSpreadProps; } /* harmony export */ }); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpreadProps(target, source) { source = source != null ? source : {} if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty( target, key, Object.getOwnPropertyDescriptor(source, key) ); }); } return target; } /***/ }), /***/ 8597: /***/ (function(module) { "use strict"; module.exports = {"i8":"6.5.4"}; /***/ }), /***/ 2454: /***/ (function(module) { "use strict"; module.exports = JSON.parse('{"O_RDONLY":0,"O_WRONLY":1,"O_RDWR":2,"S_IFMT":61440,"S_IFREG":32768,"S_IFDIR":16384,"S_IFCHR":8192,"S_IFBLK":24576,"S_IFIFO":4096,"S_IFLNK":40960,"S_IFSOCK":49152,"O_CREAT":512,"O_EXCL":2048,"O_NOCTTY":131072,"O_TRUNC":1024,"O_APPEND":8,"O_DIRECTORY":1048576,"O_NOFOLLOW":256,"O_SYNC":128,"O_SYMLINK":2097152,"O_NONBLOCK":4,"S_IRWXU":448,"S_IRUSR":256,"S_IWUSR":128,"S_IXUSR":64,"S_IRWXG":56,"S_IRGRP":32,"S_IWGRP":16,"S_IXGRP":8,"S_IRWXO":7,"S_IROTH":4,"S_IWOTH":2,"S_IXOTH":1,"E2BIG":7,"EACCES":13,"EADDRINUSE":48,"EADDRNOTAVAIL":49,"EAFNOSUPPORT":47,"EAGAIN":35,"EALREADY":37,"EBADF":9,"EBADMSG":94,"EBUSY":16,"ECANCELED":89,"ECHILD":10,"ECONNABORTED":53,"ECONNREFUSED":61,"ECONNRESET":54,"EDEADLK":11,"EDESTADDRREQ":39,"EDOM":33,"EDQUOT":69,"EEXIST":17,"EFAULT":14,"EFBIG":27,"EHOSTUNREACH":65,"EIDRM":90,"EILSEQ":92,"EINPROGRESS":36,"EINTR":4,"EINVAL":22,"EIO":5,"EISCONN":56,"EISDIR":21,"ELOOP":62,"EMFILE":24,"EMLINK":31,"EMSGSIZE":40,"EMULTIHOP":95,"ENAMETOOLONG":63,"ENETDOWN":50,"ENETRESET":52,"ENETUNREACH":51,"ENFILE":23,"ENOBUFS":55,"ENODATA":96,"ENODEV":19,"ENOENT":2,"ENOEXEC":8,"ENOLCK":77,"ENOLINK":97,"ENOMEM":12,"ENOMSG":91,"ENOPROTOOPT":42,"ENOSPC":28,"ENOSR":98,"ENOSTR":99,"ENOSYS":78,"ENOTCONN":57,"ENOTDIR":20,"ENOTEMPTY":66,"ENOTSOCK":38,"ENOTSUP":45,"ENOTTY":25,"ENXIO":6,"EOPNOTSUPP":102,"EOVERFLOW":84,"EPERM":1,"EPIPE":32,"EPROTO":100,"EPROTONOSUPPORT":43,"EPROTOTYPE":41,"ERANGE":34,"EROFS":30,"ESPIPE":29,"ESRCH":3,"ESTALE":70,"ETIME":101,"ETIMEDOUT":60,"ETXTBSY":26,"EWOULDBLOCK":35,"EXDEV":18,"SIGHUP":1,"SIGINT":2,"SIGQUIT":3,"SIGILL":4,"SIGTRAP":5,"SIGABRT":6,"SIGIOT":6,"SIGBUS":10,"SIGFPE":8,"SIGKILL":9,"SIGUSR1":30,"SIGSEGV":11,"SIGUSR2":31,"SIGPIPE":13,"SIGALRM":14,"SIGTERM":15,"SIGCHLD":20,"SIGCONT":19,"SIGSTOP":17,"SIGTSTP":18,"SIGTTIN":21,"SIGTTOU":22,"SIGURG":16,"SIGXCPU":24,"SIGXFSZ":25,"SIGVTALRM":26,"SIGPROF":27,"SIGWINCH":28,"SIGIO":23,"SIGSYS":12,"SSL_OP_ALL":2147486719,"SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION":262144,"SSL_OP_CIPHER_SERVER_PREFERENCE":4194304,"SSL_OP_CISCO_ANYCONNECT":32768,"SSL_OP_COOKIE_EXCHANGE":8192,"SSL_OP_CRYPTOPRO_TLSEXT_BUG":2147483648,"SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS":2048,"SSL_OP_EPHEMERAL_RSA":0,"SSL_OP_LEGACY_SERVER_CONNECT":4,"SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER":32,"SSL_OP_MICROSOFT_SESS_ID_BUG":1,"SSL_OP_MSIE_SSLV2_RSA_PADDING":0,"SSL_OP_NETSCAPE_CA_DN_BUG":536870912,"SSL_OP_NETSCAPE_CHALLENGE_BUG":2,"SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG":1073741824,"SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG":8,"SSL_OP_NO_COMPRESSION":131072,"SSL_OP_NO_QUERY_MTU":4096,"SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION":65536,"SSL_OP_NO_SSLv2":16777216,"SSL_OP_NO_SSLv3":33554432,"SSL_OP_NO_TICKET":16384,"SSL_OP_NO_TLSv1":67108864,"SSL_OP_NO_TLSv1_1":268435456,"SSL_OP_NO_TLSv1_2":134217728,"SSL_OP_PKCS1_CHECK_1":0,"SSL_OP_PKCS1_CHECK_2":0,"SSL_OP_SINGLE_DH_USE":1048576,"SSL_OP_SINGLE_ECDH_USE":524288,"SSL_OP_SSLEAY_080_CLIENT_DH_BUG":128,"SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG":0,"SSL_OP_TLS_BLOCK_PADDING_BUG":512,"SSL_OP_TLS_D5_BUG":256,"SSL_OP_TLS_ROLLBACK_BUG":8388608,"ENGINE_METHOD_DSA":2,"ENGINE_METHOD_DH":4,"ENGINE_METHOD_RAND":8,"ENGINE_METHOD_ECDH":16,"ENGINE_METHOD_ECDSA":32,"ENGINE_METHOD_CIPHERS":64,"ENGINE_METHOD_DIGESTS":128,"ENGINE_METHOD_STORE":256,"ENGINE_METHOD_PKEY_METHS":512,"ENGINE_METHOD_PKEY_ASN1_METHS":1024,"ENGINE_METHOD_ALL":65535,"ENGINE_METHOD_NONE":0,"DH_CHECK_P_NOT_SAFE_PRIME":2,"DH_CHECK_P_NOT_PRIME":1,"DH_UNABLE_TO_CHECK_GENERATOR":4,"DH_NOT_SUITABLE_GENERATOR":8,"NPN_ENABLED":1,"RSA_PKCS1_PADDING":1,"RSA_SSLV23_PADDING":2,"RSA_NO_PADDING":3,"RSA_PKCS1_OAEP_PADDING":4,"RSA_X931_PADDING":5,"RSA_PKCS1_PSS_PADDING":6,"POINT_CONVERSION_COMPRESSED":2,"POINT_CONVERSION_UNCOMPRESSED":4,"POINT_CONVERSION_HYBRID":6,"F_OK":0,"R_OK":4,"W_OK":2,"X_OK":1,"UV_UDP_REUSEADDR":4}'); /***/ }), /***/ 8575: /***/ (function(module) { "use strict"; module.exports = JSON.parse('{"block":"block_type","loop":"block_type","if":"block_type","br":"varuint32","br_if":"varuint32","br_table":"br_table","call":"varuint32","call_indirect":"call_indirect","get_local":"varuint32","set_local":"varuint32","tee_local":"varuint32","get_global":"varuint32","set_global":"varuint32","load":"memory_immediate","load8_s":"memory_immediate","load8_u":"memory_immediate","load16_s":"memory_immediate","load16_u":"memory_immediate","load32_s":"memory_immediate","load32_u":"memory_immediate","store":"memory_immediate","store8":"memory_immediate","store16":"memory_immediate","store32":"memory_immediate","current_memory":"varuint1","grow_memory":"varuint1","i32":"varint32","i64":"varint64","f32":"uint32","f64":"uint64"}'); /***/ }), /***/ 5936: /***/ (function(module) { "use strict"; module.exports = JSON.parse('{"start":0,"type":{"params":{"DEFAULT":0},"return_type":{"DEFAULT":0}},"import":0,"code":{"locals":{"DEFAULT":1},"code":{"get_local":120,"set_local":120,"tee_local":120,"get_global":120,"set_global":120,"load8_s":120,"load8_u":120,"load16_s":120,"load16_u":120,"load32_s":120,"load32_u":120,"load":120,"store8":120,"store16":120,"store32":120,"store":120,"grow_memory":10000,"current_memory":100,"nop":1,"block":1,"loop":1,"if":1,"then":90,"else":90,"br":90,"br_if":90,"br_table":120,"return":90,"call":90,"call_indirect":10000,"const":1,"add":45,"sub":45,"mul":45,"div_s":36000,"div_u":36000,"rem_s":36000,"rem_u":36000,"and":45,"or":45,"xor":45,"shl":67,"shr_u":67,"shr_s":67,"rotl":90,"rotr":90,"eq":45,"eqz":45,"ne":45,"lt_s":45,"lt_u":45,"le_s":45,"le_u":45,"gt_s":45,"gt_u":45,"ge_s":45,"ge_u":45,"clz":45,"ctz":45,"popcnt":45,"drop":120,"select":120,"unreachable":1}},"data":0}'); /***/ }) }]);